def deriveKernel(self, params, i):
self.checkParamsI(params, i)
ell = np.exp(params[0])
p = np.exp(params[1])
#compute d2
if (self.K_sq is None): d2 = sq_dist(self.X_scaled.T / ell) #precompute squared distances
else: d2 = self.K_sq / ell**2
#compute dp
dp = self.dp/p
K = np.exp(-d2 / 2.0)
if (i==0): return d2*K*np.cos(2*np.pi*dp)
elif (i==1): return 2*np.pi*dp*np.sin(2*np.pi*dp)*K
else: raise Exception('invalid parameter index:' + str(i))
python类sin()的实例源码
def _generate_data():
"""
?????
????u(k-1) ? y(k-1)?????y(k)
"""
# u = np.random.uniform(-1,1,200)
# y=[]
# former_y_value = 0
# for i in np.arange(0,200):
# y.append(former_y_value)
# next_y_value = (29.0 / 40) * np.sin(
# (16.0 * u[i] + 8 * former_y_value) / (3.0 + 4.0 * (u[i] ** 2) + 4 * (former_y_value ** 2))) \
# + (2.0 / 10) * u[i] + (2.0 / 10) * former_y_value
# former_y_value = next_y_value
# return u,y
u1 = np.random.uniform(-np.pi,np.pi,200)
u2 = np.random.uniform(-1,1,200)
y = np.zeros(200)
for i in range(200):
value = np.sin(u1[i]) + u2[i]
y[i] = value
return u1, u2, y
def rotate_point_cloud(batch_data):
""" Randomly rotate the point clouds to augument the dataset
rotation is per shape based along up direction
Input:
BxNx3 array, original batch of point clouds
Return:
BxNx3 array, rotated batch of point clouds
"""
rotated_data = np.zeros(batch_data.shape, dtype=np.float32)
for k in range(batch_data.shape[0]):
rotation_angle = np.random.uniform() * 2 * np.pi
cosval = np.cos(rotation_angle)
sinval = np.sin(rotation_angle)
rotation_matrix = np.array([[cosval, 0, sinval],
[0, 1, 0],
[-sinval, 0, cosval]])
shape_pc = batch_data[k, ...]
rotated_data[k, ...] = np.dot(shape_pc.reshape((-1, 3)), rotation_matrix)
return rotated_data
def rotate_point_cloud_by_angle(batch_data, rotation_angle):
""" Rotate the point cloud along up direction with certain angle.
Input:
BxNx3 array, original batch of point clouds
Return:
BxNx3 array, rotated batch of point clouds
"""
rotated_data = np.zeros(batch_data.shape, dtype=np.float32)
for k in range(batch_data.shape[0]):
#rotation_angle = np.random.uniform() * 2 * np.pi
cosval = np.cos(rotation_angle)
sinval = np.sin(rotation_angle)
rotation_matrix = np.array([[cosval, 0, sinval],
[0, 1, 0],
[-sinval, 0, cosval]])
shape_pc = batch_data[k, ...]
rotated_data[k, ...] = np.dot(shape_pc.reshape((-1, 3)), rotation_matrix)
return rotated_data
def monotoneTFosc(f):
"""Maps [-inf,inf] to [-inf,inf] with different constants
for positive and negative part.
"""
if np.isscalar(f):
if f > 0.:
f = np.log(f) / 0.1
f = np.exp(f + 0.49 * (np.sin(f) + np.sin(0.79 * f))) ** 0.1
elif f < 0.:
f = np.log(-f) / 0.1
f = -np.exp(f + 0.49 * (np.sin(0.55 * f) + np.sin(0.31 * f))) ** 0.1
return f
else:
f = np.asarray(f)
g = f.copy()
idx = (f > 0)
g[idx] = np.log(f[idx]) / 0.1
g[idx] = np.exp(g[idx] + 0.49 * (np.sin(g[idx]) + np.sin(0.79 * g[idx])))**0.1
idx = (f < 0)
g[idx] = np.log(-f[idx]) / 0.1
g[idx] = -np.exp(g[idx] + 0.49 * (np.sin(0.55 * g[idx]) + np.sin(0.31 * g[idx])))**0.1
return g
def test_pitch_estimation(self):
"""
test pitch estimation algo with contrived small example
if pitch is within 5 Hz, then say its good (for this small example,
since the algorithm wasn't made for this type of synthesized signal)
"""
cfg = ExperimentConfig(pitch_strength_thresh=-np.inf)
# the next 3 variables are in Hz
tolerance = 5
fs = 48000
f = 150
# create a sine wave of f Hz freq sampled at fs Hz
x = np.sin(2*np.pi * f/fs * np.arange(2**10))
# estimate the pitch, it should be close to f
p, t, s = pest.pitch_estimation(x, fs, cfg)
self.assertTrue(np.all(np.abs(p - f) < tolerance))
def make_wafer(self,wafer_r,frame,label,labelloc,labelwidth):
"""
Generate wafer with primary flat on the left. From https://coresix.com/products/wafers/ I estimated that the angle defining the wafer flat to arctan(flat/2 / radius)
"""
angled = 18
angle = angled*np.pi/180
circ = cad.shapes.Circle((0,0), wafer_r, width=self.boxwidth, initial_angle=180+angled, final_angle=360+180-angled, layer=self.layer_box)
flat = cad.core.Path([(-wafer_r*np.cos(angle),wafer_r*np.sin(angle)),(-wafer_r*np.cos(angle),-wafer_r*np.sin(angle))], width=self.boxwidth, layer=self.layer_box)
date = time.strftime("%d/%m/%Y")
if labelloc==(0,0):
labelloc=(-2e3,wafer_r-1e3)
# The label is added 100 um on top of the main cell
label_grid_chip = cad.shapes.LineLabel( self.name + " " +\
date,500,position=labelloc,
line_width=labelwidth,
layer=self.layer_label)
if frame==True:
self.add(circ)
self.add(flat)
if label==True:
self.add(label_grid_chip)
def ani_update(arg, ii=[0]):
i = ii[0] # don't ask...
if np.isclose(t_arr[i], np.around(t_arr[i], 1)):
fig2.suptitle('Evolution (Time: {})'.format(t_arr[i]), fontsize=24)
graphic_floor[0].set_data([-floor_lim*np.cos(incline_history[i]) + radius*np.sin(incline_history[i]), floor_lim*np.cos(incline_history[i]) + radius*np.sin(incline_history[i])], [-floor_lim*np.sin(incline_history[i])-radius*np.cos(incline_history[i]), floor_lim*np.sin(incline_history[i])-radius*np.cos(incline_history[i])])
graphic_wheel.center = (x_history[i], y_history[i])
graphic_ind[0].set_data([x_history[i], x_history[i] + radius*np.sin(w_history[i])],
[y_history[i], y_history[i] + radius*np.cos(w_history[i])])
graphic_pend[0].set_data([x_history[i], x_history[i] - cw_to_cm[1]*np.sin(q_history[i, 2])],
[y_history[i], y_history[i] + cw_to_cm[1]*np.cos(q_history[i, 2])])
graphic_dist[0].set_data([x_history[i] - cw_to_cm[1]*np.sin(q_history[i, 2]), x_history[i] - cw_to_cm[1]*np.sin(q_history[i, 2]) - pscale*p_history[i]*np.cos(q_history[i, 2])],
[y_history[i] + cw_to_cm[1]*np.cos(q_history[i, 2]), y_history[i] + cw_to_cm[1]*np.cos(q_history[i, 2]) - pscale*p_history[i]*np.sin(q_history[i, 2])])
ii[0] += int(1 / (timestep * framerate))
if ii[0] >= len(t_arr):
print("Resetting animation!")
ii[0] = 0
return [graphic_floor, graphic_wheel, graphic_ind, graphic_pend, graphic_dist]
# Run animation
def solveIter(mu,e):
"""__solvIter returns an iterative solution for Ek
Mk = Ek - e sin(Ek)
"""
thisStart = np.asarray(mu-1.01*e)
thisEnd = np.asarray(mu + 1.01*e)
bestGuess = np.zeros(mu.shape)
for i in range(5):
minErr = 10000*np.ones(mu.shape)
for j in range(5):
thisGuess = thisStart + j*(thisEnd-thisStart)/10.0
thisErr = np.asarray(abs(mu - thisGuess + e*np.sin(thisGuess)))
mask = thisErr<minErr
minErr[mask] = thisErr[mask]
bestGuess[mask] = thisGuess[mask]
# reset for next loop
thisRange = thisEnd - thisStart
thisStart = bestGuess - thisRange/10.0
thisEnd = bestGuess + thisRange/10.0
return(bestGuess)
def great_circle_dist(p1, p2):
"""Return the distance (in km) between two points in
geographical coordinates.
"""
lon0, lat0 = p1
lon1, lat1 = p2
EARTH_R = 6372.8
lat0 = np.radians(float(lat0))
lon0 = np.radians(float(lon0))
lat1 = np.radians(float(lat1))
lon1 = np.radians(float(lon1))
dlon = lon0 - lon1
y = np.sqrt(
(np.cos(lat1) * np.sin(dlon)) ** 2
+ (np.cos(lat0) * np.sin(lat1)
- np.sin(lat0) * np.cos(lat1) * np.cos(dlon)) ** 2)
x = np.sin(lat0) * np.sin(lat1) + \
np.cos(lat0) * np.cos(lat1) * np.cos(dlon)
c = np.arctan2(y, x)
return EARTH_R * c
def x_axis_rotation(theta):
"""Generates a 3x3 rotation matrix for a rotation of angle
theta about the x axis.
Parameters
----------
theta : float
amount to rotate, in radians
Returns
-------
:obj:`numpy.ndarray` of float
A random 3x3 rotation matrix.
"""
R = np.array([[1, 0, 0,],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]])
return R
def y_axis_rotation(theta):
"""Generates a 3x3 rotation matrix for a rotation of angle
theta about the y axis.
Parameters
----------
theta : float
amount to rotate, in radians
Returns
-------
:obj:`numpy.ndarray` of float
A random 3x3 rotation matrix.
"""
R = np.array([[np.cos(theta), 0, np.sin(theta)],
[0, 1, 0],
[-np.sin(theta), 0, np.cos(theta)]])
return R
def z_axis_rotation(theta):
"""Generates a 3x3 rotation matrix for a rotation of angle
theta about the z axis.
Parameters
----------
theta : float
amount to rotate, in radians
Returns
-------
:obj:`numpy.ndarray` of float
A random 3x3 rotation matrix.
"""
R = np.array([[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]])
return R
def sph2cart(r, az, elev):
""" Convert spherical to cartesian coordinates.
Attributes
----------
r : float
radius
az : float
aziumth (angle about z axis)
elev : float
elevation from xy plane
Returns
-------
float
x-coordinate
float
y-coordinate
float
z-coordinate
"""
x = r * np.cos(az) * np.sin(elev)
y = r * np.sin(az) * np.sin(elev)
z = r * np.cos(elev)
return x, y, z
def mdst(x, odd=True):
""" Calculate modified discrete sine transform of input signal in an
inefficient pure-Python method.
Use only for testing.
Parameters
----------
X : array_like
The input signal
odd : boolean, optional
Switch to oddly stacked transform. Defaults to :code:`True`.
Returns
-------
out : array_like
The output signal
"""
return trans(x, func=numpy.sin, odd=odd) * numpy.sqrt(2)
def imdst(X, odd=True):
""" Calculate inverse modified discrete sine transform of input
signal in an inefficient pure-Python method.
Use only for testing.
Parameters
----------
X : array_like
The input signal
odd : boolean, optional
Switch to oddly stacked transform. Defaults to :code:`True`.
Returns
-------
out : array_like
The output signal
"""
return itrans(X, func=numpy.sin, odd=odd) * numpy.sqrt(2)
def cmdct(x, odd=True):
""" Calculate complex modified discrete cosine transform of input
inefficient pure-Python method.
Use only for testing.
Parameters
----------
X : array_like
The input signal
odd : boolean, optional
Switch to oddly stacked transform. Defaults to :code:`True`.
Returns
-------
out : array_like
The output signal
"""
return trans(x, func=lambda x: numpy.cos(x) - 1j * numpy.sin(x), odd=odd)
def icmdct(X, odd=True):
""" Calculate inverse complex modified discrete cosine transform of input
signal in an inefficient pure-Python method.
Use only for testing.
Parameters
----------
X : array_like
The input signal
odd : boolean, optional
Switch to oddly stacked transform. Defaults to :code:`True`.
Returns
-------
out : array_like
The output signal
"""
return itrans(X, func=lambda x: numpy.cos(x) + 1j * numpy.sin(x), odd=odd)
def test_with_fake_log_prob(self):
np.random.seed(42)
def grad_log_prob(x):
return -(x/2.0 + np.sin(x))*(1.0/2.0 + np.cos(x))
def fake_log_prob(x):
return -(x/5.0 + np.sin(x) )**2.0/2.0
generator = mh_generator(log_density=fake_log_prob,x_start=1.0)
tester = GaussianSteinTest(grad_log_prob,41)
selector = SampleSelector(generator, sample_size=1000,thinning=20,tester=tester, max_iterations=5)
data,converged = selector.points_from_stationary()
assert converged is False
def test_with_ugly(self):
np.random.seed(42)
def grad_log_prob(x):
return -(x/5.0 + np.sin(x))*(1.0/5.0 + np.cos(x))
def log_prob(x):
return -(x/5.0 + np.sin(x) )**2.0/2.0
generator = mh_generator(log_density=log_prob,x_start=1.0)
tester = GaussianSteinTest(grad_log_prob,41)
selector = SampleSelector(generator, sample_size=1000,thinning=20,tester=tester, max_iterations=5)
data,converged = selector.points_from_stationary()
tester = GaussianSteinTest(grad_log_prob,41)
assert tester.compute_pvalue(data)>0.05
assert converged is True
def bandpass(self, rin, sin, rout, sout):
''' To create a band pass two circle images are created, one inverted
and pasted into dthe other'''
# if radius zero dont create the inner circle
if rin != 0:
self.create_circle_mask(rin, sin)
else:
self.data = np.zeros(self.data.shape)
# create the outer circle
bigcircle = deepcopy(self)
bigcircle.create_circle_mask(rout, sout)
bigcircle.invert()
# sum the two pictures
m = (self + bigcircle)
# limit fro 0 to 1 and invert
m.limit(1)
m.invert()
self.data = m.data
def random_points_in_circle(n,xx,yy,rr):
"""
get n random points in a circle.
"""
rnd = random(size=(n,3))
t = TWOPI*rnd[:,0]
u = rnd[:,1:].sum(axis=1)
r = zeros(n,'float')
mask = u>1.
xmask = logical_not(mask)
r[mask] = 2.-u[mask]
r[xmask] = u[xmask]
xyp = reshape(rr*r,(n,1))*column_stack( (cos(t),sin(t)) )
dartsxy = xyp + array([xx,yy])
return dartsxy
def get_data(filename,headers,ph_units):
# Importation des données .DAT
dat_file = np.loadtxt("%s"%(filename),skiprows=headers,delimiter=',')
labels = ["freq", "amp", "pha", "amp_err", "pha_err"]
data = {l:dat_file[:,i] for (i,l) in enumerate(labels)}
if ph_units == "mrad":
data["pha"] = data["pha"]/1000 # mrad to rad
data["pha_err"] = data["pha_err"]/1000 # mrad to rad
if ph_units == "deg":
data["pha"] = np.radians(data["pha"]) # deg to rad
data["pha_err"] = np.radians(data["pha_err"]) # deg to rad
data["phase_range"] = abs(max(data["pha"])-min(data["pha"])) # Range of phase measurements (used in NRMS error calculation)
data["Z"] = data["amp"]*(np.cos(data["pha"]) + 1j*np.sin(data["pha"]))
EI = np.sqrt(((data["amp"]*np.cos(data["pha"])*data["pha_err"])**2)+(np.sin(data["pha"])*data["amp_err"])**2)
ER = np.sqrt(((data["amp"]*np.sin(data["pha"])*data["pha_err"])**2)+(np.cos(data["pha"])*data["amp_err"])**2)
data["Z_err"] = ER + 1j*EI
# Normalization of amplitude
data["Z_max"] = max(abs(data["Z"])) # Maximum amplitude
zn, zn_e = data["Z"]/data["Z_max"], data["Z_err"]/data["Z_max"] # Normalization of impedance by max amplitude
data["zn"] = np.array([zn.real, zn.imag]) # 2D array with first column = real values, second column = imag values
data["zn_err"] = np.array([zn_e.real, zn_e.imag]) # 2D array with first column = real values, second column = imag values
return data
def get_data(filename,headers,ph_units):
# Importation des données .DAT
dat_file = np.loadtxt("%s"%(filename),skiprows=headers,delimiter=',')
labels = ["freq", "amp", "pha", "amp_err", "pha_err"]
data = {l:dat_file[:,i] for (i,l) in enumerate(labels)}
if ph_units == "mrad":
data["pha"] = data["pha"]/1000 # mrad to rad
data["pha_err"] = data["pha_err"]/1000 # mrad to rad
if ph_units == "deg":
data["pha"] = np.radians(data["pha"]) # deg to rad
data["pha_err"] = np.radians(data["pha_err"]) # deg to rad
data["phase_range"] = abs(max(data["pha"])-min(data["pha"])) # Range of phase measurements (used in NRMS error calculation)
data["Z"] = data["amp"]*(np.cos(data["pha"]) + 1j*np.sin(data["pha"]))
EI = np.sqrt(((data["amp"]*np.cos(data["pha"])*data["pha_err"])**2)+(np.sin(data["pha"])*data["amp_err"])**2)
ER = np.sqrt(((data["amp"]*np.sin(data["pha"])*data["pha_err"])**2)+(np.cos(data["pha"])*data["amp_err"])**2)
data["Z_err"] = ER + 1j*EI
# Normalization of amplitude
data["Z_max"] = max(abs(data["Z"])) # Maximum amplitude
zn, zn_e = data["Z"]/data["Z_max"], data["Z_err"]/data["Z_max"] # Normalization of impedance by max amplitude
data["zn"] = np.array([zn.real, zn.imag]) # 2D array with first column = real values, second column = imag values
data["zn_err"] = np.array([zn_e.real, zn_e.imag]) # 2D array with first column = real values, second column = imag values
return data
def genSphCoords():
""" Generates cartesian (x,y,z) and spherical (theta, phi) coordinates of a sphere
Returns
-------
coords : named tuple
holds cartesian (x,y,z) and spherical (theta, phi) coordinates
"""
coords = namedtuple('coords', ['x', 'y', 'z', 'az', 'el'])
az = _np.linspace(0, 2 * _np.pi, 360)
el = _np.linspace(0, _np.pi, 181)
coords.x = _np.outer(_np.cos(az), _np.sin(el))
coords.y = _np.outer(_np.sin(az), _np.sin(el))
coords.z = _np.outer(_np.ones(360), _np.cos(el))
coords.el, coords.az = _np.meshgrid(_np.linspace(0, _np.pi, 181),
_np.linspace(0, 2 * _np.pi, 360))
return coords
def sph2cartMTX(vizMTX):
""" Converts the spherical vizMTX data to named tuple contaibubg .xs/.ys/.zs
Parameters
----------
vizMTX : array_like
[180 x 360] matrix that hold amplitude information over phi and theta
Returns
-------
V : named_tuple
Contains .xs, .ys, .zs cartesian coordinates
"""
rs = _np.abs(vizMTX.reshape((181, -1)).T)
coords = genSphCoords()
V = namedtuple('V', ['xs', 'ys', 'zs'])
V.xs = rs * _np.sin(coords.el) * _np.cos(coords.az)
V.ys = rs * _np.sin(coords.el) * _np.sin(coords.az)
V.zs = rs * _np.cos(coords.el)
return V
def convert_cof_mag2mass(t0, te, u0, alpha, s, q):
"""
function to convert from center of magnification to center of mass
coordinates. Note that this function is for illustration only. It has
not been tested and may have sign errors.
"""
if s <= 1.0:
return t0, u0
else:
delta = q / (1. + q) / s
delta_u0 = delta * np.sin(alpha * np.pi / 180.)
delta_tau = delta * np.cos(alpha * np.pi / 180.)
t0_prime = t0 + delta_tau * te
u0_prime = u0 + delta_u0
return t0_prime, u0_prime
#Define model parameters in CoMAGN system
def _B_0_function(self, z):
"""
calculate B_0(z) function defined in:
Gould A. 1994 ApJ 421L, 71 "Proper motions of MACHOs
http://adsabs.harvard.edu/abs/1994ApJ...421L..71G
Yoo J. et al. 2004 ApJ 603, 139 "OGLE-2003-BLG-262: Finite-Source
Effects from a Point-Mass Lens"
http://adsabs.harvard.edu/abs/2004ApJ...603..139Y
"""
out = 4. * z / np.pi
function = lambda x: (1.-value**2*np.sin(x)**2)**.5
for (i, value) in enumerate(z):
if value < 1.:
out[i] *= ellipe(value*value)
else:
out[i] *= integrate.quad(function, 0., np.arcsin(1./value))[0]
return out
edge_canny_get_orientation_sector.py 文件源码
项目:Image-Processing-Algorithms
作者: machinelearninggod
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def get_orientation_sector(dx,dy):
# rotate (dx,dy) by pi/8
rotation = np.array([[np.cos(np.pi/8), -np.sin(np.pi/8)],
[np.sin(np.pi/8), np.cos(np.pi/8)]])
rotated = np.dot(rotation, np.array([[dx], [dy]]))
if rotated[1] < 0:
rotated[0] = -rotated[0]
rotated[1] = -rotated[1]
s_theta = -1
if rotated[0] >= 0 and rotated[0] >= rotated[1]:
s_theta = 0
elif rotated[0] >= 0 and rotated[0] < rotated[1]:
s_theta = 1
elif rotated[0] < 0 and -rotated[0] < rotated[1]:
s_theta = 2
elif rotated[0] < 0 and -rotated[0] >= rotated[1]:
s_theta = 3
return s_theta
def to_radec(coords, xc=0, yc=0):
"""
Convert the generated coordinates to (ra, dec) (unit: degree).
xc, yc: the center coordinate (ra, dec)
"""
results = []
for r, theta in coords:
# FIXME: spherical algebra should be used!!!
dx = r * np.cos(theta*np.pi/180)
dy = r * np.sin(theta*np.pi/180)
x = xc + dx
y = yc + dy
results.append((x, y))
if len(results) == 1:
return results[0]
else:
return results