Calculate the autocorrelation function of the noise
    where the noise is a 2d array that may contain nans


    Parameters
    ----------
    noise : 2d-array
        Noise image.

    Returns
    -------
    acf : 2d-array
        The ACF.
343995
def nan_acf(noise):
    
    corr = np.zeros(noise.shape)
    ix,jx = noise.shape
    for i in range(ix):
        si_min = slice(i, None, None)
        si_max = slice(None, ix-i, None)
        for j in range(jx):
            sj_min = slice(j, None, None)
            sj_max = slice(None, jx-j, None)
            if np.all(np.isnan(noise[si_min, sj_min])) or np.all(np.isnan(noise[si_max, sj_max])):
                corr[i, j] = np.nan
            else:
                corr[i, j] = np.nansum(noise[si_min, sj_min] * noise[si_max, sj_max])
    # return the normalised acf
    return corr / np.nanmax(corr)
491023
def generate(self):
        '''
        
        '''
        generated_arr = np.random.uniform(low=self.__low, high=self.__high, size=self.__output_shape)
        if self.noise_sampler is not None:
            self.noise_sampler.output_shape = generated_arr.shape
            generated_arr += self.noise_sampler.generate()
        return generated_arr
79571
def plotnoise(noisepkl, mergepkl, plot_width=950, plot_height=400):
    

    d = pickle.load(open(mergepkl))
    ndist, imstd, flagfrac = plotnoisedist(noisepkl, plot_width=plot_width/2, plot_height=plot_height)
    fluxscale = calcfluxscale(d, imstd, flagfrac)
    logger.info('Median image noise is {0:.3} Jy.'.format(fluxscale*imstd))
    ncum, imnoise = plotnoisecum(noisepkl, fluxscale=fluxscale, plot_width=plot_width/2, plot_height=plot_height)

    hndle = show(Row(ndist, ncum, width=plot_width, height=plot_height))
    return imnoise
360917
def compamp_to_ac(compamp, window=np.hanning):  # convert single or multi-subband compamps into autocorrelation waterfall

  '''
  
  
  '''
  header = compamp.header()
 
  cdata = compamp.complex_data()

  #Apply Windowing and Padding
  cdata = np.multiply(cdata, window(cdata.shape[2]))  # window for smoothing sharp time series start/end in freq. dom.
  cdata_normal = cdata - cdata.mean(axis=2)[:, :, np.newaxis]  # zero mean, does influence a minority of lines in some plots

  cdata = np.zeros((cdata.shape[0], cdata.shape[1], 2 * cdata.shape[2]), complex)
  cdata[:, :, cdata.shape[2]/2:cdata.shape[2] + cdata.shape[2]/2] = cdata_normal  # zero-pad to 2N

  #Perform Autocorrelation
  cdata = np.fft.fftshift(np.fft.fft(cdata), 2)  # FFT all blocks separately and arrange correctly
  cdata = cdata.real**2 + cdata.imag**2  # FFT(AC(x)) = FFT(x)FFT*(x) = abs(x)^2
  cdata = np.fft.ifftshift(np.fft.ifft(cdata), 2)  # AC(x) = iFFT(abs(x)^2) and arrange correctly
  cdata = np.abs(cdata)  # magnitude of AC

  # normalize each row to sqrt of AC triangle
  cdata = np.divide(cdata, np.sqrt(np.sum(cdata, axis=2))[:, :, np.newaxis])  

  return cdata
398806
def estimate_noiseperbl(data):
    
    
    # define noise per baseline for data seen by detect_bispectra or image
    datamean = data.mean(axis=2).imag                      # use imaginary part to estimate noise without calibrated, on-axis signal
    (datameanmin, datameanmax) = rtlib.sigma_clip(datamean.flatten())
    good = n.where( (datamean>datameanmin) & (datamean<datameanmax) )
    noiseperbl = datamean[good].std()   # measure single noise for input to detect_bispectra
    logger.debug('Clipped to %d%% of data (%.3f to %.3f). Noise = %.3f.' % (100.*len(good[0])/len(datamean.flatten()), datameanmin, datameanmax, noiseperbl))
    return noiseperbl
790723
def estimate_noise(fluxes, contmask):
    
    nstars = fluxes.shape[0]
    scatter = np.zeros(nstars)
    for i,spec in enumerate(fluxes): 
        cont = spec[contmask]
        scatter[i] = stats.funcs.mad_std(cont)
    return scatter
1358214
def noisysphere(self, x, noise=2.10e-9, cond=1.0, noise_offset=0.10):
        
        return self.elli(x, cond=cond) * (1 + noise * np.random.randn() / len(x)) + noise_offset * np.random.rand()
188201
def covariance(self):
        

        mu = self.moments_central
        if mu[0, 0] != 0:
            m = mu / mu[0, 0]
            covariance = self._check_covariance(
                np.array([[m[0, 2], m[1, 1]], [m[1, 1], m[2, 0]]]))
            return covariance * u.pix**2
        else:
            return np.empty((2, 2)) * np.nan * u.pix**2
392828
def signal_bursts():
    
    np.random.seed(815)
    length = 5 * 512

    # Baseline low frequency plus noise.
    data = np.sin(np.linspace(0, 80 * np.pi, length))
    noise = np.random.ranf(length)
    noise /= noise.max()
    noise /= 15
    data += noise

    # Double last two fifths of the signal.
    data[-2 * 512:] *= 2.0
    chirp1 = 2.5 * np.sin(np.linspace(0, 400 * np.pi, 512))
    chirp1 *= np.linspace(1, 0, 512)
    data[512:2 * 512] += chirp1

    # Add second transient signal.
    chirp2 = 5.0 * np.sin(np.linspace(0, 200 * np.pi, 512))
    chirp2 *= np.linspace(1, 0, 512)
    data[3 * 512:4 * 512] += chirp2

    return data
