Worked on a single timesharing and generates a single Q-transform
        spectrogram
430001
def get_spectrogram(self):
        """"""
        args = self.args

        asd = self.timeseries[0].asd().value
        if (asd.min() == 0):
            self.log(0, 'Input data has a zero in ASD. '
                     'Q-transform not possible.')
            self.got_error = True
            qtrans = None
        else:
            gps = self.qxfrm_args['gps']
            outseg = Segment(gps, gps).protract(args.plot[self.plot_num])

            # This section tries to optimize the amount of data that is
            # processed and the time resolution needed to create a good
            # image. NB:For each time span specified
            # NB: the timeseries h enough data for the longest plot
            inseg = outseg.protract(4) & self.timeseries[0].span
            proc_ts = self.timeseries[0].crop(*inseg)

            #  time resolution is calculated to provide about 4 times
            # the number of output pixels for interpolation
            tres = float(outseg.end - outseg.start) / 4 / self.args.nx
            self.qxfrm_args['tres'] = tres
            self.qxfrm_args['search'] = int(len(proc_ts) * proc_ts.dt.value)

            self.log(3, 'Q-transform arguments:')
            self.log(3, '{0:>15s} = {1}'.format('outseg', outseg))
            for key in sorted(self.qxfrm_args):
                self.log(3, '{0:>15s} = {1}'.format(key, self.qxfrm_args[key]))

            qtrans = proc_ts.q_transform(outseg=outseg, **self.qxfrm_args)

            if args.ymin is None:  # set before Spectrogram.make_plot
                args.ymin = qtrans.yspan[0]

        return qtrans
