Resamples advLIGO noise PSD to 4096 Hz
484523
def load_psd():
    
    # psd has freq resolution = 1/3 with 6145 samples
    psd = np.loadtxt("ZERO_DET_high_P_PSD.txt")[:,1]
    down_factor = 3
    pad_size = int(np.ceil(float(psd.size)/down_factor)*down_factor - psd.size)
    psd_padded = np.append(psd, np.zeros(pad_size)*np.NaN)
    psd = sp.nanmean(psd_padded.reshape(-1,down_factor), axis=1)
    # now dF = 1
    # length of psd = 2048
    return psd
9017
def noisepickle(d, data, u, v, w, chunk=200):
    

    if d['savenoise']:
        noisefile = getnoisefile(d)

        if os.path.exists(noisefile):
            logger.warn('noisefile %s already exists' % noisefile)
        else:
            nints = len(data)
            chunk = min(chunk, nints)  # ensure at least one measurement
            results = []

            rr = range(0, nints, chunk)
            if len(rr) == 1: rr.append(1)   # hack. need to make sure it iterates for nints=1 case
            for i in range(len(rr)-1):
                imid = (rr[i]+rr[i+1])/2
                noiseperbl = estimate_noiseperbl(data[rr[i]:rr[i+1]])
                imstd = sample_image(d, data, u, v, w, imid, verbose=0).std()
                zerofrac = float(len(n.where(data[rr[i]:rr[i+1]] == 0j)[0]))/data[rr[i]:rr[i+1]].size
                results.append( (d['segment'], noiseperbl, zerofrac, imstd) )

            with open(noisefile, 'a') as pkl:
                pickle.dump(results, pkl)
            logger.info('Wrote %d noise measurement%s to %s.' % (len(results), 's'[:len(results)-1], noisefile))
1125720
def get_r128_loudness(audio_filepaths, *, calc_peak=True, enable_ffmpeg_threading=True, ffmpeg_path=None):
  
  logger().info("Analyzing loudness of file%s %s..." % ("s" if (len(audio_filepaths) > 1) else "",
                                                        ", ".join("'%s'" % (audio_filepath) for audio_filepath in audio_filepaths)))

  # build command line
  cmd = [ffmpeg_path or "ffmpeg",
         "-hide_banner", "-nostats"]
  for i, audio_filepath in enumerate(audio_filepaths):
    if not enable_ffmpeg_threading:
      cmd.extend(("-threads:%u" % (i), "1"))  # single decoding thread
    cmd.extend(("-i", audio_filepath))
  if (get_ffmpeg_lib_versions()["libavfilter"] >= 0x06526400) and (not enable_ffmpeg_threading):
    cmd.extend(("-filter_threads", "1"))  # single filter thread
  cmd.extend(("-map", "a"))
  ebur128_filter_params = {"framelog": "verbose"}
  aformat_r128_filter_params = {"sample_fmts": "s16",
                                "sample_rates": "48000",
                                "channel_layouts": "stereo"}
  aformat_rg_filter_params = {"sample_fmts": "s16"}
  filter_chain = []
  if len(audio_filepaths) > 1:
    cmd.append("-filter_complex")
    for i in range(len(audio_filepaths)):
      if calc_peak:
        filter_chain.append("[%u:a]asplit[a_rg_in_%u][a_r128_in_%u]" % (i, i, i))
        filter_chain.append("[a_rg_in_%u]%s,replaygain,anullsink" % (i,
                                                                     format_ffmpeg_filter("aformat",
                                                                                          aformat_rg_filter_params)))
      else:
        filter_chain.append("[%u:a]anul[a_r128_in_%u]" % (i, i))
      filter_chain.append("[a_r128_in_%u]%s,afifo[a_r128_in_fmt_%u]" % (i,
                                                                        format_ffmpeg_filter("aformat",
                                                                                             aformat_r128_filter_params),
                                                                        i))
    filter_chain.append("%sconcat=n=%u:v=0:a=1[a_r128_in_concat]" % ("".join(("[a_r128_in_fmt_%u]" % (i)) for i in range(len(audio_filepaths))),
                                                                     len(audio_filepaths)))
    filter_chain.append("[a_r128_in_concat]%s" % (format_ffmpeg_filter("ebur128", ebur128_filter_params)))
    cmd.append("; ".join(filter_chain))
  else:
    if calc_peak:
      filter_chain.extend((format_ffmpeg_filter("aformat", aformat_rg_filter_params),
                           "replaygain"))
    filter_chain.append(format_ffmpeg_filter("ebur128", ebur128_filter_params))
    # filter_chain.append("anullsink")
    cmd.extend(("-filter:a", ",".join(filter_chain)))
  cmd.extend(("-f", "null", os.devnull))

  # run
  logger().debug(subprocess.list2cmdline(cmd))
  output = subprocess.run(cmd,
                          check=True,
                          stdin=subprocess.DEVNULL,
                          stderr=subprocess.PIPE).stderr
  output = output.decode("utf-8", errors="replace").splitlines()

  if calc_peak:
    # parse replaygain filter output
    sample_peaks = []
    for line in reversed(output):
      if line.startswith("[Parsed_replaygain_") and ("] track_peak = " in line):
        sample_peaks.append(float(line.rsplit("=", 1)[1]))
        if len(sample_peaks) == len(audio_filepaths):
          break
    sample_peak = max(sample_peaks)
  else:
    sample_peak = None

  # parse r128 filter output
  for i in reversed(range(len(output))):
    line = output[i]
    if line.startswith("[Parsed_ebur128_") and line.endswith("Summary:"):
      break
  output = filter(lambda x: x and not x.startswith("[Parsed_replaygain_"),
                  map(str.strip, output[i:]))
  r128_stats = dict(tuple(map(str.strip, line.split(":", 1))) for line in output if not line.endswith(":"))
  r128_stats = {k: float(v.split(" ", 1)[0]) for k, v in r128_stats.items()}

  return r128_stats["I"], sample_peak
