GVKun编程网logo

Python numpy 模块-angle() 实例源码(python中numpy模块)

1

此处将为大家介绍关于Pythonnumpy模块-angle()实例源码的详细内容,并且为您解答有关python中numpy模块的相关问题,此外,我们还将为您介绍关于#421Div.2B.MisterB

此处将为大家介绍关于Python numpy 模块-angle() 实例源码的详细内容,并且为您解答有关python中numpy模块的相关问题,此外,我们还将为您介绍关于#421 Div.2 B. Mister B and Angle in Polygon——几何数学、2022-03-29:整个二维平面算是一张地图,给定 [x,y],表示你站在 x 行 y 列, 你可以选择面朝的任何方向, 给定一个正数值 angle,表示你视野的角度为, 这个角度内你可以看无穷远,这个角度外你、Angle Beats Gym - 102361A(计算几何)、angle-cli如何添加sass或bootstrap?的有用信息。

本文目录一览:

Python numpy 模块-angle() 实例源码(python中numpy模块)

Python numpy 模块-angle() 实例源码(python中numpy模块)

Python numpy 模块,angle() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.angle()

项目:iFruitFly    作者:AdnanMuhib    | 项目源码 | 文件源码
  1. def getAngleIndegrees(_fft):
  2.  
  3. _angle = np.angle(_fft, True);
  4. _rows, _columns = _fft.shape;
  5.  
  6. for i in range(0, _rows):
  7. for j in range(0, _columns):
  8. if (_angle[i][j] < 0 and abs(_angle[i][j]) <= 180):
  9. #print(_angle[i][j]);
  10. #print("\\n");
  11. _angle[i][j] = 180 + _angle[i][j];
  12. #print(_angle[i][j]);
  13. #print("\\n");
  14. elif (_angle[i][j] < 0 and abs(_angle[i][j]) > 180):
  15. #print(_angle[i][j]);
  16. #print("\\n");
  17. _angle[i][j] = 360 + _angle[i][j];
  18. #print(_angle[i][j]);
  19. #print("\\n");
  20. return _angle;
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
  1. def appres(F, H, sig, chg, taux, c, mu, eps, n):
  2.  
  3. Res = np.zeros_like(F)
  4. Phase = np.zeros_like(F)
  5. App_ImpZ= np.zeros_like(F, dtype=''complex_'')
  6.  
  7. for i in range(0, len(F)):
  8.  
  9. UD, EH, Z , K = Propagate(F[i], n)
  10.  
  11. App_ImpZ[i] = EH[0, 1]/EH[1, 1]
  12.  
  13. Res[i] = np.abs(App_ImpZ[i])**2./(mu_0*omega(F[i]))
  14. Phase[i] = np.angle(App_ImpZ[i], deg = True)
  15.  
  16. return Res, Phase
  17.  
  18. # Evaluate Up,Down components,E and H field,for a frequency range,
  19. # a discretized depth range and a time range (use to calculate envelope)
项目:digital_rf    作者:MIThaystack    | 项目源码 | 文件源码
  1. def phase_plot(data, toffset, log_scale, title):
  2. """Plot the phase of the data in linear or log scale."""
  3. print("phase")
  4.  
  5. phase = numpy.angle(data) / numpy.pi
  6.  
  7. fig = plt.figure()
  8. ax = fig.add_subplot(1, 1, 1)
  9. ax.plot(phase)
  10.  
  11. axmx = numpy.max(phase)
  12.  
  13. #ax.axis([-axmx,axmx,-axmx,axmx])
  14. ax.grid(True)
  15. ax.set_xlabel(''time'')
  16. ax.set_ylabel(''phase'')
  17. ax.set_title(title)
  18.  
  19. return fig