928453
public static float noise2(float x, float y) {
        int bx0, bx1, by0, by1, b00, b10, b01, b11;
        float rx0, rx1, ry0, ry1, q[], sx, sy, a, b, t, u, v;
        int i, j;

        if (start) {
            start = false;
            init();
        }

        t = x + N;
        bx0 = ((int)t) & BM;
        bx1 = (bx0+1) & BM;
        rx0 = t - (int)t;
        rx1 = rx0 - 1.0f;

        t = y + N;
        by0 = ((int)t) & BM;
        by1 = (by0+1) & BM;
        ry0 = t - (int)t;
        ry1 = ry0 - 1.0f;

        i = p[bx0];
        j = p[bx1];

        b00 = p[i + by0];
        b10 = p[j + by0];
        b01 = p[i + by1];
        b11 = p[j + by1];

        sx = sCurve(rx0);
        sy = sCurve(ry0);

        q = g2[b00]; u = rx0 * q[0] + ry0 * q[1];
        q = g2[b10]; v = rx1 * q[0] + ry0 * q[1];
        a = lerp(sx, u, v);

        q = g2[b01]; u = rx0 * q[0] + ry1 * q[1];
        q = g2[b11]; v = rx1 * q[0] + ry1 * q[1];
        b = lerp(sx, u, v);

        return 1.5f*lerp(sy, a, b);
    }
923658
def _calc_fourier_spectrum(self, fa_length=None):
        """"""

        if fa_length is None:
            # Use the next power of 2 for the length
            n = 1
            while n < self.accels.size:
                n <<= 1
        else:
            n = fa_length

        self._fourier_amps = np.fft.rfft(self._accels, n)

        freq_step = 1. / (2 * self._time_step * (n / 2))
        self._freqs = freq_step * np.arange(1 + n / 2)
213456
def generateNoise(self):
        
        # Fill wfb array with white noise based on given discrete variance
        wfb = np.zeros(self.nr*2)
        wfb[:self.nr] = np.random.normal(0, np.sqrt(self.qd), self.nr)
        # Generate the hfb coefficients based on the noise type
        mhb = -self.b/2.0
        hfb = np.zeros(self.nr*2)
        hfb = np.zeros(self.nr*2)
        hfb[0] = 1.0
        indices = np.arange(self.nr-1)
        hfb[1:self.nr] = (mhb+indices)/(indices+1.0)
        hfb[:self.nr] = np.multiply.accumulate(hfb[:self.nr])
        # Perform discrete Fourier transform of wfb and hfb time series
        wfb_fft = np.fft.rfft(wfb)
        hfb_fft = np.fft.rfft(hfb)
        # Perform inverse Fourier transform of the product of wfb and hfb FFTs
        time_series = np.fft.irfft(wfb_fft*hfb_fft)[:self.nr]
        self.time_series = time_series
1028992
def numbaGaussian2d(psf, sy, sx):
    '''
    
    '''
    ps0, ps1 = psf.shape
    c0,c1 = ps0//2, ps1//2
    ssx = 2*sx**2
    ssy = 2*sy**2
    for i in range(ps0):
        for j in range(ps1):
            psf[i,j]=exp( -( (i-c0)**2/ssy
                            +(j-c1)**2/ssx) )
    psf/=psf.sum()
1048946
def decoherence_noise_with_asymmetric_ro(gates: Sequence[Gate], p00=0.975, p11=0.911):
    
    noise_model = _decoherence_noise_model(gates)
    aprobs = np.array([[p00, 1 - p00],
                       [1 - p11, p11]])
    aprobs = {q: aprobs for q in noise_model.assignment_probs.keys()}
    return NoiseModel(noise_model.gates, aprobs)
814452
def calc_2dsplinecoeffs_c(array2d):
    
    #Set up result arrays
    out= copy.copy(array2d)
    out= numpy.require(out,dtype=numpy.float64,requirements=['C','W'])

    #Set up the C code
    ndarrayFlags= ('C_CONTIGUOUS','WRITEABLE')
    interppotential_calc_2dsplinecoeffs= _lib.samples_to_coefficients
    interppotential_calc_2dsplinecoeffs.argtypes= [ndpointer(dtype=numpy.float64,flags=ndarrayFlags),
                                                   ctypes.c_int,
                                                   ctypes.c_int]

    #Run the C code
    interppotential_calc_2dsplinecoeffs(out,out.shape[1],out.shape[0])

    return out
1199874
def spatial_correlation_array(dmatrix, imts, correl='yes',
                              vs30clustered=True):
    
    assert correl in 'yes no full', correl
    n = len(dmatrix)
    corr = numpy.zeros((len(imts), n, n))
    for imti, im in enumerate(imts):
        if correl == 'no':
            corr[imti] = numpy.eye(n)
        if correl == 'full':
            corr[imti] = numpy.ones((n, n))
        elif correl == 'yes':
            corr[imti] = correlation.jbcorrelation(dmatrix, im, vs30clustered)
    return corr
1036500
def generate(self):
        '''
        
        '''
        generated_arr = np.random.normal(loc=self.__mu, scale=self.__sigma, size=self.__output_shape)
        if self.noise_sampler is not None:
            self.noise_sampler.output_shape = generated_arr.shape
            generated_arr += self.noise_sampler.generate()
        
        return generated_arr