本文整理匯總了Python中numpy.linspace方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.linspace方法的具體用法?Python numpy.linspace怎麽用?Python numpy.linspace使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.linspace方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _radial_wvnum
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def _radial_wvnum(k, l, N, nfactor):
""" Creates a radial wavenumber based on two horizontal wavenumbers
along with the appropriate index map
"""
# compute target wavenumbers
k = k.values
l = l.values
K = np.sqrt(k[np.newaxis,:]**2 + l[:,np.newaxis]**2)
nbins = int(N/nfactor)
if k.max() > l.max():
ki = np.linspace(0., l.max(), nbins)
else:
ki = np.linspace(0., k.max(), nbins)
# compute bin index
kidx = np.digitize(np.ravel(K), ki)
# compute number of points for each wavenumber
area = np.bincount(kidx)
# compute the average radial wavenumber for each bin
kr = (np.bincount(kidx, weights=K.ravel())
/ np.ma.masked_where(area==0, area))
return ki, kr[1:-1]
示例2: test_cross_phase_2d
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def test_cross_phase_2d(self, dask):
Ny, Nx = (32, 16)
x = np.linspace(0, 1, num=Nx, endpoint=False)
y = np.ones(Ny)
f = 6
phase_offset = np.pi/2
signal1 = np.cos(2*np.pi*f*x) # frequency = 1/(2*pi)
signal2 = np.cos(2*np.pi*f*x - phase_offset)
da1 = xr.DataArray(data=signal1*y[:,np.newaxis], name='a',
dims=['y','x'], coords={'y':y, 'x':x})
da2 = xr.DataArray(data=signal2*y[:,np.newaxis], name='b',
dims=['y','x'], coords={'y':y, 'x':x})
with pytest.raises(ValueError):
xrft.cross_phase(da1, da2, dim=['y','x'])
if dask:
da1 = da1.chunk({'x': 16})
da2 = da2.chunk({'x': 16})
cp = xrft.cross_phase(da1, da2, dim=['x'])
actual_phase_offset = cp.sel(freq_x=f).values
npt.assert_almost_equal(actual_phase_offset, phase_offset)
示例3: compute_mode
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def compute_mode(self):
"""
Pre-compute mode vectors from candidate locations (in spherical
coordinates).
"""
if self.num_loc is None:
raise ValueError('Lookup table appears to be empty. \
Run build_lookup().')
self.mode_vec = np.zeros((self.max_bin,self.M,self.num_loc),
dtype='complex64')
if (self.nfft % 2 == 1):
raise ValueError('Signal length must be even.')
f = 1.0 / self.nfft * np.linspace(0, self.nfft / 2, self.max_bin) \
* 1j * 2 * np.pi
for i in range(self.num_loc):
p_s = self.loc[:, i]
for m in range(self.M):
p_m = self.L[:, m]
if (self.mode == 'near'):
dist = np.linalg.norm(p_m - p_s, axis=1)
if (self.mode == 'far'):
dist = np.dot(p_s, p_m)
# tau = np.round(self.fs*dist/self.c) # discrete - jagged
tau = self.fs * dist / self.c # "continuous" - smoother
self.mode_vec[:, m, i] = np.exp(f * tau)
示例4: load_RSM
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def load_RSM(filename):
om, tt, psd = xu.io.getxrdml_map(filename)
om = np.deg2rad(om)
tt = np.deg2rad(tt)
wavelength = 1.54056
q_y = (1 / wavelength) * (np.cos(tt) - np.cos(2 * om - tt))
q_x = (1 / wavelength) * (np.sin(tt) - np.sin(2 * om - tt))
xi = np.linspace(np.min(q_x), np.max(q_x), 100)
yi = np.linspace(np.min(q_y), np.max(q_y), 100)
psd[psd < 1] = 1
data_grid = griddata(
(q_x, q_y), psd, (xi[None, :], yi[:, None]), fill_value=1, method="cubic"
)
nx, ny = data_grid.shape
range_values = [np.min(q_x), np.max(q_x), np.min(q_y), np.max(q_y)]
output_data = (
Panel(np.log(data_grid).reshape(nx, ny, 1), minor_axis=["RSM"])
.transpose(2, 0, 1)
.to_frame()
)
return range_values, output_data
示例5: atest_plot_samples
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def atest_plot_samples(self):
dm = np.linspace(4., 19., 1001)
samples = []
for dm_k in dm:
d = 10.**(dm_k/5.-2.)
samples.append(self._interp_ebv(self._test_data[0], d))
samples = np.array(samples).T
# print samples
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
for s in samples:
ax.plot(dm, s, lw=2., alpha=0.5)
plt.show()
示例6: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def __init__(self,alpha_max,Tg,xi):
gamma=0.9+(0.05-xi)/(0.3+6*xi)
eta1=0.02+(0.05-xi)/(4+32*xi)
eta1=eta1 if eta1>0 else 0
eta2=1+(0.05-xi)/(0.08+1.6*xi)
eta2=eta2 if eta2>0.55 else 0.55
T=np.linspace(0,6,601)
alpha=[]
for t in T:
if t<0.1:
alpha.append(np.interp(t,[0,0.1],[0.45*alpha_max,eta2*alpha_max]))
elif t<Tg:
alpha.append(eta2*alpha_max)
elif t<5*Tg:
alpha.append((Tg/t)**gamma*eta2*alpha_max)
else:
alpha.append((eta2*0.2**gamma-eta1*(t-5*Tg))*alpha_max)
self.__spectrum={'T':T,'alpha':alpha}
示例7: curve_length
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def curve_length(self, start=None, end=None, precision=0.01):
'''
Calculates the length of the curve by dividing the curve up
into pieces of parameterized-length <precision>.
'''
if start is None: start = self.t[0]
if end is None: end = self.t[-1]
from scipy import interpolate
if self.order == 1:
# we just want to add up along the steps...
ii = [ii for (ii,t) in enumerate(self.t) if start < t and t < end]
ts = np.concatenate([[start], self.t[ii], [end]])
xy = np.vstack([[self(start)], self.coordinates[:,ii].T, [self(end)]])
return np.sum(np.sqrt(np.sum((xy[1:] - xy[:-1])**2, axis=1)))
else:
t = np.linspace(start, end, int(np.ceil((end-start)/precision)))
dt = t[1] - t[0]
dx = interpolate.splev(t, self.splrep[0], der=1)
dy = interpolate.splev(t, self.splrep[1], der=1)
return np.sum(np.sqrt(dx**2 + dy**2)) * dt
示例8: test_2x3
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def test_2x3(self):
# Loading the water depth map
dat = loadtxt('data/WaterDepth1.dat')
X, Y = meshgrid(linspace(0., 1000., 50), linspace(0., 1000., 50))
depth = array(zip(X.flatten(), Y.flatten(), dat.flatten()))
borders = array([[200, 200], [150, 500], [200, 800], [600, 900], [700, 700], [900, 500], [800, 200], [500, 100], [200, 200]])
baseline = array([[587.5, 223.07692308], [525., 346.15384615], [837.5, 530.76923077], [525., 530.76923077], [525., 838.46153846], [837.5, 469.23076923]])
wt_desc = WTDescFromWTG('data/V80-2MW-offshore.wtg').wt_desc
wt_layout = GenericWindFarmTurbineLayout([WTPC(wt_desc=wt_desc, position=pos) for pos in baseline])
t = Topfarm(
baseline_layout = wt_layout,
borders = borders,
depth_map = depth,
dist_WT_D = 5.0,
distribution='spiral',
wind_speeds=[4., 8., 20.],
wind_directions=linspace(0., 360., 36)[:-1]
)
t.run()
self.fail('make save function')
t.save()
示例9: figures
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def figures(ext, show):
for name, df in TablesRecorder.generate_dataframes('thames_output.h5'):
df.columns = ['Very low', 'Low', 'Central', 'High', 'Very high']
fig, (ax1, ax2) = plt.subplots(figsize=(12, 4), ncols=2, sharey='row',
gridspec_kw={'width_ratios': [3, 1]})
df['2100':'2125'].plot(ax=ax1)
df.quantile(np.linspace(0, 1)).plot(ax=ax2)
if name.startswith('reservoir'):
ax1.set_ylabel('Volume [$Mm^3$]')
else:
ax1.set_ylabel('Flow [$Mm^3/day$]')
for ax in (ax1, ax2):
ax.set_title(name)
ax.grid(True)
plt.tight_layout()
if ext is not None:
fig.savefig(f'{name}.{ext}', dpi=300)
if show:
plt.show()
示例10: plot_percentiles
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def plot_percentiles(A, B, ax=None):
if ax is None:
ax = plt.gca()
percentiles = np.linspace(0.001, 0.999, 1000) * 100
A_pct = scipy.stats.scoreatpercentile(A.values, percentiles)
B_pct = scipy.stats.scoreatpercentile(B.values, percentiles)
percentiles = percentiles / 100.0
ax.plot(percentiles, B_pct[::-1], color=c["Bfill"], clip_on=False, linewidth=2)
ax.plot(percentiles, A_pct[::-1], color=c["Afill"], clip_on=False, linewidth=2)
ax.set_xlabel("Cumulative frequency")
ax.grid(True)
ax.xaxis.grid(True, which="both")
set_000formatter(ax.get_yaxis())
ax.set_xscale("logit")
xticks = ax.get_xticks()
xticks_minr = ax.get_xticks(minor=True)
ax.set_xticklabels([], minor=True)
ax.set_xticks([0.01, 0.1, 0.5, 0.9, 0.99])
ax.set_xticklabels(["1", "10", "50", "90", "99"])
ax.set_xlim(0.001, 0.999)
ax.legend([B.name, A.name], loc="best")
return ax
示例11: generate_anchors
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def generate_anchors(self, image_width: int, image_height: int, num_x_anchors: int, num_y_anchors: int) -> Tensor:
center_ys = np.linspace(start=0, stop=image_height, num=num_y_anchors + 2)[1:-1]
center_xs = np.linspace(start=0, stop=image_width, num=num_x_anchors + 2)[1:-1]
ratios = np.array(self._anchor_ratios)
ratios = ratios[:, 0] / ratios[:, 1]
sizes = np.array(self._anchor_sizes)
# NOTE: it's important to let `center_ys` be the major index (i.e., move horizontally and then vertically) for consistency with 2D convolution
# giving the string 'ij' returns a meshgrid with matrix indexing, i.e., with shape (#center_ys, #center_xs, #ratios)
center_ys, center_xs, ratios, sizes = np.meshgrid(center_ys, center_xs, ratios, sizes, indexing='ij')
center_ys = center_ys.reshape(-1)
center_xs = center_xs.reshape(-1)
ratios = ratios.reshape(-1)
sizes = sizes.reshape(-1)
widths = sizes * np.sqrt(1 / ratios)
heights = sizes * np.sqrt(ratios)
center_based_anchor_bboxes = np.stack((center_xs, center_ys, widths, heights), axis=1)
center_based_anchor_bboxes = torch.from_numpy(center_based_anchor_bboxes).float()
anchor_bboxes = BBox.from_center_base(center_based_anchor_bboxes)
return anchor_bboxes
示例12: test_dist_albedo
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def test_dist_albedo(self):
"""
Test that albedos outside of the range have zero probability
"""
spec = copy.deepcopy(self.spec)
spec['modules']['PlanetPhysicalModel'] = 'FortneyMarleyCahoyMix1'
with RedirectStreams(stdout=self.dev_null):
pp = DulzPlavchan(**spec)
p = np.linspace(pp.prange[0]-1,pp.prange[1]+1,100)
fp = pp.dist_albedo(p)
self.assertTrue(np.all(fp[p < pp.prange[0]] == 0),'dist_albedo high bound failed for DulzPlavchan')
self.assertTrue(np.all(fp[p > pp.prange[1]] == 0),'dist_albedo low bound failed for DulzPlavchan')
self.assertTrue(np.all(fp[(p >= pp.prange[0]) & (p <= pp.prange[1])] > 0),'dist_albedo generates zero probabilities within range for DulzPlavchan')
示例13: test_dist_eccen
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def test_dist_eccen(self):
"""
Test that eccentricities outside of the range have zero probability
"""
for mod in self.allmods:
if 'dist_eccen' in mod.__dict__:
with RedirectStreams(stdout=self.dev_null):
pp = mod(**self.spec)
e = np.linspace(pp.erange[0]-1,pp.erange[1]+1,100)
fe = pp.dist_eccen(e)
self.assertTrue(np.all(fe[e < pp.erange[0]] == 0),'dist_eccen high bound failed for %s'%mod.__name__)
self.assertTrue(np.all(fe[e > pp.erange[1]] == 0),'dist_eccen low bound failed for %s'%mod.__name__)
self.assertTrue(np.all(fe[(e >= pp.erange[0]) & (e <= pp.erange[1])] > 0),'dist_eccen generates zero probabilities within range for %s'%mod.__name__)
示例14: test_dist_albedo
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def test_dist_albedo(self):
"""
Test that albedos outside of the range have zero probability
"""
exclude_mods = ['KeplerLike1', 'AlbedoByRadiusDulzPlavchan', 'DulzPlavchan']
for mod in self.allmods:
if (mod.__name__ not in exclude_mods) and ('dist_albedo' in mod.__dict__):
with RedirectStreams(stdout=self.dev_null):
pp = mod(**self.spec)
p = np.linspace(pp.prange[0]-1,pp.prange[1]+1,100)
fp = pp.dist_albedo(p)
self.assertTrue(np.all(fp[p < pp.prange[0]] == 0),'dist_albedo high bound failed for %s'%mod.__name__)
self.assertTrue(np.all(fp[p > pp.prange[1]] == 0),'dist_albedo low bound failed for %s'%mod.__name__)
self.assertTrue(np.all(fp[(p >= pp.prange[0]) & (p <= pp.prange[1])] > 0),'dist_albedo generates zero probabilities within range for %s'%mod.__name__)
示例15: test_ppFact_fits
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import linspace [as 別名]
def test_ppFact_fits(self):
# get fits file path for ppFact test
classpath = os.path.split(inspect.getfile(self.__class__))[0]
ppFactPath = os.path.join(classpath,'test_PostProcessing_ppFact.fits')
# fits file has values for WA in [0.1,0.2]
testWA = np.linspace(0.1,0.2,100)*u.arcsec
for mod in self.allmods:
with RedirectStreams(stdout=self.dev_null):
obj = mod(ppFact=ppFactPath,**self.specs)
vals = obj.ppFact(testWA)
self.assertTrue(np.all(vals > 0),'negative value of ppFact for %s'%mod.__name__)
self.assertTrue(np.all(vals <= 1),'ppFact > 1 for %s'%mod.__name__)