项目:speech_feature_extractor    作者:ZhihaoDU    | 项目源码 | 文件源码
  1. def unkNown_feature_extractor(x, sr, win_len, shift_len, barks, inner_win, inner_shift, win_type, method_version):
  2. x_spectrum = stft_extractor(x, win_type)
  3. coef = get_fft_bark_mat(sr, 20, sr//2)
  4. bark_spect = np.matmul(coef, x_spectrum)
  5. ams = np.zeros((barks, inner_win//2+1, (bark_spect.shape[1] - inner_win)//inner_shift))
  6. for i in range(barks):
  7. channel_stft = stft_extractor(bark_spect[i, :], ''hanning'')
  8. if method_version == ''v1'':
  9. ams[i, :, :] = 20 * np.log(np.abs(channel_stft[:inner_win//2+1, :(bark_spect.shape[1] - inner_win)//inner_shift]))
  10. elif method_version == ''v2'':
  11. channel_amplitude = np.abs(channel_stft[:inner_win//2+1, :(bark_spect.shape[1] - inner_win)//inner_shift])
  12. channel_angle = np.angle(channel_stft[:inner_win//2+1, :(bark_spect.shape[1] - inner_win)//inner_shift])
  13. channel_angle = channel_angle - (np.floor(channel_angle / (2.*np.pi)) * (2.*np.pi))
  14. ams[i, :] = np.power(channel_amplitude, 1./3.) * channel_angle
  15. else:
  16. ams[i, :] = np.abs(channel_stft)
  17. return ams
项目:speech_feature_extractor    作者:ZhihaoDU    | 项目源码 | 文件源码
  1. def ams_extractor(x, :] = np.abs(channel_stft)
  2. return ams
项目:magenta    作者:tensorflow    | 项目源码 | 文件源码
  1. def griffin_lim(mag, phase_angle, n_fft, hop, num_iters):
  2. """Iterative algorithm for phase retrival from a magnitude spectrogram.
  3.  
  4. Args:
  5. mag: Magnitude spectrogram.
  6. phase_angle: Initial condition for phase.
  7. n_fft: Size of the FFT.
  8. hop: Stride of FFT. Defaults to n_fft/2.
  9. num_iters: Griffin-Lim iterations to perform.
  10.  
  11. Returns:
  12. audio: 1-D array of float32 sound samples.
  13. """
  14. fft_config = dict(n_fft=n_fft, win_length=n_fft, hop_length=hop, center=True)
  15. ifft_config = dict(win_length=n_fft, center=True)
  16. complex_specgram = inv_magphase(mag, phase_angle)
  17. for i in range(num_iters):
  18. audio = librosa.istft(complex_specgram, **ifft_config)
  19. if i != num_iters - 1:
  20. complex_specgram = librosa.stft(audio, **fft_config)
  21. _, phase = librosa.magphase(complex_specgram)
  22. phase_angle = np.angle(phase)
  23. complex_specgram = inv_magphase(mag, phase_angle)
  24. return audio
项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码
  1. def __init__(self, qubit_names, quad="real"):
  2. super(pulseCalibration, self).__init__()
  3. self.qubit_names = qubit_names if isinstance(qubit_names, list) else [qubit_names]
  4. self.qubit = [qubitFactory(qubit_name) for qubit_name in qubit_names] if isinstance(qubit_names, list) else qubitFactory(qubit_names)
  5. self.filename = ''None''
  6. self.exp = None
  7. self.axis_descriptor = None
  8. self.cw_mode = False
  9. self.saved_settings = config.load_meas_file(config.meas_file)
  10. self.settings = deepcopy(self.saved_settings) #make a copy for used during calibration
  11. self.quad = quad
  12. if quad == "real":
  13. self.quad_fun = np.real
  14. elif quad == "imag":
  15. self.quad_fun = np.imag
  16. elif quad == "amp":
  17. self.quad_fun = np.abs
  18. elif quad == "phase":
  19. self.quad_fun = np.angle
  20. else:
  21. raise ValueError(''Quadrature to calibrate must be one of ("real","imag","amp","phase").'')
  22. self.plot = self.init_plot()
项目:chxanalys    作者:yugangzhang    | 项目源码 | 文件源码
  1. def displayResult(self):
  2. fig = plt.figure(101)
  3. plt.subplot(221)
  4. plt.imshow(np.abs(self.reconstruction),origin=''lower'')
  5. plt.draw()
  6. plt.title(''Reconstruction Magnitude'')
  7. plt.subplot(222)
  8. plt.imshow(np.angle(self.reconstruction),origin=''lower'')
  9. plt.draw()
  10. plt.title(''Reconstruction Phase'')
  11. plt.subplot(223)
  12. plt.imshow(np.abs(self.aperture),origin=''lower'')
  13. plt.title("Aperture Magnitude")
  14. plt.draw()
  15. plt.subplot(224)
  16. plt.imshow(np.angle(self.aperture),origin=''lower'')
  17. plt.title("Aperture Phase")
  18. plt.draw()
  19. fig.canvas.draw()
  20.  
  21.  
  22. #fig.tight_layout()
  23. # display.display(fig)
  24. # display.clear_output(wait=True)
  25. # time.sleep(.00001)
项目:chxanalys    作者:yugangzhang    | 项目源码 | 文件源码
  1. def displayResult2(self):
  2.  
  3. fig = plt.figure()
  4. ax = fig.add_subplot(2,2,1 )
  5. ax.imshow(np.abs(self.reconstruction))
  6. ax.set_title(''Reconstruction Magnitude'')
  7.  
  8. ax = fig.add_subplot(2,2 )
  9. ax.imshow(np.angle(self.reconstruction))
  10. ax.set_title(''Reconstruction Phase'')
  11.  
  12. ax = fig.add_subplot(2,3 )
  13. ax.imshow(np.abs(self.aperture))
  14. ax.set_title("Aperture Magnitude")
  15.  
  16. ax = fig.add_subplot(2,4 )
  17. ax.imshow(np.angle(self.aperture))
  18. ax.set_title("Aperture Phase")
  19. fig.tight_layout()
项目:qiskit-sdk-py    作者:QISKit    | 项目源码 | 文件源码
  1. def phase_to_color_wheel(complex_number):
  2. """Map a phase of a complexnumber to a color in (r,g,b).
  3.  
  4. complex_number is phase is first mapped to angle in the range
  5. [0,2pi] and then to a color wheel with blue at zero phase.
  6. """
  7. angles = np.angle(complex_number)
  8. angle_round = int(((angles + 2 * np.pi) % (2 * np.pi))/np.pi*6)
  9. # print(angleround)
  10. color_map = {0: (0, 0, 1), # blue,
  11. 1: (0.5, # blue-violet
  12. 2: (1, # violet
  13. 3: (1, 0.5), # red-violet,
  14. 4: (1, 0), # red
  15. 5: (1, 0.5, # red-oranage,
  16. 6: (1, # orange
  17. 7: (0.5, # orange-yellow
  18. 8: (0, # yellow,
  19. 9: (0, # yellow-green,
  20. 10: (0, # green,
  21. 11: (0, 1) # green-blue,
  22. }
  23. return color_map[angle_round]
项目:gr-rxdrm    作者:florianbrauchle    | 项目源码 | 文件源码
  1. def time_sync(self, signal, start_est, stop_est):
  2. self.symbol_found = 0
  3. self.symbol_start = 0
  4. self.log.debug(''time_sync()'')
  5. corr_res = np.zeros( self.sym_len[self.mode], dtype=complex)
  6. for s in range(start_est, self.sym_len[self.mode]-1):
  7. corr_res[s] = self.gi_correlation(self.gi_len[self.mode], self.sym_len[self.mode], signal[s: s+self.sym_len[self.mode]] )
  8. corr_max = np.argmax( np.abs(corr_res) )
  9.  
  10. self.symbol_found = 1
  11. self.symbol_start = corr_max + 256 - 20
  12. self.generated_samples = self.sym_len[self.mode] - self.gi_len[self.mode]
  13.  
  14. # Tracking
  15. self.fine_freq_off = np.angle(corr_res[corr_max])/(2*np.pi*(self.sym_len[self.mode] - self.gi_len[self.mode])*(1.0/self.fs))
  16.  
  17. return
项目:pyssp    作者:shunsukeaihara    | 项目源码 | 文件源码
  1. def compute_by_noise_pow(self, n_pow):
  2. s_spec = np.fft.fftpack.fft(signal * self._window)
  3. s_amp = np.absolute(s_spec)
  4. s_phase = np.angle(s_spec)
  5. gamma = self._calc_aposteriori_snr(s_amp, n_pow)
  6. xi = self._calc_apriori_snr(gamma)
  7. self._prevGamma = gamma
  8. nu = gamma * xi / (1.0 + xi)
  9. self._G = (self._gamma15 * np.sqrt(nu) / gamma) * np.exp(-nu / 2.0) *\\
  10. ((1.0 + nu) * spc.i0(nu / 2.0) + nu * spc.i1(nu / 2.0))
  11. idx = np.less(s_amp ** 2.0, n_pow)
  12. self._G[idx] = self._constant
  13. idx = np.isnan(self._G) + np.isinf(self._G)
  14. self._G[idx] = xi[idx] / (xi[idx] + 1.0)
  15. idx = np.isnan(self._G) + np.isinf(self._G)
  16. self._G[idx] = self._constant
  17. self._G = np.maximum(self._G, 0.0)
  18. amp = self._G * s_amp
  19. amp = np.maximum(amp, 0.0)
  20. amp2 = self._ratio * amp + (1.0 - self._ratio) * s_amp
  21. self._prevAmp = amp
  22. spec = amp2 * np.exp(s_phase * 1j)
  23. return np.real(np.fft.fftpack.ifft(spec))
项目:pyssp    作者:shunsukeaihara    | 项目源码 | 文件源码
  1. def compute_by_noise_pow(self, n_pow)
  2. xi = self._calc_apriori_snr(gamma)
  3. # xi = self._calc_apriori_snr2(gamma,n_pow)
  4. self._prevGamma = gamma
  5. nu = gamma * xi / (1.0 + xi)
  6. self._G = xi / (1.0 + xi) * np.exp(0.5 * spc.exp1(nu))
  7. idx = np.less(s_amp ** 2.0, n_pow)
  8. # xi = self._calc_apriori_snr2(gamma,n_pow)
  9. xi = self._calc_apriori_snr(gamma)
  10. self._prevGamma = gamma
  11. u = 0.5 - self._mu / (4.0 * np.sqrt(gamma * xi))
  12. self._G = u + np.sqrt(u ** 2.0 + self._tau / (gamma * 2.0))
  13. idx = np.less(s_amp ** 2.0, 0.0)
  14. amp2 = self._ratio * amp + (1.0 - self._ratio) * s_amp
  15. self._prevAmp = amp
  16. spec = amp2 * np.exp(s_phase * 1j)
  17. return np.real(np.fft.fftpack.ifft(spec))
项目:babusca    作者:georglind    | 项目源码 | 文件源码
  1. def plot_eigen_function(ax, se, n, psi1l, psi1r):
  2.  
  3. # plt.figure(figsize=(8,8))
  4. for x in range(se.info[''L'']):
  5. for y in range(se.info[''W'']):
  6. i = x + y * se.info[''L'']
  7.  
  8. w = np.sqrt(10) * np.abs(psi1r[i, n])
  9. arg = np.angle(psi1r[i, n])
  10.  
  11. circle = plt.Circle((x, y), w, color=''black'', zorder=10)
  12. ax.add_artist(circle)
  13.  
  14. ax.plot([x, x + w * np.cos(arg)], [y, y + w * np.sin(arg)], color=''white'', lw=.8, zorder=12)
  15.  
  16. ax.set_xlim([-.5, se.info[''L''] - .5])
  17. ax.set_ylim([-.5, se.info[''W''] - .5])
  18. # plt.show()
项目:jrm_ssl    作者:Fhrozen    | 项目源码 | 文件源码
  1. def single_spectrogram(inseq,fs,wlen,h,imag=False):
  2. """
  3. imag: Return Imaginary Data of the STFT on True
  4. """
  5. nfft = int(2**(np.ceil(np.log2(wlen))))
  6. K = np.sum(hamming(wlen, False))/wlen
  7. raw_data = inseq.astype(''float32'')
  8. raw_data = raw_data/np.amax(np.absolute(raw_data))
  9. stft_data,_,_ = STFT(raw_data,nfft,fs)
  10. s = np.absolute(stft_data)/wlen/K;
  11. if np.fmod(nfft,2):
  12. s[1:,:] *=2
  13. else:
  14. s[1:-2] *=2
  15. real_data = np.transpose(20*np.log10(s + 10**-6)).astype(np.float32)
  16. if imag:
  17. imag_data = np.angle(stft_data).astype(np.float32)
  18. return real_data,imag_data
  19. return real_data
项目:zorro    作者:C-CINA    | 项目源码 | 文件源码
  1. def complex2rgbalin(s):
  2. """
  3. displays complex image with intensity corresponding to the MODULUS and color (hsv) correponging to PHASE.
  4. From: pyvincent/ptycho.py
  5. """
  6. ph=np.angle(s)
  7. t=np.pi/3
  8. nx,ny=s.shape
  9. rgba=np.zeros((nx,ny,4))
  10. rgba[:,:,0]=(ph<t)*(ph>-t) + (ph>t)*(ph<2*t)*(2*t-ph)/t + (ph>-2*t)*(ph<-t)*(ph+2*t)/t
  11. rgba[:,1]=(ph>t) + (ph<-2*t) *(-2*t-ph)/t+ (ph>0)*(ph<t) *ph/t
  12. rgba[:,2]=(ph<-t) + (ph>-t)*(ph<0) *(-ph)/t + (ph>2*t) *(ph-2*t)/t
  13. a=np.abs(s)
  14. a/=a.max()
  15. rgba[:,3]=a
  16. return rgba
项目:leeds_seismology_programs    作者:georgetaylor3152    | 项目源码 | 文件源码
  1. def autocorr(trace):
  2. """This function takes an obspy trace object and performs a phase autocorrelation
  3. of the trace with itself. First,the hilbert transform is taken to obtain the
  4. analytic signal and hence the instantaneous phase. This is then passed to a
  5. fortran script where phase correlation is performed after Schimmel et al.,2011.
  6.  
  7. This function relies on the shared object file phasecorr.so,which is the file
  8. containing the fortran subroutine for phase correlation.
  9. """
  10.  
  11. import numpy as np
  12.  
  13. from scipy.signal import hilbert
  14. from phasecorr import phasecorr
  15. # Hilbert transform to obtain the analytic signal
  16. htrans = hilbert(trace)
  17. # Perform phase autocorrelation with instantaneous phase
  18. pac = phasecorr(np.angle(htrans),np.angle(htrans),len(htrans))
  19.  
  20. return pac
项目:leeds_seismology_programs    作者:georgetaylor3152    | 项目源码 | 文件源码
  1. def crosscorr(tr1,tr2):
  2. """This function takes 2 obspy traces and performs a phase crosscorrelation
  3. of the traces. First,which is the file
  4. containing the fortran subroutine for phase correlation.
  5. """
  6.  
  7. import numpy as np
  8.  
  9. from scipy.signal import hilbert
  10. from phasecorr import phasecorr
  11. # Hilbert transform to obtain the analytic signal
  12. htrans1 = hilbert(tr1)
  13. htrans2 = hilbert(tr2)
  14. # Perform phase autocorrelation with instantaneous phase
  15. pcc = phasecorr(np.angle(htrans1),np.angle(htrans2),len(htrans1))
  16.  
  17. return pcc
项目:pyha    作者:gasparka    | 项目源码 | 文件源码
  1. def __init__(self, gain):
  2. self.gain = gain * np.pi # pi term puts angle output to pi range
  3.  
  4. # components
  5. self.conjugate = Conjugate()
  6. self.complex_mult = ComplexMultiply()
  7. self.angle = Angle()
  8. self.out = Sfix()
  9.  
  10. # specify component delay
  11. self._delay = self.conjugate._delay + \\
  12. self.complex_mult._delay + \\
  13. self.angle._delay + 1
  14.  
  15. # constants
  16. self.gain_sfix = Const(Sfix(self.gain, 3, -14))
项目:apicultor    作者:sonidosmutantes    | 项目源码 | 文件源码
  1. def NMF(stft, n_sources):
  2. """
  3. Sound source separation using NMF
  4. :param stft: the short-time Fourier Transform of the signal
  5. :param n_sources: the number of sources
  6. :returns:
  7. - Ys: sources
  8. """
  9. print "Computing approximations"
  10. W, H = librosa.decompose.decompose(np.abs(stft), n_components=n_sources, sort=True)
  11. print "Reconstructing signals"
  12. Ys = list(scipy.outer(W[:,i], H[i])*np.exp(1j*np.angle(stft)) for i in xrange(n_sources))
  13. print "Saving sound arrays"
  14. ys = [librosa.istft(Y) for Y in Ys]
  15. del Ys
  16. return ys
项目:singing_horse    作者:f0k    | 项目源码 | 文件源码
  1. def undo_melspect(spect, sample_rate=SAMPLE_RATE, fps=FPS, frame_len=FRAME_LEN, min_freq=MIN_FREQ, max_freq=MAX_FREQ, invert_melbank_method=''transpose'', phases=''random'', normalize=False):
  2. """
  3. Resynthesizes a mel spectrogram into a numpy array of samples.
  4. """
  5. # undo logarithmic scaling
  6. spect = undo_logarithmize(spect)
  7. # undo Mel filterbank
  8. spect = undo_melfilter(spect, sample_rate, frame_len, min_freq, max_freq, invert_melbank_method)
  9. # randomize or reuse phases
  10. if phases == ''random'':
  11. spect = spect * np.exp(np.pi*2.j*np.random.random(spect.shape))
  12. elif phases is not None:
  13. spect = spect * np.exp(1.j * np.angle(phases))
  14. # undo STFT
  15. hop_size = sample_rate / fps
  16. samples = undo_stft(spect, hop_size, frame_len)
  17. # normalize if needed
  18. if normalize:
  19. samples -= samples.mean()
  20. samples /= np.abs(samples).max()
  21. return samples.astype(np.float32)
项目:empymod    作者:empymod    | 项目源码 | 文件源码
  1. def __new__(cls, realpart, imagpart=None):
  2. """Create a new EMArray."""
  3.  
  4. # Create complex obj
  5. if np.any(imagpart):
  6. obj = np.real(realpart) + 1j*np.real(imagpart)
  7. else:
  8. obj = np.asarray(realpart, dtype=complex)
  9.  
  10. # Ensure its at least a 1D-Array,view cls
  11. obj = np.atleast_1d(obj).view(cls)
  12.  
  13. # Store amplitude
  14. obj.amp = np.abs(obj)
  15.  
  16. # Calculate phase,unwrap it,transform to degrees
  17. obj.pha = np.rad2deg(np.unwrap(np.angle(obj.real + 1j*obj.imag)))
  18.  
  19. return obj
  20.  
  21.  
  22. # 2. Input parameter checks for modelling
  23.  
  24. # 2.a <Check>s (alphabetically)
项目:magphase    作者:CSTR-Edinburgh    | 项目源码 | 文件源码
  1. def ph_dec(m_phs, m_phc, mode=''angle''):
  2.  
  3. if mode == ''sign'':
  4. m_bs = np.arcsin(m_phs)
  5. m_bc = np.arccos(m_phc)
  6. m_ph = np.sign(m_bs) * np.abs(m_bc)
  7.  
  8. elif mode == ''angle'':
  9. m_ph = np.angle(m_phc + m_phs * 1j)
  10.  
  11. return m_ph
  12.  
  13.  
  14. #==============================================================================
  15. # From ''analysis_with_del_comp_and_ph_encoding_from_files''
  16. # f0_type: ''f0'',''lf0''
项目:pactools    作者:pactools    | 项目源码 | 文件源码
  1. def phase_string(sig):
  2. """Take the angle and create a string as \\pi if close to some \\pi values"""
  3. if isinstance(sig, np.ndarray):
  4. sig = sig.ravel()[0]
  5. if isinstance(sig, np.complex):
  6. angle = np.angle(sig)
  7. else:
  8. angle = sig
  9.  
  10. fractions = [Fraction(i, 12) for i in np.arange(-12, 12 + 1)]
  11. pi_multiples = np.array([np.pi * frac_to_float(f) for f in fractions])
  12. strings = [frac_to_str(f) for f in fractions]
  13.  
  14. if np.min(np.abs(angle - pi_multiples)) < 1e-3:
  15. return strings[np.argmin(np.abs(angle - pi_multiples))]
  16. else:
  17. return ''%.2f'' % angle
项目:jamespy_py3    作者:jskDr    | 项目源码 | 文件源码
  1. def cimshow(f_impulse):
  2. plt.figure(figsize=(7,5))
  3. plt.subplot(2,1)
  4. plt.imshow(np.real(f_impulse))
  5. plt.colorbar()
  6. plt.title(''Re{}'')
  7.  
  8. plt.subplot(2,2)
  9. plt.imshow(np.imag(f_impulse))
  10. plt.colorbar()
  11. plt.title(''Img{}'')
  12.  
  13. plt.subplot(2,2+1)
  14. plt.imshow(np.abs(f_impulse))
  15. plt.colorbar()
  16. plt.title(''Magnitude'')
  17.  
  18. plt.subplot(2,2+2)
  19. plt.imshow(np.angle(f_impulse))
  20. plt.colorbar()
  21. plt.title(''Phase'')
项目:jamespy_py3    作者:jskDr    | 项目源码 | 文件源码
  1. def cimshow(f_impulse):
  2. plt.figure(figsize=(7,2+2)
  3. plt.imshow(np.angle(f_impulse))
  4. plt.colorbar()
  5. plt.title(''Phase'')
项目:jamespy_py3    作者:jskDr    | 项目源码 | 文件源码
  1. def cimshow(f_impulse):
  2. plt.figure(figsize=(7,2+2)
  3. plt.imshow(np.angle(f_impulse))
  4. plt.colorbar()
  5. plt.title(''Phase'')
项目:jamespy_py3    作者:jskDr    | 项目源码 | 文件源码
  1. def update_recon_py(Recon1, support):
  2. err1 = 1.0
  3. Constraint = np.ones(Recon1.shape)
  4. # cdef int R1y,R1x
  5. Recon1_abs = np.abs(Recon1)
  6. Recon1_pwr2 = np.power(Recon1_abs, 2)
  7. R1y, R1x = Recon1.shape
  8.  
  9. for p in range(R1y):
  10. for q in range(R1x):
  11. if support[p, q] == 1:
  12. Constraint[p, q] = Recon1_abs[p, q]
  13. err1 += Recon1_pwr2[p, q]
  14. if Recon1_abs[p, q] > 1:
  15. Constraint[p, q] = 1
  16.  
  17. Recon1_update = Constraint * np.exp(1j * np.angle(Recon1))
  18.  
  19. return Recon1_update, err1
项目:jamespy_py3    作者:jskDr    | 项目源码 | 文件源码
  1. def imshow_GfpGbp(Gfp, Gbp):
  2. plt.subplot(2, 2, 1)
  3. plt.imshow(np.abs(Gfp), cmap=''Greys_r'')
  4. plt.title(''abs(Gfp)'')
  5.  
  6. plt.subplot(2, 2)
  7. plt.imshow(np.angle(Gfp), cmap=''Greys_r'')
  8. plt.title(''angle(Gfp)'')
  9.  
  10. plt.subplot(2, 1 + 2)
  11. plt.imshow(np.abs(Gbp), cmap=''Greys_r'')
  12. plt.title(''abs(Gbp)'')
  13.  
  14. plt.subplot(2, 2 + 2)
  15. plt.imshow(np.angle(Gbp), cmap=''Greys_r'')
  16. plt.title(''angle(Gbp)'')
项目:jamespy_py3    作者:jskDr    | 项目源码 | 文件源码
  1. def imshow_h(self):
  2. Gbp, Gfp = self.Gbp, self.Gfp
  3.  
  4. plt.figure(figsize=[10, 10])
  5. plt.subplot(2, 1)
  6. plt.imshow(np.abs(Gbp), cmap=''Greys_r'', interpolation=''none'')
  7. plt.title(''Gbp - Maganitute'')
  8.  
  9. plt.subplot(2, 2)
  10. plt.imshow(np.angle(Gbp), interpolation=''none'')
  11. plt.title(''Gbp - Angle'')
  12.  
  13. plt.subplot(2, 2 + 1)
  14. plt.imshow(np.abs(Gfp), interpolation=''none'')
  15. plt.title(''Gbf - Maganitute'')
  16.  
  17. plt.subplot(2, 2 + 2)
  18. plt.imshow(np.angle(Gfp), interpolation=''none'')
  19. plt.title(''Gbf - Angle'')
项目:jamespy_py3    作者:jskDr    | 项目源码 | 文件源码
  1. def run_complex(self, Original):
  2. """
  3. diffract original image and recon.
  4. ALso,the results will be shown
  5. """
  6. Input = self.diffract_full(Original)
  7. Recon = self.reconstruct(Input)
  8.  
  9. figure(figsize=(3 * 3 + 2, 3))
  10. subplot(1, 4, 1)
  11. imshow(Original, ''Greys_r'')
  12. title(''Original'')
  13. subplot(1, 2)
  14. imshow(np.abs(Input), ''Greys_r'')
  15. title(''|Diffraction|'')
  16. subplot(1, 3)
  17. imshow(np.angle(Input), ''Greys_r'')
  18. title(''Angle(Diffraction)'')
  19. subplot(1, 4)
  20. imshow(np.abs(Recon), ''Greys_r'')
  21. title(''Modulus: |Recon|'')
项目:ArduPi-ECG    作者:ferdavid1    | 项目源码 | 文件源码
  1. def fourierExtrapolation(x, n_predict):
  2. n = len(x)
  3. n_harm = 10 # number of harmonics in model
  4. t = np.arange(0, n)
  5. p = np.polyfit(t, x, 1) # find linear trend in x
  6. x_notrend = x - p[0] * t # detrended x
  7. x_freqdom = fft.fft(x_notrend) # detrended x in frequency domain
  8. f = fft.fftfreq(n) # frequencies
  9. indexes = list(range(n))
  10. # sort indexes by frequency,lower -> higher
  11. indexes.sort(key = lambda i: np.absolute(f[i]))
  12.  
  13. t = np.arange(0, n + n_predict)
  14. restored_sig = np.zeros(t.size)
  15. for i in indexes[:1 + n_harm * 2]:
  16. ampli = np.absolute(x_freqdom[i]) / n # amplitude
  17. phase = np.angle(x_freqdom[i]) # phase
  18. restored_sig += ampli * np.cos(2 * np.pi * f[i] * t + phase)
  19. return restored_sig + p[0] * t
项目:ArduPi-ECG    作者:ferdavid1    | 项目源码 | 文件源码
  1. def fourierExtrapolation(x, n + n_predict)
  2. restored_sig = np.zeros(t.size)
  3. for i in indexes[:1 + n_harm * 2]:
  4. ampli = np.absolute(x_freqdom[i]) / n # amplitude
  5. phase = np.angle(x_freqdom[i]) # phase
  6. restored_sig += ampli * np.cos(2 * np.pi * f[i] * t + phase)
  7. return restored_sig + p[0] * t
项目:ArduPi-ECG    作者:ferdavid1    | 项目源码 | 文件源码
  1. def fourierExtrapolation(x, n + n_predict)
  2. restored_sig = np.zeros(t.size)
  3. for i in indexes[:1 + n_harm * 2]:
  4. ampli = np.absolute(x_freqdom[i]) / n # amplitude
  5. phase = np.angle(x_freqdom[i]) # phase
  6. restored_sig += ampli * np.cos(2 * np.pi * f[i] * t + phase)
  7. return restored_sig + p[0] * t
项目:Tacotron    作者:barronalex    | 项目源码 | 文件源码
  1. def griffinlim(spectrogram, n_iter=50, window=''hann'', n_fft=2048, win_length=2048, hop_length=-1, verbose=False):
  2. if hop_length == -1:
  3. hop_length = n_fft // 4
  4.  
  5. angles = np.exp(2j * np.pi * np.random.rand(*spectrogram.shape))
  6.  
  7. t = tqdm(range(n_iter), ncols=100, mininterval=2.0, disable=not verbose)
  8. for i in t:
  9. full = np.abs(spectrogram).astype(np.complex) * angles
  10. inverse = librosa.istft(full, hop_length = hop_length, win_length = win_length, window = window)
  11. rebuilt = librosa.stft(inverse, n_fft = n_fft, window = window)
  12. angles = np.exp(1j * np.angle(rebuilt))
  13.  
  14. if verbose:
  15. diff = np.abs(spectrogram) - np.abs(rebuilt)
  16. t.set_postfix(loss=np.linalg.norm(diff, ''fro''))
  17.  
  18. full = np.abs(spectrogram).astype(np.complex) * angles
  19. inverse = librosa.istft(full, window = window)
  20.  
  21. return inverse
项目:Test-stock-prediction-algorithms    作者:timestocome    | 项目源码 | 文件源码
  1. def fourierEx(x, n_predict, harmonics):
  2.  
  3. n = len(x) # number of input samples
  4. n_harmonics = harmonics # f,2*f,3*f,.... n_harmonics ( 1,2,)
  5. t = np.arange(0, n) # place to store data
  6. p = np.polyfit(t, 1) # find trend
  7. x_no_trend = x - p[0] * t
  8. x_frequency_domains = fft.fft(x_no_trend)
  9. f = np.fft.fftfreq(n) # frequencies
  10. indexes = list(range(n))
  11. indexes.sort(key=lambda i: np.absolute(f[i]))
  12.  
  13. t = np.arange(0, n + n_predict)
  14. restored_signal = np.zeros(t.size)
  15. for i in indexes[:1 + n_harmonics * 2]:
  16. amplitude = np.absolute(x_frequency_domains[i] / n)
  17. phase = np.angle(x_frequency_domains[i])
  18. restored_signal += amplitude * np.cos(2 * np.pi * f[i] * t + phase)
  19.  
  20. return restored_signal + p[0] * t
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def processData(self, data):
  2. times = data.xvals(''Time'')
  3. dt = times[1]-times[0]
  4.  
  5. data1 = data.asarray()
  6. ft = np.fft.fft(data1)
  7.  
  8. ## determine frequencies in fft data
  9. df = 1.0 / (len(data1) * dt)
  10. freqs = np.linspace(0.0, (len(ft)-1) * df, len(ft))
  11.  
  12. ## flatten spikes at f0 and harmonics
  13. f0 = self.ctrls[''f0''].value()
  14. for i in xrange(1, self.ctrls[''harmonics''].value()+2):
  15. f = f0 * i # target frequency
  16.  
  17. ## determine index range to check for this frequency
  18. ind1 = int(np.floor(f / df))
  19. ind2 = int(np.ceil(f / df)) + (self.ctrls[''samples''].value()-1)
  20. if ind1 > len(ft)/2.:
  21. break
  22. mag = (abs(ft[ind1-1]) + abs(ft[ind2+1])) * 0.5
  23. for j in range(ind1, ind2+1):
  24. phase = np.angle(ft[j]) ## Must preserve the phase of each point,otherwise any transients in the trace might lead to large artifacts.
  25. re = mag * np.cos(phase)
  26. im = mag * np.sin(phase)
  27. ft[j] = re + im*1j
  28. ft[len(ft)-j] = re - im*1j
  29.  
  30. data2 = np.fft.ifft(ft).real
  31.  
  32. ma = Metaarray.MetaArray(data2, info=data.infocopy())
  33. return ma
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def removePeriodic(data, f0=60.0, dt=None, harmonics=10, samples=4):
  2. if (hasattr(data, ''implements'') and data.implements(''MetaArray'')):
  3. data1 = data.asarray()
  4. if dt is None:
  5. times = data.xvals(''Time'')
  6. dt = times[1]-times[0]
  7. else:
  8. data1 = data
  9. if dt is None:
  10. raise Exception(''Must specify dt for this data'')
  11.  
  12. ft = np.fft.fft(data1)
  13.  
  14. ## determine frequencies in fft data
  15. df = 1.0 / (len(data1) * dt)
  16. freqs = np.linspace(0.0, len(ft))
  17.  
  18. ## flatten spikes at f0 and harmonics
  19. for i in xrange(1, harmonics + 2):
  20. f = f0 * i # target frequency
  21.  
  22. ## determine index range to check for this frequency
  23. ind1 = int(np.floor(f / df))
  24. ind2 = int(np.ceil(f / df)) + (samples-1)
  25. if ind1 > len(ft)/2.:
  26. break
  27. mag = (abs(ft[ind1-1]) + abs(ft[ind2+1])) * 0.5
  28. for j in range(ind1, ind2+1):
  29. phase = np.angle(ft[j]) ## Must preserve the phase of each point,otherwise any transients in the trace might lead to large artifacts.
  30. re = mag * np.cos(phase)
  31. im = mag * np.sin(phase)
  32. ft[j] = re + im*1j
  33. ft[len(ft)-j] = re - im*1j
  34.  
  35. data2 = np.fft.ifft(ft).real
  36.  
  37. if (hasattr(data, ''implements'') and data.implements(''MetaArray'')):
  38. return Metaarray.MetaArray(data2, info=data.infocopy())
  39. else:
  40. return data2
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def processData(self, info=data.infocopy())
  2. return ma
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def removePeriodic(data, info=data.infocopy())
  2. else:
  3. return data2
项目:iFruitFly    作者:AdnanMuhib    | 项目源码 | 文件源码
  1. def getMag(_fft):
  2. _mag = abs(_fft);
  3. norm_mag = _mag/_mag.max();
  4. #angle = angle/angle.max();
  5. return norm_mag;
项目:prysm    作者:brandondube    | 项目源码 | 文件源码
  1. def resample_2d_complex(array, sample_pts, query_pts):
  2. '''''' Resamples a 2D complex array by interpolating the magnitude and phase
  3. independently and merging the results into a complex value.
  4.  
  5. Args:
  6. array (numpy.ndarray): complex 2D array.
  7.  
  8. sample_pts (tuple): pair of numpy.ndarray objects that contain the x and y sample locations,
  9. each array should be 1D.
  10.  
  11. query_pts (tuple): points to interpolate onto,also 1D for each array.
  12.  
  13. Returns:
  14. numpy.ndarray array resampled onto query_pts via bivariate spline
  15.  
  16. ''''''
  17. xq, yq = np.meshgrid(*query_pts)
  18. mag = abs(array)
  19. phase = np.angle(array)
  20.  
  21. magfunc = interpolate.RegularGridInterpolator(sample_pts, mag)
  22. phasefunc = interpolate.RegularGridInterpolator(sample_pts, phase)
  23.  
  24. interp_mag = magfunc((yq, xq))
  25. interp_phase = phasefunc((yq, xq))
  26.  
  27. return interp_mag * exp(1j * interp_phase)
项目:untwist    作者:IoSR-Surrey    | 项目源码 | 文件源码
  1. def phase(self):
  2. """
  3. Return the phase spectrum.
  4. """
  5. return np.angle(self)
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
  1. def phase(z):
  2. val = np.angle(z)
  3. # val = np.rad2deg(np.unwrap(np.angle((z))))
  4. return val
项目:mss_pytorch    作者:Js-Mim    | 项目源码 | 文件源码
  1. def DFT(x, N):
  2. """ discrete Fourier Transformation(Analysis) of a given real input signal
  3. via an FFT implementation from scipy. Single channel is being supported.
  4. Args:
  5. x : (array) Real time domain input signal
  6. w : (array) Desired windowing function
  7. N : (int) FFT size
  8. Returns:
  9. magX : (2D ndarray) Magnitude Spectrum
  10. phsX : (2D ndarray) Phase Spectrum
  11. """
  12.  
  13. # Half spectrum size containing DC component
  14. hlfN = (N/2)+1
  15.  
  16. # Half window size. Two parameters to perform zero-phase windowing technique
  17. hw1 = int(math.floor((w.size+1)/2))
  18. hw2 = int(math.floor(w.size/2))
  19.  
  20. # Window the input signal
  21. winx = x*w
  22.  
  23. # Initialize FFT buffer with zeros and perform zero-phase windowing
  24. fftbuffer = np.zeros(N)
  25. fftbuffer[:hw1] = winx[hw2:]
  26. fftbuffer[-hw2:] = winx[:hw2]
  27.  
  28. # Compute DFT via scipy''s FFT implementation
  29. X = fft(fftbuffer)
  30.  
  31. # Acquire magnitude and phase spectrum
  32. magX = (np.abs(X[:hlfN]))
  33. phsX = (np.angle(X[:hlfN]))
  34.  
  35. return magX, phsX
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_simple(self):
  2. x = np.array([1+0j, 1+2j])
  3. y_r = np.log(np.abs(x)) + 1j * np.angle(x)
  4. y = np.log(x)
  5. for i in range(len(x)):
  6. assert_almost_equal(y[i], y_r[i])
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_basic_ufuncs(self):
  2. # Test varIoUs functions such as sin,cos.
  3. (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
  4. assert_equal(np.cos(x), cos(xm))
  5. assert_equal(np.cosh(x), cosh(xm))
  6. assert_equal(np.sin(x), sin(xm))
  7. assert_equal(np.sinh(x), sinh(xm))
  8. assert_equal(np.tan(x), tan(xm))
  9. assert_equal(np.tanh(x), tanh(xm))
  10. assert_equal(np.sqrt(abs(x)), sqrt(xm))
  11. assert_equal(np.log(abs(x)), log(xm))
  12. assert_equal(np.log10(abs(x)), log10(xm))
  13. assert_equal(np.exp(x), exp(xm))
  14. assert_equal(np.arcsin(z), arcsin(zm))
  15. assert_equal(np.arccos(z), arccos(zm))
  16. assert_equal(np.arctan(z), arctan(zm))
  17. assert_equal(np.arctan2(x, arctan2(xm, ym))
  18. assert_equal(np.absolute(x), absolute(xm))
  19. assert_equal(np.angle(x + 1j*y), angle(xm + 1j*ym))
  20. assert_equal(np.angle(x + 1j*y, deg=True), angle(xm + 1j*ym, deg=True))
  21. assert_equal(np.equal(x, equal(xm, ym))
  22. assert_equal(np.not_equal(x, not_equal(xm, ym))
  23. assert_equal(np.less(x, less(xm, ym))
  24. assert_equal(np.greater(x, greater(xm, ym))
  25. assert_equal(np.less_equal(x, less_equal(xm, ym))
  26. assert_equal(np.greater_equal(x, greater_equal(xm, ym))
  27. assert_equal(np.conjugate(x), conjugate(xm))
项目:speech_feature_extractor    作者:ZhihaoDU    | 项目源码 | 文件源码
  1. def synthesis_speech(noisy_speech, ideal_mask, syn_method=''A&R''):
  2. samples = noisy_speech.shape[0]
  3. frames = (samples - win_len) // shift_len
  4.  
  5. if win_type == ''hanning'':
  6. window = np.hanning(win_len)
  7. elif win_type == ''hamming'':
  8. window = np.hamming(win_len)
  9. elif win_type == ''rectangle'':
  10. window = np.ones(win_len)
  11. to_ifft = np.zeros(win_len, dtype=np.complex64)
  12. clean_speech = np.zeros((frames-1)*shift_len+win_len, dtype=np.float32)
  13. window_sum = np.zeros((frames-1)*shift_len+win_len, dtype=np.float32)
  14. for i in range(frames):
  15. one_frame = noisy_speech[i * shift_len: i * shift_len + win_len]
  16. windowed_frame = np.multiply(one_frame, window)
  17. stft = np.fft.fft(windowed_frame, win_len)
  18. masked_abs = np.abs(stft[:win_len//2+1]) * ideal_mask[:, i]
  19. to_ifft[:win_len//2+1] = masked_abs * np.exp(1j * np.angle(stft[:win_len//2+1]))
  20. to_ifft[win_len//2+1:] = np.conj(to_ifft[win_len//2-1:0:-1])
  21. speech_seg = np.real(np.fft.ifft(to_ifft, win_len))
  22.  
  23. if syn_method == ''A&R'' or syn_method == ''ALLEN & rabinER'':
  24. clean_speech[i*shift_len:i*shift_len+win_len] += speech_seg
  25. window_sum[i*shift_len:i*shift_len+win_len] += window
  26.  
  27. elif syn_method == ''G&L'' or syn_method == ''GRIFFIN & LIM'':
  28. speech_seg = np.multiply(speech_seg, window)
  29. clean_speech[i * shift_len:i * shift_len + win_len] += speech_seg
  30. window_sum[i * shift_len:i * shift_len + win_len] += np.power(window, 2.)
  31. # if i > 0:
  32. # clean_speech[i*shift_len: (i-1)*shift_len+win_len] *= 0.5
  33. window_sum = np.where(window_sum < 1e-2, 1e-2, window_sum)
  34. return clean_speech / window_sum
项目:speech_feature_extractor    作者:ZhihaoDU    | 项目源码 | 文件源码
  1. def synthesis_speech(ns, mk, syn_method=''A&R''):
  2. samples = ns.shape[0]
  3. frames = (samples - win_len) // shift_len
  4.  
  5. if win_type == ''hanning'':
  6. window = np.hanning(win_len)
  7. elif win_type == ''hamming'':
  8. window = np.hamming(win_len)
  9. elif win_type == ''rectangle'':
  10. window = np.ones(win_len)
  11. to_ifft = np.zeros(win_len, dtype=np.float32)
  12. for i in range(frames):
  13. one_frame = ns[i * shift_len: i * shift_len + win_len]
  14. windowed_frame = np.multiply(one_frame, win_len)
  15. masked_abs = np.abs(stft[:win_len//2+1]) * mk[:, 320))
  16.  
  17. if syn_method == ''A&R'' or syn_method == ''ALLEN & rabinER'':
  18. clean_speech[i*shift_len:i*shift_len+win_len] += speech_seg
  19. window_sum[i*shift_len:i*shift_len+win_len] += window
  20.  
  21. elif syn_method == ''G&L'' or syn_method == ''GRIFFIN & LIM'':
  22. speech_seg = np.multiply(speech_seg, window_sum)
  23. return clean_speech / window_sum

#421 Div.2 B. Mister B and Angle in Polygon——几何数学

#421 Div.2 B. Mister B and Angle in Polygon——几何数学

总结

以上是小编为你收集整理的#421 Div.2 B. Mister B and Angle in Polygon——几何数学全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

2022-03-29:整个二维平面算是一张地图,给定 [x,y],表示你站在 x 行 y 列, 你可以选择面朝的任何方向, 给定一个正数值 angle,表示你视野的角度为, 这个角度内你可以看无穷远,这个角度外你

2022-03-29:整个二维平面算是一张地图,给定 [x,y],表示你站在 x 行 y 列, 你可以选择面朝的任何方向, 给定一个正数值 angle,表示你视野的角度为, 这个角度内你可以看无穷远,这个角度外你

2022-03-29:整个二维平面算是一张地图,给定 [x,y],表示你站在 x 行 y 列, 你可以选择面朝的任何方向, 给定一个正数值 angle,表示你视野的角度为, 这个角度内你可以看无穷远,这个角度外你看不到任何东西。 给定一批点的二维坐标, 返回你在朝向最好的情况下,最多能看到几个点。

答案 2022-03-29:

第一步:把 x,y 平移到原点上。 第二步:把所有点放在单位圆上,算出夹角。 第三步:不回退计算。在原点的点需要单独算。

代码用 golang 编写。代码如下:

package main

import (
	"fmt"
	"math"
	"sort"
)

func main() {
	points := [][]int{{2, 1}, {2, 2}, {3, 3}}
	angle := 90
	location := []int{1, 1}
	ret := visiblePoints(points, angle, location)
	fmt.Println(ret)
}

func visiblePoints(points [][]int, angle int, location []int) int {
	n := len(points)
	a := location[0]
	b := location[1]
	zero := 0
	arr := make([]float64, n<<1)
	m := 0
	for i := 0; i < n; i++ {
		x := points[i][0] - a
		y := points[i][1] - b
		if x == 0 && y == 0 {
			zero++
		} else {
			math.Atan2(float64(y), float64(x))
			arr[m] = toDegrees(math.Atan2(float64(y), float64(x)))
			arr[m+1] = arr[m] + 360
			m += 2
		}
	}
	sort.Float64s(arr[0:m])
	max := 0
	for L, R := 0, 0; L < n; L++ {
		for R < m && arr[R]-arr[L] <= float64(angle) {
			R++
		}
		max = getMax(max, R-L)
	}
	return max + zero
}

func getMax(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func toDegrees(x float64) float64 {
	return x * (180.0 / math.Pi)
}

执行结果如下:


左神 java 代码

Angle Beats Gym - 102361A(计算几何)

Angle Beats Gym - 102361A(计算几何)

Angle Beats

$$ Time Limit: 4000 ms \quad Memory Limit: 1048576 kB $$

题意

给出 $n$ 个初始点以及 $q$ 次询问,每次询问给出一个询问点 $Q$,求包括 $Q$ 点的直角三角形有多少个。保证 $n+q$ 个点都不重复。

思路

  1. 对于每次询问,当 $Q$ 为直角点时,以 $Q$ 为原点,对 $n$ 个点做象限极角排序,然后用双指针 $L$、 $R$ 维护直角三角形的个数。 $L$ 指针用来枚举其中的一条直角边, $R$ 指针用来寻找在另一条直角边上的点有多少个,每次找 $QL$ 这条边逆时针方向的另一条边$QR$。所以当 $L$ 往逆时针转动时,$R$ 也会往逆时针转动,那么就可以用双指针直接维护出来了,特别注意一下多个点在同一条直线上的情况就可以了。
  2. 若 $Q$ 不是直角点时,可以离线处理,把 $n+q$ 个点全部存出来,然后枚举以 $n$ 个初始点为直角点时,对哪些的 $Q$ 点有贡献,维护方法同上。

最后的复杂度为 $O\left(qnC_1 + n(n+q)C_2\right)$,$C_1、C_2$ 取决于在枚举直角点为原点后,到原点在同一条直线上的点数量。 我试过把 $n+q$ 个节点全部提取出来,然后暴力枚举每个点为直角点的情况,但是这样复杂度会 $T$。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e4+10;

struct Point {
	ll x, y;
	int id;
} p[maxn], be[maxn];
int n, m;
int ans[maxn];

int cmp1(Point a, Point b) {
	ll d = a.x*b.y - b.x*a.y;
	if(d == 0) {
		return a.x<b.x;
	} else {
		return d>0;
	}
}
int Qua(Point a) {
	if(a.x>0 && a.y>=0)	return 1;
	if(a.x<=0 && a.y>0)	return 2;
	if(a.x<0 && a.y<=0)	return 3;
	if(a.x>=0 && a.y<0)	return 4;
}

int cmp(Point a, Point b) {
	if(Qua(a) == Qua(b))	return cmp1(a, b);
	else	return Qua(a)<Qua(b);
}

ll check(Point a, Point b) {
	return a.x*b.x + a.y*b.y;
}

ll chaji(Point a, Point b) {
	return a.x*b.y - b.x*a.y;
}

ll work(Point pp) {
	for(int i=1; i<=n; i++) {
		p[i] = be[i];
		p[i].x -= pp.x;
		p[i].y -= pp.y;
	}
	p[0] = pp;
	sort(p+1, p+1+n, cmp);
	for(int j=1; j<=n; j++) {
		p[j+n] = p[j];
	}
	ll ans = 0;
	int R = 2;
	for(int L=1; L<=n; L++) {
		while(R<=2*n) {
			if(chaji(p[L], p[R]) < 0)	break;
			if(check(p[L], p[R]) <= 0)	break;
			R++;
		}
		int tR = R;
		while(tR<=2*n) {
			if(chaji(p[L], p[tR]) <= 0)	break;
			if(check(p[L], p[tR]) != 0)	break;
			ans++;
			tR++;
		}
	}
	return ans;
}

int main(){
	// freopen("in", "r", stdin);
	while(~scanf("%d%d", &n, &m)) {
		int all = 0;
		for(int i=1; i<=n; i++) {
			all++;
			int x, y;
			scanf("%d%d", &x, &y);
			p[all].x = x, p[all].y = y, p[all].id = 0;
			be[all] = p[all];
		}
		for(int i=1; i<=m; i++) {
			all++;
			int x, y;
			scanf("%d%d", &x, &y);
			p[all].x = x, p[all].y = y, p[all].id = i;
			be[all] = p[all];
			ans[i] = work(p[all]);
		}
		for(int i=1; i<=n; i++) {
			for(int j=1; j<=all; j++) {
				p[j] = be[j];
			}
			p[0] = be[i];
			int flag = 0;
			for(int j=1; j<=all; j++) {
				if(p[j].x == p[0].x && p[j].y == p[0].y)	flag = 1;
				if(flag)	p[j] = p[j+1];
				p[j].x -= p[0].x;
				p[j].y -= p[0].y;
			}

			int nn = all-1;
			sort(p+1, p+1+nn, cmp);
			for(int j=1; j<=nn; j++) {
				p[j+nn] = p[j];
			}
			int R = 2;
			for(int L=1; L<=nn; L++) {
				int id = 0;
				if(p[0].id)	id = p[0].id;
				if(p[L].id)	id = p[L].id;
				while(R<=2*nn) {
					if(chaji(p[L], p[R]) < 0)	break;
					if(check(p[L], p[R]) <= 0)	break;
					R++;
				}
				int tR = R;
				while(tR<=2*nn) {
					if(chaji(p[L], p[tR]) <= 0)	break;
					if(check(p[L], p[tR]) != 0)	break;
					if(id == 0)	{
						if(p[tR].id)	ans[p[tR].id]++;
					} else {
						if(p[tR].id == 0)	ans[id]++;
					}
					tR++;
				}
			}
		}
		for(int i=1; i<=m; i++) {
			printf("%d\n", ans[i]);
		}
	}
	return 0;
}

angle-cli如何添加sass或bootstrap?

angle-cli如何添加sass或bootstrap?

我正在尝试角色,并尝试在项目中获得sass和bootstrap.我在 wiki读过,你可以简单地做:
ng install sass

用最新的(beta.5)进行此操作会给我一个错误:

Install Failed. Could not find addon with name: sass

我该如何去安装引导程序和/或sass,方法角度来处理索引页面和systemJS?

解决方法

NOTE: This answer is out of date due to changes in the Angular CLI,please refer to the answer below from Woot which is more current.

您需要通过npm i node-sass –save-dev安装node-sass,然后将angular-cli.json中的styleExt更改为sass或scss(或者您可以通过ng set defaults.styleExt scss

至于引导,将它放在公共目录下(我使用一个名为style的子目录),并在index.html中引用它

更新:
此外,如果您想要有变量文件,您可以将目录添加到这样的angular-cli-build.js …

return new Angular2App(defaults,{
  vendorNpmFiles: [
    ...
  ],sassCompiler: {
    includePaths: [
      'src/app/style' <-- directory for SASS reference files
    ]
  }
});

今天关于Python numpy 模块-angle() 实例源码python中numpy模块的分享就到这里,希望大家有所收获,若想了解更多关于#421 Div.2 B. Mister B and Angle in Polygon——几何数学、2022-03-29:整个二维平面算是一张地图,给定 [x,y],表示你站在 x 行 y 列, 你可以选择面朝的任何方向, 给定一个正数值 angle,表示你视野的角度为, 这个角度内你可以看无穷远,这个角度外你、Angle Beats Gym - 102361A(计算几何)、angle-cli如何添加sass或bootstrap?等相关知识,可以在本站进行查询。

本文标签: