I am trying to get the numpy code into tensorflow. But when I run the session I am getting the below error.
Here is the code:
def cal_anchors():
# Output:
# anchors: (w, l, 2, 7) x y z h w l r
x = np.linspace(0,48,240) #48/.2
y = np.linspace(20,-20,200) #40/.2
cx, cy = np.meshgrid(x, y)
# all is (w, l, 2)
cx = np.tile(cx[..., np.newaxis], 2)
cy = np.tile(cy[..., np.newaxis], 2)
cz = np.ones_like(cx) * (-1.465)
w = np.ones_like(cx) * 0.6
l = np.ones_like(cx) * 0.8
h = np.ones_like(cx) * 1.73
r = np.ones_like(cx) #(200,240,2)
print(r.shape)
r[..., 0] = 0 # 0 #(200,240,1)
r[..., 1] = 90 / 180 * np.pi # 90
# 7*(w,l,2) -> (w, l, 2, 7)
anchors = np.stack([cx, cy, cz, h, w, l, r], axis=-1)
return anchors
print(cal_anchors().shape) #(200,240,2,7)
#tensorflow code
def anchors():
x = tf.linspace(0.0,48.0,240)
y = tf.linspace(-20.0,20.0,200)
cx,cy = tf.meshgrid(x,y)
cx = tf.expand_dims(cx,2)
cy = tf.expand_dims(cy,2)
cx = tf.tile(cx,2)
cy = tf.tile(cy,2)
cz = tf.ones_like(cx)
w = tf.ones_like(cx)
l = tf.ones_like(cx)
h = tf.ones_like(cx)
r = ones_like(cx)
r[:,:,0] = 0
pi = tf.constant(3.141592)
r[:,:,1] = tf.math.divide(90,tf.math.multiply(180,pi))
anchros = tf.stack([cx,cy,cz,h,w,l,r],axis=-1,name="anchors")
sess = tf.Session()
sess.run(tf.global_variables_initializer())
result = sess.run(anchros)
print(result.shape)
anchors()
I am getting the below error:
File "anchros.py", line 39, in anchors
cx = tf.tile(cx,2)
File "/home/surendra/venv/tensorflow2/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py", line 11450, in tile
_ops.raise_from_not_ok_status(e, name)
File "/home/surendra/venv/tensorflow2/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 6862, in raise_from_not_ok_status
six.raise_from(core._status_to_exception(e.code, message), None)
File "", line 3, in raise_from
tensorflow.python.framework.errors_impl.InvalidArgumentError: Expected multiples to be 1-D, but got shape [] [Op:Tile]
Can anyone help me with this?
Thanks in advance
Couple of issues there, this should work:
def anchors():
x = tf.linspace(0.0, 48.0, 240)
y = tf.linspace(-20.0, 20.0, 200)
cx, cy = tf.meshgrid(x, y)
cx = tf.expand_dims(cx, 2)
cy = tf.expand_dims(cy, 2)
cx = tf.tile(cx, [1,1,2])
cy = tf.tile(cy, [1,1,2])
cz = tf.ones_like(cx)
w = tf.ones_like(cx)
l = tf.ones_like(cx)
h = tf.ones_like(cx)
r = tf.Variable(initial_value=tf.ones_like(cx))
r[:, :, 0].assign(tf.zeros(r.shape[:2]))
pi = tf.constant(3.141592)
r[:, :, 1].assign(tf.multiply(tf.math.divide(90., tf.math.multiply(180., pi)), tf.ones(r.shape[:2])))
anchros = tf.stack([cx, cy, cz, h, w, l, r], axis=-1, name="anchors")
sess = tf.Session()
sess.run(tf.global_variables_initializer())
result = sess.run(anchros)
print(result.shape)
Related
After using
plt.savefig() in a function, I obtain
File "/usr/lib/python3.8/tkinter/__init__.py", line 4017, in __del__
self.tk.call('image', 'delete', self.name)
RuntimeError: main thread is not in main loop
Tcl_AsyncDelete: async handler deleted by the wrong thread
Aborted (core dumped)
I tried to add
plt.switch_backend('agg')
however, the code is not going to finish after this edit.
What to do, please?
I have downloaded https://github.com/amerand/PMOIRED
and I added
plt.savefig('bootstrap1.png')
before return in the function showBootstrap in the file oimodels.py.
def showBootstrap(b, indx=None, fig=0, figWidth=None, showRejected=False,
combParam={}, sigmaClipping=4.5, showChi2=False):
"""
you can look at combination of parameters:
combParam: {'sep':'np.sqrt($x**2 + $y**2)'} assuming 'x' and 'y' are parameters from the model
"""
global _AX, _AY
boot = copy.deepcopy(b)
# -- THIS IS NOT WORKING :(
#if showChi2:
# if not type(combParam) == dict:
# combParam = {}
# combParam.update({'_chi2': 'chi2'})
#boot['fitOnly'] = boot['fitOnly']
if len(combParam)>0:
s = '$'
for k in combParam:
if not k in boot['fitOnly']:
boot['fitOnly'].append(k)
for i,f in enumerate(boot['fitOnly']):
if 'chi2' in k:
boot['all fits'][i]['best'][k] = boot['all fits'][i]['chi2']
boot['all fits'][i]['uncer'][k] = 0.0
else:
tmp = combParam[k]+''
j = 0
while s in tmp and j<5:
for x in boot['best'].keys():
if s+x in tmp:
tmp = tmp.replace(s+x, '('+str(boot['best'][x])+')')
j+=1
boot['all fits'][i]['best'][k] = eval(tmp)
boot['all fits'][i]['uncer'][k] = 0.0
print('analyse')
boot = analyseBootstrap(boot, indx=inxd, inx=None, verbose=2, sigmaClipping=sigmaClipping)
print('done')
if figWidth is None:
figWidth = min(9.5, 1+2*len(boot['fitOnly']))
fontsize = max(min(4*figWidth/len(boot['fitOnly']), 14), 6)
plt.close(fig)
plt.figure(fig, figsize=(figWidth, figWidth))
_AX = {}
color1 = 'orange'
color2 = (0.2, 0.4, 1.0)
color3 = (0.8, 0.2, 0.4)
colorC2 = (0, 0.4, 0.2)
combi = False
# -- for each fitted parameters, show histogram
showP = sorted(boot['fitOnly'])
if showChi2:
showP.append('chi2')
offs = {}
amps = {}
for i1, k1 in enumerate(showP):
# -- create histogram plot
_AX[i1] = plt.subplot(len(showP),
len(showP),
1+i1*len(showP)+i1)
if k1=='chi2':
# -- assumes bins is already defined (chi2 cannot be first!)
# -- show histogram: line and area
h = plt.hist(boot['all chi2'], bins=bins,
color=colorC2, histtype='step', alpha=0.9)
h = plt.hist(boot['all chi2'], bins=bins,
color=colorC2, histtype='stepfilled', alpha=0.05)
plt.plot(boot['fit to all data']['chi2'],
0.4*max(h[0]), 's', markersize=fontsize/2,
color=colorC2, label='fit to all data')
plt.title(r'$\chi_{\rm red}^2$', fontsize=fontsize)
offs['chi2'] = 0
amps['chi2'] = 1
plt.xlim(min(min(h[1]),
boot['fit to all data']['chi2']-0.1*np.ptp(h[1])),
max(max(h[1]),
boot['fit to all data']['chi2']+0.1*np.ptp(h[1])))
#print('Xlim:', min(h[1]), max(h[1]), boot['fit to all data']['chi2'])
else:
# -- guess number of bins
if k1 in boot['uncer']:
bins = int(3*np.ptp(boot['all best'][k1])/boot['uncer'][k1])
else:
bins = 10
bins = min(bins, len(boot['mask'])//5)
bins = max(bins, 5)
nd = np.abs(np.mean(boot['all best'][k1])/np.ptp(boot['all best'][k1]))
if nd>0:
nd = int(np.log10(nd))
if nd>=4:
offs[k1] = np.round(np.mean(boot['all best'][k1]), nd)
amps[k1] = 10**(nd+1)
else:
offs[k1] = 0.0
amps[k1] = 1.0
#print(k1, nd, offs[k1])
# -- show histogram: line and area
h = plt.hist(amps[k1]*(boot['all best'][k1]-offs[k1]), bins=bins,
color='k', histtype='step', alpha=0.9)
h = plt.hist(amps[k1]*(boot['all best'][k1]-offs[k1]), bins=bins,
color='k', histtype='stepfilled', alpha=0.05)
# -- fitted and bootstrap values and uncertainties
if k1 in boot['fit to all data']['best']:
plt.errorbar(amps[k1]*(boot['fit to all data']['best'][k1]-offs[k1]),
0.4*max(h[0]), markersize=fontsize/2,
xerr=amps[k1]*boot['fit to all data']['uncer'][k1],
color=color1, fmt='s', capsize=fontsize/2,
label='fit to all data')
combi = False
else:
combi = True
plt.errorbar(amps[k1]*(boot['best'][k1]-offs[k1]), 0.5*max(h[0]),
xerr=amps[k1]*boot['uncer'][k1],
color=color3 if combi else color2, fmt='d',
capsize=fontsize/2, label='bootstrap', markersize=fontsize/2)
n = int(np.ceil(-np.log10(boot['uncer'][k1])+1))
fmt = '%s=\n'+'%.'+'%d'%n+'f'+'$\pm$'+'%.'+'%d'%n+'f'
plt.title(fmt%(k1, boot['best'][k1], boot['uncer'][k1]),
fontsize=fontsize)
plt.legend(fontsize=5)
# -- title
_AX[i1].yaxis.set_visible(False)
if i1!=(len(showP)-1):
_AX[i1].xaxis.set_visible(False)
else:
_AX[i1].tick_params(axis='x', labelsize=fontsize*0.8)
_AX[i1].set_xlabel(k1, fontsize=fontsize)
if offs[k1]<0:
_AX[i1].set_xlabel(k1+'\n+%f (%.0e)'%(np.abs(offs[k1]), 1/amps[k1]),
fontsize=fontsize)
elif offs[k1]>0:
_AX[i1].set_xlabel(k1+'\n-%f (%.0e)'%(np.abs(offs[k1]), 1/amps[k1]),
fontsize=fontsize)
_AX[i1].callbacks.connect('ylim_changed', _callbackAxes)
# -- end histogram
_AY = {}
# -- show density plots
for i1, k1 in enumerate(showP):
for i2 in range(i1+1, len(showP)):
k2 = showP[i2]
if i1==0:
_AY[i2] = plt.subplot(len(showP),
len(showP),
1+i2*len(showP)+i1,
sharex=_AX[i1])
ax = _AY[i2]
else:
ax = plt.subplot(len(showP),
len(showP),
1+i2*len(showP)+i1,
#sharex=_AX[i1],
sharey=_AY[i2])
#if k1=='chi2' or k2=='chi2':
# continue
#print(k1, k2)
c, m = 'k', '.'
if k1=='chi2':
X1 = boot['all chi2']
X1r = boot['all chi2 ignored']
c = colorC2
else:
X1 = boot['all best'][k1]
X1r = boot['all best ignored'][k1]
if k2=='chi2':
X2 = boot['all chi2']
X2r = boot['all chi2 ignored']
c = colorC2
else:
X2 = boot['all best'][k2]
X2r = boot['all best ignored'][k2]
plt.plot(amps[k1]*(X1-offs[k1]), amps[k2]*(X2-offs[k2]), m,
alpha=np.sqrt(2/len(boot['mask'])), color=c)
if showRejected:
plt.plot(amps[k1]*(X1r-offs[k1]), amps[k2]*(X2r-offs[k2]),
'xr', alpha=0.3)
# -- combined parameters function of the other one?
#print(combParam, k1, k2)
if (k1 in combParam and k2 in combParam[k1]) or \
(k2 in combParam and k1 in combParam[k2]):
_c = color3
else:
_c = color2
#x, y = dpfit.errorEllipse(boot, k1, k2)
if k1=='chi2':
_i1 = len(boot['fitOnly'])
_c = colorC2
else:
_i1 = boot['fitOnly'].index(k1)
if k2=='chi2':
_i2 = len(boot['fitOnly'])
_c = colorC2
else:
_i2 = boot['fitOnly'].index(k2)
t = np.linspace(0,2*np.pi,100)
sMa, sma, a = dpfit._ellParam(boot['cov'][_i1,_i1],
boot['cov'][_i2,_i2],
boot['cov'][_i1,_i2])
_X,_Y = sMa*np.cos(t), sma*np.sin(t)
_X,_Y = _X*np.cos(a)+_Y*np.sin(a),-_X*np.sin(a)+_Y*np.cos(a)
if (k1.endswith(',x') and k2.endswith(',y')) or \
(k1.endswith(',y') and k2.endswith(',x')):
print('ellipse (emin, emax, PA) for %s/%s: %.4f %.4f %.1f'%(
k1, k2, sMa, sma, a*180/np.pi))
if k1=='chi2':
x = np.mean(boot['all chi2'])+_X
else:
x = boot['best'][k1]+_X
if k2=='chi2':
y = np.mean(boot['all chi2'])+_Y
else:
y = boot['best'][k2]+_Y
plt.plot(amps[k1]*(x-offs[k1]),
amps[k2]*(y-offs[k2]), '-', color=_c,
label='c=%.2f'%boot['cord'][k1][k2])
plt.legend(fontsize=5)
if k1 in boot['fit to all data']['best'] and \
k2 in boot['fit to all data']['best']:
plt.plot(amps[k1]*(boot['fit to all data']['best'][k1]-offs[k1]),
amps[k2]*(boot['fit to all data']['best'][k2]-offs[k2]),
'x', color='0.5')
x, y = dpfit.errorEllipse(boot['fit to all data'], k1, k2)
plt.plot(amps[k1]*(x-offs[k1]), amps[k2]*(y-offs[k2]), '-',
color=color1)#, label='c=%.2f'%boot['cord'][k1][k2])
plt.plot(amps[k1]*(boot['best'][k1]-offs[k1]),
amps[k2]*(boot['best'][k2]-offs[k2]),
'+', color=_c)
if i2==(len(showP)-1):
plt.xlabel(k1, fontsize=fontsize)
if offs[k1]<0:
plt.xlabel(k1+'\n+%f (%.0e)'%(np.abs(offs[k1]), 1/amps[k1]),
fontsize=fontsize)
elif offs[k1]>0:
plt.xlabel(k1+'\n-%f (%.0e)'%(np.abs(offs[k1]), 1/amps[k1]),
fontsize=fontsize)
ax.tick_params(axis='x', labelsize=fontsize*0.8)
else:
ax.xaxis.set_visible(False)
if i1==0:
plt.ylabel(k2, fontsize=fontsize)
if offs[k2]<0:
plt.ylabel(k2+'\n+%f (%.0e)'%(np.abs(offs[k2]), 1/amps[k2]),
fontsize=fontsize)
elif offs[k2]>0:
plt.ylabel(k2+'\n-%f (%.0e)'%(np.abs(offs[k2]), 1/amps[k2]),
fontsize=fontsize)
_AY[i2].callbacks.connect('ylim_changed', _callbackAxes)
_AY[i2].tick_params(axis='y', labelsize=fontsize*0.8)
else:
ax.yaxis.set_visible(False)
plt.tight_layout()
plt.subplots_adjust(hspace = 0, # 0.65*fig.subplotpars.hspace,
wspace = 0, # 0.65*fig.subplotpars.wspace
)
plt.savefig('bootstrap1.png')
return
I am a little bit puzzled. I wanted to check the christoffelsymbol calculation and Riemann Tensor calculation by using the Schwarzschildmetric. But I do not get the expected results. Where is my error - or does sympy miss something? I miss Gamma_t_tr and Gamma_r_rr and Gamma_r_tt.
from sympy.diffgeom import Manifold, Patch, CoordSystem, TensorProduct, metric_to_Riemann_components, metric_to_Christoffel_1st, metric_to_Christoffel_2nd
import sympy as sym
from sympy import sin,cos,sinh,cosh, acos, atan2, exp, asin, acot
sym.init_printing(num_columns=200)
TP = TensorProduct
t,x,y,z = sym.symbols("t x y z")
tau, r, theta, phi = sym.symbols("tau r theta phi")
rs, M = sym.symbols("rs M")
m = Manifold("M",4)
p = Patch("P",m)
term_r = 1 - 2*M/r
relation_dict = {
('cartesian', 'schwarz'): [(t, x, y, z), (t, (x**2 + y**2 + z**2)**(0.5), atan2(y,x), acos(z/(x*x+y*y+z*z)**0.5) )],
('schwarz', 'cartesian'): [(tau, r, phi, theta), (tau, r*cos(phi)*sin(theta), r*sin(phi)*sin(theta), r*cos(theta))]
}
cartesian = CoordSystem('cartesian', p, (t, x, y, z), relation_dict)
schwarz = CoordSystem('schwarz', p, (tau, r, phi, theta), relation_dict)
tau, r, phi, theta = schwarz.coord_functions()
g00 = -term_r
g01 = 0
g02 = 0
g03 = 0
g10 = 0
g11 = 1/term_r
g12 = 0
g13 = 0
g20 = 0
g21 = 0
g22 = r**2*sin(theta)**2
g23 = 0
g30 = 0
g31 = 0
g32 = 0
g33 = r**2
g = sym.Matrix([[g00, g01, g02, g03],
[g10, g11, g12, g13],
[g20, g21, g22, g23],
[g30, g31, g32, g33]
])
diff_forms = schwarz.base_oneforms()
metric_diff_form = sum([TensorProduct(di, dj)*g[i, j] for i, di in enumerate(diff_forms)
for j, dj in enumerate(diff_forms)
])
print(metric_diff_form)
chris2 = metric_to_Christoffel_2nd(metric_diff_form)
print(chris2)
Rie = metric_to_Riemann_components(metric_diff_form)
print(Rie)
How to edit the for cycles under #ax5 and #ax6 to plot graphs in the same fashion? Now, the lower figure has no colour transit, as opposed to the upper one. The colour transit appears in the lower figure after increasing of dpi, however, some unwanted stuff also appears. Is there a scalling problem? Thank you
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
import math
fig, ax = plt.subplots()
plt.rcParams["figure.figsize"] = [8, 8]
# Function for plotting parallels to curves
def get_parallels(length=.1):
px, py = [], []
for idx in range(len(x)-1):
x0, y0, xa, ya = x[idx], y[idx], x[idx+1], y[idx+1]
dx, dy = xa-x0, ya-y0
norm = math.hypot(dx, dy) * 1/length
dx /= norm
dy /= norm
px.append(x0-dy)
py.append(y0+dx)
return px, py
def offset(x,y, o):
""" Offset coordinates given by array x,y by o """
X = np.c_[x,y].T
m = np.array([[0,-1],[1,0]])
R = np.zeros_like(X)
S = X[:,2:]-X[:,:-2]
R[:,1:-1] = np.dot(m, S)
R[:,0] = np.dot(m, X[:,1]-X[:,0])
R[:,-1] = np.dot(m, X[:,-1]-X[:,-2])
On = R/np.sqrt(R[0,:]**2+R[1,:]**2)*o
Out = On+X
return Out[0,:], Out[1,:]
dpi = 20
def offset_curve(ax, x,y, o):
""" Offset array x,y in data coordinates
by o in points """
trans = ax.transData.transform
inv = ax.transData.inverted().transform
X = np.c_[x,y]
Xt = trans(X)
xto, yto = offset(Xt[:,0],Xt[:,1],o*dpi/72. )
Xto = np.c_[xto, yto]
Xo = inv(Xto)
return Xo[:,0], Xo[:,1]
fig = plt.figure(constrained_layout=True)
gs = GridSpec(3, 6, figure=fig)
ax5 = fig.add_subplot(gs[1, 3:6])
ax6 = fig.add_subplot(gs[2, :3])
ax7 = fig.add_subplot(gs[2, 3:6])
cmap = plt.get_cmap('Greys_r')
# ax5
x = np.linspace(-1, 1, 100)
y = -x**2
ax5.set_ylim(-1.02, 0.3)
width_l = ax5.get_ylim()[1] - ax5.get_ylim()[0]
for t in np.linspace(0, 1, 40):
length = -0.1*width_l*t
ax5.plot(*get_parallels(length=length), color=cmap(t/2 + 0.25))
# ax6
x = np.linspace(-3, 3, 100)
y = -(1/4*x**4 - 1.6*x**2)
ax6.plot(x, y)
ax6.set_xlim(ax6.get_xlim()[0]-0.5, ax6.get_xlim()[1]+0.5)
ax6.scatter(1/2*(ax6.get_xlim()[0] + ax6.get_xlim()[1]), 1.2, marker = 'o', s=900, facecolors='none')
lines = []
width_l = ax6.get_ylim()[1] - ax6.get_ylim()[0]
for t in np.linspace(0, 1, 40):
l, = ax6.plot(x, y - t * 0.1 * width_l, color=cmap(t/2 + 0.25))
lines.append(l)
def plot_rainbow(event=None):
x0 = x
y0 = y
for i in range(len(lines)):
xx, yy = offset_curve(ax, x0, y0, -width_l)
lines[i].set_data(xx, yy)
lines[i].set_linewidth(1.1*width_l)
x0 = xx
y0 = yy
plot_rainbow()
fig.canvas.mpl_connect("resize_event", plot_rainbow)
fig.canvas.mpl_connect("button_release_event", plot_rainbow)
plt.savefig('fig.pdf')
How to edit this code to have the same width and colour map as in the following figure? The script is based on this question.
import numpy as np
import matplotlib.pyplot as plt
dpi = 100
def offset(x,y, o):
""" Offset coordinates given by array x,y by o """
X = np.c_[x,y].T
m = np.array([[0,-1],[1,0]])
R = np.zeros_like(X)
S = X[:,2:]-X[:,:-2]
R[:,1:-1] = np.dot(m, S)
R[:,0] = np.dot(m, X[:,1]-X[:,0])
R[:,-1] = np.dot(m, X[:,-1]-X[:,-2])
On = R/np.sqrt(R[0,:]**2+R[1,:]**2)*o
Out = On+X
return Out[0,:], Out[1,:]
def offset_curve(ax, x,y, o):
""" Offset array x,y in data coordinates
by o in points """
trans = ax.transData.transform
inv = ax.transData.inverted().transform
X = np.c_[x,y]
Xt = trans(X)
xto, yto = offset(Xt[:,0],Xt[:,1],o*dpi/72. )
Xto = np.c_[xto, yto]
Xo = inv(Xto)
return Xo[:,0], Xo[:,1]
x = np.linspace(-3, 3, 100)
y = -(1/4*x**4 - 1.6*x**2)
fig, ax=plt.subplots(figsize=(4,2.5), dpi=dpi)
cmap = plt.get_cmap('Greys_r')
lw = 2.
lines = []
width_l = ax.get_ylim()[1] - ax.get_ylim()[0]
for t in np.linspace(0, 1, 40):
l, = ax.plot(x, y - t * 0.1 * width_l, color=cmap(t/2 + 0.25))
lines.append(l)
def plot_rainbow(event=None):
# initialization of lists
xr, yr = 6*[None], 6*[None]
xr[0],yr[0] = offset_curve(ax, x,y, lw/2.)
xr[1],yr[1] = offset_curve(ax, x,y, -lw/2.)
xr[2],yr[2] = offset_curve(ax, xr[0],yr[0], lw)
xr[3],yr[3] = offset_curve(ax, xr[1],yr[1], -lw)
xr[4],yr[4] = offset_curve(ax, xr[2],yr[2], lw)
xr[5],yr[5] = offset_curve(ax, xr[3],yr[3], -lw)
for i in range(6):
lines[i].set_data(xr[i], yr[i])
plot_rainbow()
fig.canvas.mpl_connect("resize_event", plot_rainbow)
fig.canvas.mpl_connect("button_release_event", plot_rainbow)
plt.show()
The figure above was created by the following script:
import numpy as np
import matplotlib.pyplot as plt
import math
dpi = 100
# Function for plotting parallels to curves
def get_parallels(length=.1):
px, py = [], []
for idx in range(len(x)-1):
x0, y0, xa, ya = x[idx], y[idx], x[idx+1], y[idx+1]
dx, dy = xa-x0, ya-y0
norm = math.hypot(dx, dy) * 1/length
dx /= norm
dy /= norm
px.append(x0-dy)
py.append(y0+dx)
return px, py
fig, ax=plt.subplots(figsize=(4,2.5), dpi=dpi)
cmap = plt.get_cmap('Greys_r')
x = np.linspace(-1, 1, 100)
y = -x**2
ax.set_ylim(-1.02, 0.3)
ax.scatter(1/2*(ax.get_xlim()[0] + ax.get_xlim()[1]), 0.145, marker = 'o', s=900, facecolors='none')
width_l = ax.get_ylim()[1] - ax.get_ylim()[0]
for t in np.linspace(0, 1, 40):
length = -0.1*width_l*t
ax.plot(*get_parallels(length=length), color=cmap(t/2 + 0.25))
plt.tight_layout()
plt.show()
Several curves are plotted in camp and the length is set.
I would like to have the same "shadow" for the curve in the first scrip. How to do that, please?
I'm using the line of sight algorithm for a path planning problem, and I'm here checking its work, but as shown in the below picture that the line of sight checking is giving wrong results. The black tiles are paths that are checked by the line of sight, the function should also check tiles on (1,1) but it is not. How could I fix these errors?
The python code
import numpy as np
import matplotlib.pyplot as plt
grid = [[0,0,0,0,0,0,0,0],
[0,1,1,0,0,1,1,0],
[0,0,0,0,0,0,0,0],
[0,1,1,0,0,1,1,0],
[0,0,0,0,0,0,0,0]]
start, goal = (0,0), (3,2)
def lineOfSight(p, s):
x0 = p[0]
y0 = p[1]
x1 = s[0]
y1 = s[1]
dy = y1 - y0
dx = x1 - x0
f = 0
if dy < 0:
dy = -dy
sy = -1
else:
sy = 1
if dx < 0:
dx = -dx
sx = -1
else:
sx = 1
result = []
if dx >= dy:
while x0 != x1:
f = f + dy
i1 = x0 + int((sx-1)/2)
i2 = y0 + int((sy-1)/2)
if f >= dx:
result.append((i1,i2))
y0 = y0 + sy
f = f - dx
if f != 0:
result.append((i1,i2))
if dy == 0:
result.append((i1, y0))
result.append((i1, y0-1))
x0 = x0 + sx
else:
while y0 != y1:
f = f + dx
i1 = x0 + int((sx-1)/2)
i2 = y0 + int((sy-1)/2)
if f >= dy:
result.append((i1, i2))
x0 = x0 + sx
f = f - dy
if f != 0:
print((i1, i2))
if dx == 0:
result.append((x0, i2))
result.append((x0-1, i2))
y0 = y0 + sy
return result
check = lineOfSight(start,goal)
def getSquare(point):
x = [point[1], point[1]+1]
y0 = [-point[0], -point[0]]
y1 = [-(point[0]+1), -(point[0]+1)]
return (x,y0,y1)
checked = []
for xy in check:
checked.append(getSquare(xy))
plt.plot(start[1], -start[0], 'sb', label="Start Point")
plt.plot(goal[1], -goal[0], 'sg', label="Goal Point")
maxRow = len(grid)
maxCol = len(grid[0])
listRow = [-i for i in range(maxRow+1)]
listCol = [i for i in range(maxCol+1)]
xHorizontal, yHorizontal = np.meshgrid(listCol, [[0],[-maxRow]])
yVertical, xVertical = np.meshgrid(listRow, [[0],[maxCol]])
plt.plot(xHorizontal, yHorizontal, color='black')
plt.plot(xVertical, yVertical, color='black')
for square in checked:
x, y0, y1 = square
plt.fill_between(x,y0,y1, color='black')
plt.plot([start[1], goal[1]], [-start[0], -goal[0]], '-g')
plt.axis('equal')
plt.show()