255903
function quantizeAndInverse(zz, dataOut, dataIn) {
    const qt = component.quantizationTable;
    let v0;
    let v1;
    let v2;
    let v3;
    let v4;
    let v5;
    let v6;
    let v7;
    let t;
    const p = dataIn;
    let i;

    // dequant
    for (i = 0; i < 64; i++) {
      p[i] = zz[i] * qt[i];
    }

    // inverse DCT on rows
    for (i = 0; i < 8; ++i) {
      const row = 8 * i;

      // check for all-zero AC coefficients
      if (p[1 + row] === 0 && p[2 + row] === 0 && p[3 + row] === 0 &&
        p[4 + row] === 0 && p[5 + row] === 0 && p[6 + row] === 0 &&
        p[7 + row] === 0) {
        t = ((dctSqrt2 * p[0 + row]) + 512) >> 10;
        p[0 + row] = t;
        p[1 + row] = t;
        p[2 + row] = t;
        p[3 + row] = t;
        p[4 + row] = t;
        p[5 + row] = t;
        p[6 + row] = t;
        p[7 + row] = t;
        continue; // eslint-disable-line no-continue
      }

      // stage 4
      v0 = ((dctSqrt2 * p[0 + row]) + 128) >> 8;
      v1 = ((dctSqrt2 * p[4 + row]) + 128) >> 8;
      v2 = p[2 + row];
      v3 = p[6 + row];
      v4 = ((dctSqrt1d2 * (p[1 + row] - p[7 + row])) + 128) >> 8;
      v7 = ((dctSqrt1d2 * (p[1 + row] + p[7 + row])) + 128) >> 8;
      v5 = p[3 + row] << 4;
      v6 = p[5 + row] << 4;

      // stage 3
      t = (v0 - v1 + 1) >> 1;
      v0 = (v0 + v1 + 1) >> 1;
      v1 = t;
      t = ((v2 * dctSin6) + (v3 * dctCos6) + 128) >> 8;
      v2 = ((v2 * dctCos6) - (v3 * dctSin6) + 128) >> 8;
      v3 = t;
      t = (v4 - v6 + 1) >> 1;
      v4 = (v4 + v6 + 1) >> 1;
      v6 = t;
      t = (v7 + v5 + 1) >> 1;
      v5 = (v7 - v5 + 1) >> 1;
      v7 = t;

      // stage 2
      t = (v0 - v3 + 1) >> 1;
      v0 = (v0 + v3 + 1) >> 1;
      v3 = t;
      t = (v1 - v2 + 1) >> 1;
      v1 = (v1 + v2 + 1) >> 1;
      v2 = t;
      t = ((v4 * dctSin3) + (v7 * dctCos3) + 2048) >> 12;
      v4 = ((v4 * dctCos3) - (v7 * dctSin3) + 2048) >> 12;
      v7 = t;
      t = ((v5 * dctSin1) + (v6 * dctCos1) + 2048) >> 12;
      v5 = ((v5 * dctCos1) - (v6 * dctSin1) + 2048) >> 12;
      v6 = t;

      // stage 1
      p[0 + row] = v0 + v7;
      p[7 + row] = v0 - v7;
      p[1 + row] = v1 + v6;
      p[6 + row] = v1 - v6;
      p[2 + row] = v2 + v5;
      p[5 + row] = v2 - v5;
      p[3 + row] = v3 + v4;
      p[4 + row] = v3 - v4;
    }

    // inverse DCT on columns
    for (i = 0; i < 8; ++i) {
      const col = i;

      // check for all-zero AC coefficients
      if (p[(1 * 8) + col] === 0 && p[(2 * 8) + col] === 0 && p[(3 * 8) + col] === 0 &&
        p[(4 * 8) + col] === 0 && p[(5 * 8) + col] === 0 && p[(6 * 8) + col] === 0 &&
        p[(7 * 8) + col] === 0) {
        t = ((dctSqrt2 * dataIn[i + 0]) + 8192) >> 14;
        p[(0 * 8) + col] = t;
        p[(1 * 8) + col] = t;
        p[(2 * 8) + col] = t;
        p[(3 * 8) + col] = t;
        p[(4 * 8) + col] = t;
        p[(5 * 8) + col] = t;
        p[(6 * 8) + col] = t;
        p[(7 * 8) + col] = t;
        continue; // eslint-disable-line no-continue
      }

      // stage 4
      v0 = ((dctSqrt2 * p[(0 * 8) + col]) + 2048) >> 12;
      v1 = ((dctSqrt2 * p[(4 * 8) + col]) + 2048) >> 12;
      v2 = p[(2 * 8) + col];
      v3 = p[(6 * 8) + col];
      v4 = ((dctSqrt1d2 * (p[(1 * 8) + col] - p[(7 * 8) + col])) + 2048) >> 12;
      v7 = ((dctSqrt1d2 * (p[(1 * 8) + col] + p[(7 * 8) + col])) + 2048) >> 12;
      v5 = p[(3 * 8) + col];
      v6 = p[(5 * 8) + col];

      // stage 3
      t = (v0 - v1 + 1) >> 1;
      v0 = (v0 + v1 + 1) >> 1;
      v1 = t;
      t = ((v2 * dctSin6) + (v3 * dctCos6) + 2048) >> 12;
      v2 = ((v2 * dctCos6) - (v3 * dctSin6) + 2048) >> 12;
      v3 = t;
      t = (v4 - v6 + 1) >> 1;
      v4 = (v4 + v6 + 1) >> 1;
      v6 = t;
      t = (v7 + v5 + 1) >> 1;
      v5 = (v7 - v5 + 1) >> 1;
      v7 = t;

      // stage 2
      t = (v0 - v3 + 1) >> 1;
      v0 = (v0 + v3 + 1) >> 1;
      v3 = t;
      t = (v1 - v2 + 1) >> 1;
      v1 = (v1 + v2 + 1) >> 1;
      v2 = t;
      t = ((v4 * dctSin3) + (v7 * dctCos3) + 2048) >> 12;
      v4 = ((v4 * dctCos3) - (v7 * dctSin3) + 2048) >> 12;
      v7 = t;
      t = ((v5 * dctSin1) + (v6 * dctCos1) + 2048) >> 12;
      v5 = ((v5 * dctCos1) - (v6 * dctSin1) + 2048) >> 12;
      v6 = t;

      // stage 1
      p[(0 * 8) + col] = v0 + v7;
      p[(7 * 8) + col] = v0 - v7;
      p[(1 * 8) + col] = v1 + v6;
      p[(6 * 8) + col] = v1 - v6;
      p[(2 * 8) + col] = v2 + v5;
      p[(5 * 8) + col] = v2 - v5;
      p[(3 * 8) + col] = v3 + v4;
      p[(4 * 8) + col] = v3 - v4;
    }

    // convert to 8-bit integers
    for (i = 0; i < 64; ++i) {
      const sample = 128 + ((p[i] + 8) >> 4);
      if (sample < 0) {
        dataOut[i] = 0;
      } else if (sample > 0XFF) {
        dataOut[i] = 0xFF;
      } else {
        dataOut[i] = sample;
      }
    }
  }
