本文整理汇总了Python中scipy.logspace函数的典型用法代码示例。如果您正苦于以下问题:Python logspace函数的具体用法?Python logspace怎么用?Python logspace使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了logspace函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test
def test():
import datasource
import model
import dataset
f = Fitter()
# define source of "experimental data"
function = lambda s, i: (10.0*s/1.0)/(1.0 + s/1.0 + i/5.0)
data_source = datasource.Generated_ScanDataSource(
function,
['s', 'i'],
'v',
[scipy.logspace(-2, 2, 50), scipy.logspace(-2, 2, 10)],
noise=0.3
)
# define model
model = model.Equation_Model("Vmax*s/Ks/(1 + s/Ks + i/Ki)", ['s', 'i'])
dataset.ScanDataSet('name', f, data_source, model)
# specify the optimization algorithm, defaults to scipy_leastsq
#~ alg = algorithm.scipy_leastsq()
alg = algorithm.robust_biweight()
f.setAlgorithm(alg)
# specify the parameters to be fitted
f.addParameter('Vmax', init=1.0, min=0, max=100)
f.addParameter('Ks', init=1.0, min=0, max=10)
f.addParameter('Ki', init=1.0, min=0, max=10)
r = f.solve()
r.writeOutput()
示例2: D2_setup_scan
def D2_setup_scan(self,min1,max1,step1,min2,max2,step2):
self.P1min = min1
self.P1max = max1
self.P1steps = step1
self.P2min = min2
self.P2max = max2
self.P2steps = step2
self.P1range = scipy.logspace(scipy.log10(min1),scipy.log10(max1),step1)
self.P2range = scipy.logspace(scipy.log10(min2),scipy.log10(max2),step2)
示例3: _getParamGridFixedEffectModel
def _getParamGridFixedEffectModel(self, G0, G1, link):
if link == 'linear':
param_grid = dict(alpha=0.5*sp.logspace(-5, 5, 20))
elif link == 'logistic':
param_grid = dict(C=sp.logspace(-5, 5, 20))
else:
assert False
return param_grid
示例4: D3_setup_scan
def D3_setup_scan(self,min1,max1,step1,min2,max2,step2,min3,max3,step3):
self.P1min = min1
self.P1max = max1
self.P1steps = step1
self.P2min = min2
self.P2max = max2
self.P2steps = step2
self.P3min = min3
self.P3max = max3
self.P3steps = step3
self.P1range = scipy.logspace(scipy.log10(min1),scipy.log10(max1),step1)
self.P2range = scipy.logspace(scipy.log10(min2),scipy.log10(max2),step2)
self.P3range = scipy.logspace(scipy.log10(min3),scipy.log10(max3),step3)
示例5: degree_distrib
def degree_distrib(net, deg_type="total", node_list=None, use_weights=True,
log=False, num_bins=30):
'''
Computing the degree distribution of a network.
Parameters
----------
net : :class:`~nngt.Graph` or subclass
the network to analyze.
deg_type : string, optional (default: "total")
type of degree to consider ("in", "out", or "total").
node_list : list or numpy.array of ints, optional (default: None)
Restrict the distribution to a set of nodes (default: all nodes).
use_weights : bool, optional (default: True)
use weighted degrees (do not take the sign into account: all weights
are positive).
log : bool, optional (default: False)
use log-spaced bins.
Returns
-------
counts : :class:`numpy.array`
number of nodes in each bin
deg : :class:`numpy.array`
bins
'''
ia_node_deg = net.get_degrees(node_list, deg_type, use_weights)
ra_bins = sp.linspace(ia_node_deg.min(), ia_node_deg.max(), num_bins)
if log:
ra_bins = sp.logspace(sp.log10(sp.maximum(ia_node_deg.min(),1)),
sp.log10(ia_node_deg.max()), num_bins)
counts,deg = sp.histogram(ia_node_deg, ra_bins)
ia_indices = sp.argwhere(counts)
return counts[ia_indices], deg[ia_indices]
示例6: default_frequency_range
def default_frequency_range(syslist):
"""Compute a reasonable default frequency range for frequency
domain plots.
Finds a reasonable default frequency range by examining the features
(poles and zeros) of the systems in syslist.
Parameters
----------
syslist : list of Lti
List of linear input/output systems (single system is OK)
Returns
-------
omega : array
Range of frequencies in rad/sec
Examples
--------
>>> from matlab import ss
>>> sys = ss("1. -2; 3. -4", "5.; 7", "6. 8", "9.")
>>> omega = default_frequency_range(sys)
"""
# This code looks at the poles and zeros of all of the systems that
# we are plotting and sets the frequency range to be one decade above
# and below the min and max feature frequencies, rounded to the nearest
# integer. It excludes poles and zeros at the origin. If no features
# are found, it turns logspace(-1, 1)
# Find the list of all poles and zeros in the systems
features = np.array(())
# detect if single sys passed by checking if it is sequence-like
if (not getattr(syslist, '__iter__', False)):
syslist = (syslist,)
for sys in syslist:
try:
# Add new features to the list
features = np.concatenate((features, np.abs(sys.pole())))
features = np.concatenate((features, np.abs(sys.zero())))
except:
pass
# Get rid of poles and zeros at the origin
features = features[features != 0];
# Make sure there is at least one point in the range
if (features.shape[0] == 0): features = [1];
# Take the log of the features
features = np.log10(features)
#! TODO: Add a check in discrete case to make sure we don't get aliasing
# Set the range to be an order of magnitude beyond any features
omega = sp.logspace(np.floor(np.min(features))-1,
np.ceil(np.max(features))+1)
return omega
示例7: fit
def fit(self, kk=None):
"""
Fit Fourier spectrum with the function set at class instantination
==> NB: fitting is done in logarithmic coordinates
and fills plotting arrays with data
--------
Options:
--------
kk
(k1,k2) <None> spectral interval for function fitting
by default interval [ kk[1], kk[imax__kk] ] will be fitted
==> i.e. k=0 is excluded
"""
# fitting interval
if kk:
ik_min=(self.fft_data.kk[1:self.fft_data.imax__kk]<=kk[0]).nonzero()[0][-1]
ik_max=(self.fft_data.kk[1:self.fft_data.imax__kk]<=kk[1]).nonzero()[0][-1]
else:
ik_min=1;
ik_max=self.fft_data.imax__kk
# do fitting
self.__popt,self.__pcov = scipy.optimize.curve_fit(self.__func_fit,
scipy.log(self.fft_data.kk[ik_min:ik_max]),
scipy.log(self.fft_data.Ik[ik_min:ik_max]) )
# boundaries of fitted interval
self.kmin = self.fft_data.kk[ik_min]
self.kmax = self.fft_data.kk[ik_max]
# fill plot arrays <===============
self.kk_plot=scipy.logspace( scipy.log10(self.kmin),
scipy.log10(self.kmax),
self.nk_plot )
self.Ik_plot=self.fitting_function(self.kk_plot)
示例8: compute_rls
def compute_rls(data_file, output_filename, rls_type=DEFAULT_RLS, save_out=DEFAULT_SAVE):
"""
data file contains sampels and labels saved as a mat file
with respective keywords. Make your own data wrapper if needed
"""
if path.splitext(output_filename)[-1] != ".mat":
output_filename += ".mat"
if path.splitext(data_file)[-1] != ".mat":
raise ValueError, "mat file needed"
data = loadmat(data_file)
X = data["samples"]
Y = data["labels"]
lambdas = sp.logspace(-6, 6, 30)
if rls_type.lower() == "linear":
w, loos = lrlsloo(X, Y, lambdas)
elif rls_type.lower() == "nonlinear":
w, loos = rlsloo(X, Y, lambdas)
else:
print "ERROR: specify linear or nonlinear"
if save_out:
out_data = {"weights": w, "loos": loos}
savemat(out_fname, out_data)
示例9: run
def run(self, npts=25, inv_points=None, access_limited=True, **kwargs):
r"""
Parameters
----------
npts : int (default = 25)
The number of pressure points to apply. The list of pressures
is logarithmically spaced between the lowest and highest throat
entry pressures in the network.
inv_points : array_like, optional
A list of specific pressure point(s) to apply.
"""
if 'inlets' in kwargs.keys():
logger.info('Inlets recieved, passing to set_inlets')
self.set_inlets(pores=kwargs['inlets'])
if 'outlets' in kwargs.keys():
logger.info('Outlets recieved, passing to set_outlets')
self.set_outlets(pores=kwargs['outlets'])
self._AL = access_limited
if inv_points is None:
logger.info('Generating list of invasion pressures')
min_p = sp.amin(self['throat.entry_pressure']) * 0.98 # nudge down
max_p = sp.amax(self['throat.entry_pressure']) * 1.02 # bump up
inv_points = sp.logspace(sp.log10(min_p),
sp.log10(max_p),
npts)
self._npts = sp.size(inv_points)
# Execute calculation
self._do_outer_iteration_stage(inv_points)
示例10: create_grid
def create_grid(r_in, r_out, nshell, space = 'powerlaw1', end = True):
# function to create grid
if space == 'log10':
from scipy import log10, logspace
# get the exponent of the start- and
# stop-radius in input units
start = [log10(r_in), 0][r_in == 0]
stop = log10(r_out)
radii = logspace(start, stop, num=nshell, endpoint=end)
elif space == "powerlaw1":
from scipy import arange
radii = r_in * (r_out/r_in)**(arange(nshell)/(nshell - 1.0))
elif space == 'linear':
from scipy import linspace
# linearly spaced grid
radii = linspace(r_in, r_out, num=nshell, endpoint=end)
elif space == 'powerlaw2':
from scipy import linspace
# first check if coefficients to the power-law was given
#~ if 'exp' in kwargs:
#~ p_exp = kwargs['exp']
#~ else: # if not, set it to 2, i.e. r^2
#~ p_exp = 2
radii = r_in + (r_out - r_in)*(linspace(r_in, r_out, num=nshell, endpoint=end)/(r_out))**2
#pr_int('Not implemented yet.')
#raise ParError(spaced)
else:
raise Exception(space)
return radii
示例11: add_axis
def add_axis(self, param, start, stop, steps, logspace=False):
"""Add a parameter discretization axis to the the grid
Arguments
---------
param : string
The name of the model parameter.
start : float
The starting value of the model parameter.
stop : float
The ending value of the model parameter.
steps : integer
The number of steps to insert between the start and stop.
logspace : boolean
Space the steps logarithmically?
Returns
-------
None
"""
assert param in self.sim.get_model_params().keys()
if logspace:
self._grid_pts.append( scipy.logspace(start,stop,steps) )
else:
self._grid_pts.append( scipy.linspace(start,stop,steps) )
self._grid_size *= len(self._grid_pts[-1])
self._grid_order.append(param)
示例12: _make_forces
def _make_forces(self, extreme_forces, num):
a = extreme_forces[0]
b = extreme_forces[1]
c = extreme_forces[2]
#print a, b, c, num
forces = numpy.append(
b -( scipy.logspace(scipy.log10(a), scipy.log10(b),
num=num/2+1) - a),
scipy.logspace(scipy.log10(b), scipy.log10(c),
num=num-num/2)[1:]
)
forces = numpy.array( sorted(list(set(forces))) )
if len(forces) != num:
Exception("problem with forces: length ", len(forces))
#print forces
#for i in range(len(forces)):
# f = forces[i]
# rand = random.uniform( 0.99*f, 1.01*f)
# forces[i] = rand
return forces
示例13: plot
def plot(self, indice):
self.diagrama.ax.clear()
self.diagrama.ax.set_xlim(0.1, 10)
self.diagrama.ax.set_ylim(0, 1)
self.diagrama.ax.set_xscale("log")
self.diagrama.ax.set_title(QtWidgets.QApplication.translate(
"pychemqt", "Heat Transfer Temperature Effectiveness"), size='12')
self.diagrama.ax.set_xlabel("NTU", size='12')
self.diagrama.ax.set_ylabel("P", size='14')
self.diagrama.ax.set_xticklabels(["0.1", "1.0", "10"])
xticklabels = ["0.2", "0.3", "", "0.5", "", "0.7", "", "", "2.0",
"3.0", "", "5.0", "", "7.0", "", ""]
self.diagrama.ax.set_xticklabels(xticklabels, minor=True)
flujo = self.flujo[indice][1]
self.mixed.setVisible(flujo == "CrFSMix")
kwargs = {}
if flujo == "CrFSMix":
kwargs["mixed"] = str(self.mixed.currentText())
R = [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1., 1.2, 1.4, 1.6, 1.8,
2., 2.5, 3., 4., 6., 8., 10., 15.]
NTU = logspace(-1.5, 1, 100)
for ri in R:
e = [0]+[TemperatureEffectiveness(N, ri, flujo, **kwargs) for N in NTU[1:]]
self.diagrama.plot(NTU, e, "k")
self.diagrama.ax.annotate(" R=%0.1f" % ri, (NTU[-1], e[-1]),
size="medium", ha="left", va="center")
# F=[0.3]
# for f in F:
# p=[]
# NTU=[]
# for r in R:
# func=lambda P: CorrectionFactor(P, r, flujo)-f
# print func(0.)
# pi=fsolve(func, 0.2)
# p.append(pi)
# NTU.append(NTU_fPR(p, r, flujo))
# p=[fsolve(lambda P: CorrectionFactor(P, r, flujo)-f, 0.5)[0] for r in R]
# NTU=[NTU_fPR(pi, ri) for pi, ni in zip(p, R)]
# self.diagrama.plot(NTU, p, "--")
self.diagrama.draw()
if flujo == "CrFSMix" and self.mixed.currentIndex():
img = image.imread('images/equation/%s2.png' % flujo)
else:
img = image.imread('images/equation/%s.png' % flujo)
self.image.set_data(img)
self.refixImage()
示例14: run
def run(self, npts=25, inv_pressures=None):
r"""
Run the algorithm for specified number of points or at given capillary
pressures.
Parameters
----------
npts : scalar
The number of points to obtain on the curve. The points are
automatically selected to span the range of capillary pressures
using a logarithmic spacing (more points are lower capillary
pressure values).
inv_pressures : array_like
A list of capillary pressures to apply. List should contain
increasing and unique values.
"""
# If no invasion points are given then generate some
if inv_pressures is None:
logger.info('Generating list of invasion pressures')
min_p = sp.amin(self['throat.entry_pressure']) * 0.98 # nudge down
max_p = sp.amax(self['throat.entry_pressure']) * 1.02 # bump up
inv_points = sp.logspace(sp.log10(min_p),
sp.log10(max_p),
npts)
else:
# Make sure the given invastion points are sensible
inv_points = sp.unique(inv_pressures)
self._inv_points = inv_points
# Ensure inlets are set
if sp.sum(self['pore.inlets']) == 0:
raise Exception('Inlet pores have not been specified')
# Ensure outlet pores are set if trapping is enabled
if self._trapping:
if sp.sum(self['pore.outlets']) == 0:
raise Exception('Outlet pores have not been specified')
# Generate curve from points
for inv_val in self._inv_points:
# Apply one applied pressure and determine invaded pores
logger.info('Applying capillary pressure: ' + str(inv_val))
self._apply_percolation(inv_val)
if self._trapping:
logger.info('Checking for trapping')
self._check_trapping(inv_val)
# Find invasion sequence values (to correspond with IP algorithm)
Pinv = self['pore.inv_Pc']
self['pore.inv_seq'] = sp.searchsorted(sp.unique(Pinv), Pinv)
Tinv = self['throat.inv_Pc']
self['throat.inv_seq'] = sp.searchsorted(sp.unique(Tinv), Tinv)
示例15: setScanJobs
def setScanJobs(self, start, end, intervals, job, log=False):
"""Splits a range into a number of jobs with intervals"""
assert intervals >= 1, '\n* Minimum of 1 interval'
if log:
kpoints = scipy.logspace(scipy.log10(start), scipy.log10(end), intervals+1)
else:
kpoints = scipy.linspace(start, end, intervals+1)
self.job_list = []
for p in range(len(kpoints)-1):
job2 = job % (kpoints[p], kpoints[p+1])
self.job_list.append(job2)
print(job2)