1084774
def show_frequencies(vid_data, fps, bounds=None):
    """"""
    averages = []

    if bounds:
        for x in range(1, vid_data.shape[0] - 1):
            averages.append(vid_data[x, bounds[2]:bounds[3], bounds[0]:bounds[1], :].sum())
    else:
        for x in range(1, vid_data.shape[0] - 1):
            averages.append(vid_data[x, :, :, :].sum())

    averages = averages - min(averages)

    charts_x = 1
    charts_y = 2
    pyplot.figure(figsize=(20, 10))
    pyplot.subplots_adjust(hspace=.7)

    pyplot.subplot(charts_y, charts_x, 1)
    pyplot.title("Pixel Average")
    pyplot.xlabel("Time")
    pyplot.ylabel("Brightness")
    pyplot.plot(averages)

    freqs = scipy.fftpack.fftfreq(len(averages), d=1.0 / fps)
    fft = abs(scipy.fftpack.fft(averages))
    idx = np.argsort(freqs)

    pyplot.subplot(charts_y, charts_x, 2)
    pyplot.title("FFT")
    pyplot.xlabel("Freq (Hz)")
    freqs = freqs[idx]
    fft = fft[idx]

    freqs = freqs[len(freqs) // 2 + 1:]
    fft = fft[len(fft) // 2 + 1:]
    pyplot.plot(freqs, abs(fft))

    pyplot.show()
1191866
def read_resampled(self):
        """"""
        return self.resample(data=self.buffer_queue.get(),
                             input_rate=self.input_rate)
509131
def calc_downsample(w, h, target=400):
    """"""
    if w > h:
        return h / target
    elif h >= w:
        return w / target
407639
def multiply_frequencies(signal, fs, frange, calibration_frequencies, attendB):
    """"""
    npts = len(signal)
    padto = 1 << (npts - 1).bit_length()

    X = np.fft.rfft(signal, n=padto)

    npts = padto
    f = np.arange((npts / 2) + 1) / (npts / fs)

    fidx_low = (np.abs(f - frange[0])).argmin()
    fidx_high = (np.abs(f - frange[1])).argmin()

    cal_func = interp1d(calibration_frequencies, attendB)
    roi = f[fidx_low:fidx_high]
    Hroi = cal_func(roi)
    H = np.zeros((len(X),))
    H[fidx_low:fidx_high] = Hroi

    H = smooth(H)
    # print 'H dB max', np.amax(H)

    H = 10 ** ((H).astype(float) / 20)
    # print 'H amp max', np.amax(H)

    # Xadjusted = X.copy()
    # Xadjusted[fidx_low:fidx_high] *= H
    # Xadjusted = smooth(Xadjusted)

    Xadjusted = X * H
    # print 'X max', np.amax(abs(X))
    # print 'Xadjusted max', np.amax(abs(Xadjusted))

    signal_calibrated = np.fft.irfft(Xadjusted)
    return signal_calibrated[:len(signal)]
94626
def get_noise_correction(self, shape, chunks=None):
        """"""
        data_items = self.root.findall(".//noiseVector")
        data, low_res_coords = self.read_xml_array(data_items, 'noiseLut')
        if not data_items:
            data_items = self.root.findall(".//noiseRangeVector")
            data, low_res_coords = self.read_xml_array(data_items, 'noiseRangeLut')
            range_noise = self.interpolate_xml_array(data, low_res_coords, shape, chunks=chunks)
            data_items = self.root.findall(".//noiseAzimuthVector")
            data, low_res_coords = self.read_azimuth_noise_array(data_items)
            azimuth_noise = self.interpolate_xml_array(data, low_res_coords, shape, chunks=chunks)
            noise = range_noise * azimuth_noise
        else:
            noise = self.interpolate_xml_array(data, low_res_coords, shape, chunks=chunks)
        return noise
1219160
def _resample_obspy(samples, sr, newsr, window='hanning', lowpass=True):
    # type: (np.ndarray, int, int, str, bool) -> np.ndarray
    
    from scipy.signal import resample
    from math import ceil
    factor = sr/float(newsr)
    if newsr < sr and lowpass:
        # be sure filter still behaves good
        if factor > 16:
            logger.info("Automatic filter design is unstable for resampling "
                        "factors (current sampling rate/new sampling rate) " 
                        "above 16. Manual resampling is necessary.")
        freq = min(sr, newsr) * 0.5 / float(factor)
        logger.debug(f"resample_obspy: lowpass {freq}")
        samples = lowpass_cheby2(samples, freq=freq, sr=sr, maxorder=12)
    num = int(ceil(len(samples) / factor))

    return _applyMultichan(samples, 
                           lambda S: resample(S, num, window=window))
35929
private function resample($srcImg, $nw, $nh, $ow, $oh, $imgInfo, $nx = 0, $ny = 0, $ox = 0, $oy = 0)
    {
        return $this->copy($srcImg, $nw, $nh, $ow, $oh, $imgInfo, $nx, $ny, $ox, $oy, true);
    }
1088391
def generate_with_delta_f_and_max_freq(self, t_num, max_freq, delta_f,
                                           low_frequency_cutoff=None,
                                           cached_mem=None):
        """"""
        approximant = self.approximant(t_num)
        # Don't want to use INTERP waveforms in here
        if approximant.endswith('_INTERP'):
            approximant = approximant.replace('_INTERP', '')
        # Using SPAtmplt here is bad as the stored cbrt and logv get
        # recalculated as we change delta_f values. Fall back to TaylorF2
        # in lalsimulation.
        if approximant == 'SPAtmplt':
            approximant = 'TaylorF2'
        if cached_mem is None:
            wav_len = int(max_freq / delta_f) + 1
            cached_mem = zeros(wav_len, dtype=np.complex64)
        if self.has_compressed_waveforms and self.enable_compressed_waveforms:
            htilde = self.get_decompressed_waveform(cached_mem, t_num,
                                                    f_lower=low_frequency_cutoff,
                                                    approximant=approximant,
                                                    df=delta_f)
        else :
            htilde = pycbc.waveform.get_waveform_filter(
                cached_mem, self.table[t_num], approximant=approximant,
                f_lower=low_frequency_cutoff, f_final=max_freq, delta_f=delta_f,
                distance=1./DYN_RANGE_FAC, delta_t=1./(2.*max_freq))
        return htilde
1305665
def timefreq(x,fs=200):
    
    from numpy import size, shape, arange, append
    
    maxfreq=float(fs)/2.0 # Maximum frequency
    minfreq=float(fs)/float(size(x,0)) # Minimum and delta frequency -- simply the inverse of the length of the recording in seconds
    F=arange(minfreq,maxfreq+minfreq,minfreq) # Create frequencies evenly spaced from 0:minfreq:maxfreq
    F=append(0,F) # Add zero-frequency component
    
    return F
12058
def corruptSparseVector(sdr, noiseLevel):
  

  numNoiseBits = int(noiseLevel * np.sum(sdr))
  if numNoiseBits <= 0:
    return sdr
  activeBits = np.where(sdr > 0)[0]
  inActiveBits = np.where(sdr == 0)[0]

  turnOffBits = np.random.permutation(activeBits)
  turnOnBits = np.random.permutation(inActiveBits)
  turnOffBits = turnOffBits[:numNoiseBits]
  turnOnBits = turnOnBits[:numNoiseBits]

  sdr[turnOffBits] = 0
  sdr[turnOnBits] = 1
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)
1094253
def _hz_to_semitones(self, hz):
        
        return np.log(hz / self._a440) / np.log(self._a)
1334726
def mod_4hz(self, rate_wavsample):
    """"""

    # Set parameters
    wl = self.win_length_ms
    ws = self.win_shift_ms
    nf = self.n_filters
    f_min = self.f_min
    f_max = self.f_max
    pre = self.pre_emphasis_coef

    c = bob.ap.Spectrogram(rate_wavsample[0], wl, ws, nf, f_min, f_max, pre)
    c.energy_filter=True
    c.log_filter=False
    c.energy_bands=True

    sig =  rate_wavsample[1]
    energy_bands = c(sig)
    filtering_res = self.pass_band_filtering(energy_bands, rate_wavsample[0])
    mod_4hz = self.modulation_4hz(filtering_res, rate_wavsample)
    mod_4hz = self.averaging(mod_4hz)
    e = bob.ap.Energy(rate_wavsample[0], wl, ws)
    energy_array = e(rate_wavsample[1])
    labels = self._voice_activity_detection(energy_array, mod_4hz)
    labels = utils.smoothing(labels,self.smoothing_window) # discard isolated speech less than 100ms
    logger.info("After Mod-4Hz based VAD there are %d frames remaining over %d", numpy.sum(labels), len(labels))
    return labels, energy_array, mod_4hz
622672
def _resample_samplerate(samples, sr, newsr):
    # type: (np.ndarray, int, int, str) -> np.ndarray
    
    try:
        from samplerate import resample
    except ImportError:
        return None

    ratio = newsr/sr
    return _applyMultichan(samples,
                           lambda S: resample(S, ratio, 'sinc_best'))