894364
def _split_sequences_singletraj(dtraj, nstates, lag):
    
    sall = [[] for _ in range(nstates)]
    res_states = []
    res_seqs = []

    for t in range(len(dtraj)-lag):
        sall[dtraj[t]].append(dtraj[t+lag])

    for i in range(nstates):
        if len(sall[i]) > 0:
            res_states.append(i)
            res_seqs.append(np.array(sall[i]))
    return res_states, res_seqs
413859
def _call_qc_transform_pairs(n, ispacing, ishift, fI, fC, r, r_def, reim):
    """
    print('* QC: Input transform-pairs:')
    print('  fC: x-range defined through ``n``, ``spacing``, ``shift``, and ' +
          '``r``-parameters; b-range defined through ``r``-parameter.')
    print('  fI: x- and b-range defined through ``n``, ``spacing``' +
          ', ``shift``, and ``r_def``-parameters.')

    # Calculate min/max k, from minimum and maximum spacing/shift
    minspace = np.arange(*ispacing).min()
    maxspace = np.arange(*ispacing).max()
    minshift = np.arange(*ishift).min()
    maxshift = np.arange(*ishift).max()

    maxbase = np.exp(maxspace*(n//2) + maxshift)
    minbase = np.exp(maxspace*(-n//2+1) + minshift)

    # For fC-r  (k defined with same amount of points as r)
    kmax = maxbase/r.min()
    kmin = minbase/r.max()
    k = np.logspace(np.log10(kmin), np.log10(kmax) + minspace, r.size)

    # For fI-r
    rI = np.logspace(np.log10(1/maxbase) - r_def[0],
                     np.log10(1/minbase) + r_def[1], r_def[2]*n)
    kmaxI = maxbase/rI.min()
    kminI = minbase/rI.max()
    kI = np.logspace(np.log10(kminI), np.log10(kmaxI) + minspace,
                     r_def[2]*n)

    # Plot QC
    fig, axs = plt.subplots(figsize=(9.5, 6), nrows=2, ncols=2,
                            num="Transform pairs")
    axs = axs.ravel()
    plt.subplots_adjust(wspace=.3, hspace=.4)

    _plot_transform_pairs(fC, r, k, axs[:2], 'fC')
    if reim == np.real:
        tit = 'RE(fI)'
    else:
        tit = 'IM(fI)'
    _plot_transform_pairs(fI, rI, kI, axs[2:], tit)

    fig.canvas.draw()  # To force draw in notebook while running
    plt.show()
1295568
def fingerprint(channel_samples: list, Fs: int = DEFAULT_FS,
                wsize: int = DEFAULT_WINDOW_SIZE,
                wratio: Union[int, float] = DEFAULT_OVERLAP_RATIO,
                fan_value: int = DEFAULT_FAN_VALUE,
                amp_min: Union[int, float] = DEFAULT_AMP_MIN)-> Iterator[tuple]:
    
    # FFT the signal and extract frequency components
    arr2D = mlab.specgram(
        channel_samples,
        NFFT=wsize,
        Fs=Fs,
        window=mlab.window_hanning,
        noverlap=int(wsize * wratio))[0]

    arr2D = 10 * np.log10(arr2D)

    arr2D[arr2D == -np.inf] = 0  # replace infs with zeros

    # find local maxima
    local_maxima = get_2D_peaks(arr2D, plot=False, amp_min=amp_min)

    # return hashes
    return generate_hashes(local_maxima, fan_value=fan_value)
943987
def generate_parallel(samples, run_parallel):
    
    to_analyze, extras = _split_samples_by_qc(samples)
    qced = run_parallel("pipeline_summary", to_analyze)
    samples = _combine_qc_samples(qced) + extras
    qsign_info = run_parallel("qsignature_summary", [samples])
    metadata_file = _merge_metadata([samples])
    summary_file = write_project_summary(samples, qsign_info)
    out = []
    for data in samples:
        if "summary" not in data[0]:
            data[0]["summary"] = {}
        data[0]["summary"]["project"] = summary_file
        data[0]["summary"]["metadata"] = metadata_file
        if qsign_info:
            data[0]["summary"]["mixup_check"] = qsign_info[0]["out_dir"]
        out.append(data)
    out = _add_researcher_summary(out, summary_file)
    # MultiQC must be run after all file outputs are set:
    return [[utils.to_single_data(d)] for d in run_parallel("multiqc_summary", [out])]
891765
def _spectrogram_mono(self, x):
        ''''''
        x = K.permute_dimensions(x, [0, 2, 1])
        x = K.expand_dims(x, 3)  # add a dummy dimension (channel axis)
        subsample = (self.n_hop, 1)
        output_real = K.conv2d(x, self.dft_real_kernels,
                               strides=subsample,
                               padding=self.padding,
                               data_format='channels_last')
        output_imag = K.conv2d(x, self.dft_imag_kernels,
                               strides=subsample,
                               padding=self.padding,
                               data_format='channels_last')
        output = output_real ** 2 + output_imag ** 2
        # now shape is (batch_sample, n_frame, 1, freq)
        if self.image_data_format == 'channels_last':
            output = K.permute_dimensions(output, [0, 3, 1, 2])
        else:
            output = K.permute_dimensions(output, [0, 2, 3, 1])
        return output
964822
def runMultiprocessNoiseExperiment(resultName, repeat, numWorkers,
                                   appendResults, **kwargs):
  
  experiments = [{}]
  for key, values in kwargs.items():
    if type(values) is list:
      newExperiments = []
      for experiment in experiments:
        for val in values:
          newExperiment = copy(experiment)
          newExperiment[key] = val
          newExperiments.append(newExperiment)
      experiments = newExperiments
    else:
      [a.__setitem__(key, values) for a in experiments]

  newExperiments = []
  for experiment in experiments:
    for _ in xrange(repeat):
      newExperiments.append(copy(experiment))
  experiments = newExperiments

  return runExperiments(experiments, resultName, numWorkers, appendResults)
546469
def qteKeyPress(self, msgObj):
        
        # Unpack the data structure.
        (srcObj, keysequence, macroName) = msgObj.data

        # Append the last QKeyEvent object to the so far recorded
        # sequence. Note that both ``keysequence`` and
        # ``self.recorded_keysequence`` are ``QtmacsKeysequence``
        # instances.
        last_key = keysequence.toQKeyEventList()[-1]
        self.recorded_keysequence.appendQKeyEvent(last_key)
1353089
def getPyBrainDataSetScalarEncoder(sequence, nTrain, encoderInput, encoderOutput,
                                   predictionStep=1, useTimeOfDay=True, useDayOfWeek=True):
  
  print "generate a pybrain dataset of sequences"
  print "the training data contains ", str(nTrain-predictionStep), "records"

  if encoderInput is None:
    inDim = 1 + int(useTimeOfDay) + int(useDayOfWeek)
  else:
    inDim = encoderInput.n + int(useTimeOfDay) + int(useDayOfWeek)

  if encoderOutput is None:
    outDim = 1
  else:
    outDim = encoderOutput.n

  ds = SequentialDataSet(inDim, outDim)
  if useTimeOfDay:
    print "include time of day as input field"
  if useDayOfWeek:
    print "include day of week as input field"

  for i in xrange(nTrain-predictionStep):

    sample = getSingleSample(i, sequence, useTimeOfDay, useDayOfWeek)

    if encoderOutput is None:
      dataSDROutput = [sequence['normdata'][i+predictionStep]]
    else:
      dataSDROutput = encoderOutput.encode(sequence['data'][i+predictionStep])


    ds.addSample(sample, dataSDROutput)

  return ds
204873
function buildSample (sampleNumber, rawData, sendCounts) {
  let sample;
  if (sendCounts) {
    sample = newSampleNoScale(sampleNumber);
    sample.channelDataCounts = rawData;
  } else {
    sample = newSample(sampleNumber);
    for (let j = 0; j < k.OBCINumberOfChannelsGanglion; j++) {
      sample.channelData.push(rawData[j] * k.OBCIGanglionScaleFactorPerCountVolts);
    }
  }
  sample.timestamp = Date.now();
  return sample;
}
1078687
def _single_cluster(c, data, out_file, args):
    
    valid, ann = 0, 0
    raw_file = None
    freq = defaultdict()
    [freq.update({s.keys()[0]: s.values()[0]}) for s in data[0][c]['freq']]
    names = [s.keys()[0] for s in data[0][c]['seqs']]
    seqs = [s.values()[0] for s in data[0][c]['seqs']]
    loci = data[0][c]['loci']

    if loci[0][3] - loci[0][2] > 500:
        logger.info("locus bigger > 500 nt, skipping: %s" % loci)
        return valid, ann, {}
    if not file_exists(out_file):
        if args.razer:
            logger.debug("map with razer all sequences to all loci %s " % loci)
            map_to_precursors(seqs, names, {loci[0][0]: [loci[0][0:5]]}, out_file, args)
        else:
            logger.debug("map with biopython fn all sequences to all loci %s " % loci)
            if args.debug:
                raw_file = out_file
            out_file = map_to_precursor_biopython(seqs, names, loci[0][0:5], args)

    logger.debug("plot sequences on loci")
    df = _convert_to_df(out_file, freq, raw_file)
    if df:
        valid, ann = _make(data[0][c])

    return valid, ann, df
581732
def get_spectrogram(self):
    '''
     
    '''

    return self._spec_power(self._spec_fft(  self._sigProc( self._reshape( self.complex_data() )) ))
1243074
def frame_generator(frame_duration_ms, audio, sample_rate):
    
    n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)
    offset = 0
    timestamp = 0.0
    duration = (float(n) / sample_rate) / 2.0
    while offset + n < len(audio):
        yield Frame(audio[offset:offset + n], timestamp, duration)
        timestamp += duration
        offset += n
842936
def add_transient(d, data, u, v, w, l1, m1, i, s, dm=0, dt=1):
    

    ang = lambda ch: l1 * u * d['freq'][ch]/d['freq_orig'][0] + m1 * v * d['freq'][ch]/d['freq_orig'][0]
    delay = lambda ch: n.round(4.1488e-3 * dm * (d['freq'][ch]**(-2) - d['freq'][-1]**(-2))/d['inttime'], 0).astype(int)

    #snr_ideal = s/(data[i].real.std()/n.sqrt(d['npol']*d['nbl']*d['nchan']))
    #logger.info('SNR of source with system brightness %.1f = %d (idealized; ok at low SNR)' % (s, int(snr_ideal)))

    for ch in range(d['nchan']):
        data[i+delay(ch):i+delay(ch)+dt, :, ch] += s * n.exp(2j*n.pi*ang(ch)[None,:,None])
62578
def bandpass(ts, low_hz, high_hz, order=3):
    """"""
    orig_ndim = ts.ndim
    if ts.ndim is 1:
        ts = ts[:, np.newaxis]
    channels = ts.shape[1]
    fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0])
    nyq = 0.5 * fs
    low = low_hz/nyq
    high = high_hz/nyq
    b, a = signal.butter(order, [low, high], btype='band')
    if not np.all(np.abs(np.roots(a)) < 1.0):
        raise ValueError('Filter will not be stable with these values.')
    dtype = ts.dtype
    output = np.zeros((len(ts), channels), dtype)
    for i in range(channels):
        output[:, i] = signal.filtfilt(b, a, ts[:, i])
    if orig_ndim is 1:
        output = output[:, 0]
    return Timeseries(output, ts.tspan, labels=ts.labels)
738432
def featurize(self, audio_clip, overwrite=False, save_feature_as_csvfile=False):
        
        return spectrogram_from_file(
            audio_clip, step=self.step, window=self.window,
            max_freq=self.max_freq, overwrite=overwrite,
            save_feature_as_csvfile=save_feature_as_csvfile)