def test_visualization():
ax = Axes3D(figure())
# Without axis.
ut.state_histogram(grove.tomography.operator_utils.GS, title="test")
# With axis.
ut.state_histogram(grove.tomography.operator_utils.GS, ax, "test")
assert ax.get_title() == "test"
ptX = grove.tomography.operator_utils.PAULI_BASIS.transfer_matrix(qt.to_super(
grove.tomography.operator_utils.QX)).toarray()
ax = Mock()
with patch("matplotlib.pyplot.colorbar"):
ut.plot_pauli_transfer_matrix(ptX, ax, grove.tomography.operator_utils.PAULI_BASIS.labels, "bla")
assert ax.imshow.called
assert ax.set_xlabel.called
assert ax.set_ylabel.called
python类Axes3D()的实例源码
def ShowCooordsTopology(coords,topo):
'''Plots the STL if coords and topology is given. '''
ax = a3d.Axes3D(plt.figure())
xm,ym,zm=coords.max(axis=0)
xmi,ymi,zmi =coords.min(axis=0)
for nodes in topo:
tri = a3d.art3d.Poly3DCollection([coords[nodes,:3]])
tri.set_color(colors.rgb2hex([0.9,0.6,0.]))
tri.set_edgecolor('k')
ax.add_collection3d(tri)
ax.set_xlim3d([xmi,xm])
ax.set_ylim3d([ymi,ym])
ax.set_zlim3d([zmi,zm])
plt.show()
def ShowSTLFile(v1,v2,v3):
'''Plots the STL files, give vertices v1,v2,v3'''
ax = a3d.Axes3D(plt.figure())
xm,ym,zm=v1.max(axis=0)
xmi,ymi,zmi =v2.min(axis=0)
for i in range(v1.shape[0]):
vtx=np.vstack((v1[i],v2[i],v3[i]))
tri = a3d.art3d.Poly3DCollection([vtx])
tri.set_color(colors.rgb2hex([0.9,0.6,0.]))
tri.set_edgecolor('k')
ax.add_collection3d(tri)
ax.set_xlim3d([xmi,xm])
ax.set_ylim3d([ymi,ym])
ax.set_zlim3d([zmi,zm])
plt.show()
def test_plot_3d(self):
"""Plot 3d test."""
# Test 3d plots.
self.assert_X_from_iterables(
self.assertIsInstance,
# TODO: error prone since colorbars can be added.
(fig.get_axes()[0] for fig in self.figures_3d),
itertools.repeat(Axes3D))
# Test that there is just one axes per figure.
for i, figure in enumerate(self.figures_3d):
axes = figure.get_axes()
if len(axes) != 1:
# TODO: colorbar may add a second axes.
pass
raise ValueError(
"Axes has the wrong number of elements: {0} but "
"should be 1.".format(len(axes)))
def display(self,angles):
"""
Plots wireframe models of the Dobot and obstacles.
"""
arm = DobotModel.get_mesh(angles)
#fig = plt.figure()
fig = plt.gcf()
ax = Axes3D(fig)
#plt.axis('equal')
for Ta in arm:
ax.plot(Ta[[0,1,2,0],0],Ta[[0,1,2,0],1],Ta[[0,1,2,0],2],'b')
for To in self.obstacles:
ax.plot(To[[0,1,2,0],0],To[[0,1,2,0],1],To[[0,1,2,0],2],'b')
r_max = DobotModel.l1 + DobotModel.l2 + DobotModel.d
plt.xlim([-np.ceil(r_max/np.sqrt(2)),r_max])
plt.ylim([-r_max,r_max])
ax.set_zlim(-150, 250)
ax.view_init(elev=30.0, azim=60.0)
plt.show()
return fig
policy_estimation.py 文件源码
项目:ReinforcementLearning
作者: persistforever
项目源码
文件源码
阅读 29
收藏 0
点赞 0
评论 0
def _plot_value_function(self, value_functions, n_iter):
value_matrix = numpy.zeros((10, 10), dtype='float')
for stateid in range(len(self.states)):
dealer_showing, player_state = self.states[stateid].split('#')
dealer_showing = 0 if dealer_showing == 'A' else int(dealer_showing)-1
player_state = int(player_state)
if player_state >= 12 and player_state < 22:
value_matrix[player_state-12, dealer_showing] = value_functions[stateid]
fig = plt.figure()
ax = Axes3D(fig)
Y, X = numpy.meshgrid(range(10), range(12,22))
ax.plot_surface(Y, X, value_matrix, rstride=1, cstride=1, cmap='coolwarm')
ax.set_title('value function in iteration %i' % n_iter)
ax.set_xlabel('dealer showing')
ax.set_ylabel('player sum')
ax.set_zlabel('value function')
plt.show()
monte_carlo_control.py 文件源码
项目:ReinforcementLearning
作者: persistforever
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def _plot_value_function(self, value_functions, n_iter):
value_matrix = numpy.zeros((10, 10), dtype='float')
for stateid in range(len(self.states)):
dealer_showing, player_state = self.states[stateid].split('#')
dealer_showing = 0 if dealer_showing == 'A' else int(dealer_showing)-1
player_state = int(player_state)
if player_state >= 12 and player_state < 22:
value_matrix[player_state-12, dealer_showing] = value_functions[stateid]
fig = plt.figure()
ax = Axes3D(fig)
Y, X = numpy.meshgrid(range(10), range(12,22))
ax.plot_surface(Y, X, value_matrix, rstride=1, cstride=1, cmap='coolwarm')
ax.set_title('value function in iteration %i' % n_iter)
ax.set_xlabel('dealer showing')
ax.set_ylabel('player sum')
ax.set_zlabel('value function')
plt.show()
def plot_ring(self, Nb_pts=201):
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
if self.X is None or self.Y is None:
raise Exception(" X and Y must be grid or a list for plotting")
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.array([self.X[0]])
Y = np.array([self.Y[0]])
intensity = np.array([self.intensity[0]])
ax.plot(X, Y, intensity, '^', label='ring number 0')
ring_number = 1
while (ring_number * Nb_pts < len(self.X)):
X = self.X[(ring_number - 1) * Nb_pts + 1:ring_number * Nb_pts + 1]
Y = self.Y[(ring_number - 1) * Nb_pts + 1:ring_number * Nb_pts + 1]
intensity = self.intensity[(ring_number - 1) * Nb_pts + 1:ring_number * Nb_pts + 1]
ax.plot(X, Y, intensity, label='ring number %d' % ring_number)
ring_number += 1
ax.set_xlabel("X")
ax.set_ylabel('Y')
ax.set_zlabel("itensity")
ax.legend()
plt.show()
def plot_3d(X, y_actual, y_predicted=None):
fig = plt.figure()
if y_predicted is None:
plt.title("Predicted vs actual function values")
else:
plt.title("Approximated function samples")
ax = Axes3D(fig)
ax.view_init(elev=30, azim=70)
scatter_actual = ax.scatter(X[:,0], X[:,1], y_actual, c='g', depthshade=False)
if not y_predicted is None:
scatter_predicted = ax.scatter(X[:,0], X[:,1], y_predicted, c='b', depthshade=False)
if y_predicted is None:
plt.legend((scatter_actual, scatter_predicted),
('Actual values', 'Predicted values'),
scatterpoints = 1)
plt.grid()
plt.show()
def plot_surface_3d(X, y_actual, NN):
fig = plt.figure()
plt.title("Predicted function with marked training samples")
ax = Axes3D(fig)
size = X.shape[0]
ax.view_init(elev=30, azim=70)
scatter_actual = ax.scatter(X[:,0], X[:,1], y_actual, c='g', depthshade=False)
x0s = sorted(X[:,0])
x1s = sorted(X[:,1])
x0s, x1s = np.meshgrid(x0s, x1s)
predicted_surface = np.zeros((size, size))
for i in range(size):
for j in range(size):
predicted_surface[i,j] = NN.output(np.array([x0s[i,j], x1s[i,j]]))
surf = ax.plot_surface(x0s, x1s, predicted_surface, rstride=2, cstride=2, linewidth=0, cmap=cm.coolwarm, alpha=0.5)
plt.grid()
plt.show()
def plot_3d(X, y_actual, y_predicted=None):
fig = plt.figure()
if y_predicted is None:
plt.title("Predicted vs actual function values")
else:
plt.title("Approximated function samples")
ax = Axes3D(fig)
ax.view_init(elev=30, azim=70)
scatter_actual = ax.scatter(X[:,0], X[:,1], y_actual, c='g', depthshade=False)
if not y_predicted is None:
scatter_predicted = ax.scatter(X[:,0], X[:,1], y_predicted, c='b', depthshade=False)
if y_predicted is None:
plt.legend((scatter_actual, scatter_predicted),
('Actual values', 'Predicted values'),
scatterpoints = 1)
plt.grid()
plt.show()
def plot_surface_3d(X, y_actual, NN):
fig = plt.figure()
plt.title("Predicted function with marked training samples")
ax = Axes3D(fig)
size = X.shape[0]
ax.view_init(elev=30, azim=70)
scatter_actual = ax.scatter(X[:,0], X[:,1], y_actual, c='g', depthshade=False)
x0s = sorted(X[:,0])
x1s = sorted(X[:,1])
x0s, x1s = np.meshgrid(x0s, x1s)
predicted_surface = np.zeros((size, size))
for i in range(size):
for j in range(size):
predicted_surface[i,j] = NN.output(np.array([x0s[i,j], x1s[i,j]]))
surf = ax.plot_surface(x0s, x1s, predicted_surface, rstride=2, cstride=2, linewidth=0, cmap=cm.coolwarm, alpha=0.5)
plt.grid()
plt.show()
def plot_LDA(converted_X,y):
'''
plot the graph after transfer
:param converted_X: train data after transfer
:param y: train_value
:return: None
'''
from mpl_toolkits.mplot3d import Axes3D
fig=plt.figure()
ax=Axes3D(fig)
colors='rgb'
markers='o*s'
for target,color,marker in zip([0,1,2],colors,markers):
pos=(y==target).ravel()
X=converted_X[pos,:]
ax.scatter(X[:,0], X[:,1], X[:,2],color=color,marker=marker,
label="Label {0}".format(target))
ax.legend(loc="best")
fig.suptitle("Iris After LDA")
plt.show()
def plotModel3D(vectorFile, numClusters):
# http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_iris.html
model = Doc2Vec.load("Models\\" + vectorFile)
docVecs = model.docvecs.doctag_syn0
reduced_data = PCA(n_components=10).fit_transform(docVecs)
kmeans = KMeans(init='k-means++', n_clusters=numClusters, n_init=10)
fig = plt.figure(1, figsize=(10, 10))
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
kmeans.fit(reduced_data)
labels = kmeans.labels_
ax.scatter(reduced_data[:, 5], reduced_data[:, 2], reduced_data[:, 3], c=labels.astype(np.float))
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
# Plot the ground truth
fig = plt.figure(1, figsize=(10, 10))
plt.clf()
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
plt.cla()
ax.scatter(reduced_data[:, 5], reduced_data[:, 2], reduced_data[:, 3], c=labels.astype(np.float))
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
plt.show()
def plot_figs(fig_num, elev, azim, X_train, clf):
fig = plt.figure(fig_num, figsize=(4, 3))
plt.clf()
ax = Axes3D(fig, elev=elev, azim=azim)
ax.scatter(X_train[:, 0], X_train[:, 1], y_train, c='k', marker='+')
ax.plot_surface(np.array([[-.1, -.1], [.15, .15]]),
np.array([[-.1, .15], [-.1, .15]]),
clf.predict(np.array([[-.1, -.1, .15, .15],
[-.1, .15, -.1, .15]]).T
).reshape((2, 2)),
alpha=.5)
ax.set_xlabel('X_1')
ax.set_ylabel('X_2')
ax.set_zlabel('Y')
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
#Generate the three different figures from different views
def preview_mesh(*args):
"""
This function plots numpy stl mesh objects entered into args. Note it will scale the preview plot based on the last mesh
object entered.
:param args: mesh objects to plot ex.- preview_mesh(mesh1, mesh2, mesh3)
:return:
"""
print ("...preparing preview...")
# Create a new plot
figure = pyplot.figure()
axes = mplot3d.Axes3D(figure)
for mesh_obj in args:
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(mesh_obj.vectors))
# Auto scale to the mesh size. Note it will choose the last mesh
scale = mesh_obj.points.flatten(-1)
axes.auto_scale_xyz(scale, scale, scale)
# Show the plot to the screen
pyplot.show()
def preview_mesh(*args):
"""
This function plots numpy stl mesh objects entered into args. Note it will scale the preview plot based on the last mesh
object entered.
:param args: mesh objects to plot ex.- preview_mesh(mesh1, mesh2, mesh3)
:return:
"""
print ("...preparing preview...")
# Create a new plot
figure = pyplot.figure()
axes = mplot3d.Axes3D(figure)
for mesh_obj in args:
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(mesh_obj.vectors))
# Auto scale to the mesh size. Note it will choose the last mesh
scale = mesh_obj.points.flatten(-1)
axes.auto_scale_xyz(scale, scale, scale)
# Show the plot to the screen
pyplot.show()
def visualize_pca3D(X,y):
"""
Visualize the first three principal components
Keyword arguments:
X -- The feature vectors
y -- The target vector
"""
pca = PCA(n_components = 3)
principal_components = pca.fit_transform(X)
fig = pylab.figure()
ax = Axes3D(fig)
# azm=30
# ele=30
# ax.view_init(azim=azm,elev=ele)
palette = sea.color_palette()
ax.scatter(principal_components[y==0, 0], principal_components[y==0, 1], principal_components[y==0, 2], label="Paid", alpha=0.5,
edgecolor='#262626', c=palette[1], linewidth=0.15)
ax.scatter(principal_components[y==1, 0], principal_components[y==1, 1], principal_components[y==1, 2],label="Default", alpha=0.5,
edgecolor='#262626''', c=palette[2], linewidth=0.15)
ax.legend()
plt.show()
def threeD():
fig = figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')
show()
def apply_limits(ax, pad=0.1):
"""
apply the stored phoebe_limits to an axes, applying an additional padding
:parameter ax:
:parameter float pad: ratio of the range to apply as a padding (default: 0.1)
"""
#try:
if True:
xlim = ax._phoebe_xlim
ylim = ax._phoebe_ylim
zlim = ax._phoebe_zlim
#except AttributeError:
# return ax
# initialize new lists for the padded limits. We don't want to directly
# edit xlim, ylim, zlim because we need padding based off the originals
# and we don't want to have to worry about deepcopying issues
xlim_pad = xlim[:]
ylim_pad = ylim[:]
zlim_pad = zlim[:]
xlim_pad[0] = xlim[0] - pad*(xlim[1]-xlim[0])
xlim_pad[1] = xlim[1] + pad*(xlim[1]-xlim[0])
ylim_pad[0] = ylim[0] - pad*(ylim[1]-ylim[0])
ylim_pad[1] = ylim[1] + pad*(ylim[1]-ylim[0])
zlim_pad[0] = zlim[0] - pad*(zlim[1]-zlim[0])
zlim_pad[1] = zlim[1] + pad*(zlim[1]-zlim[0])
if isinstance(ax, Axes3D):
ax.set_xlim3d(xlim_pad)
ax.set_ylim3d(ylim_pad)
ax.set_zlim3d(zlim_pad)
else:
ax.set_xlim(xlim_pad)
ax.set_ylim(ylim_pad)
return ax
plot_3d_color_spaces.py 文件源码
项目:udacity-detecting-vehicles
作者: wonjunee
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def plot3d(pixels, colors_rgb,
axis_labels=list("RGB"), axis_limits=[(0, 255), (0, 255), (0, 255)]):
"""Plot pixels in 3D."""
# Create figure and 3D axes
fig = plt.figure(figsize=(8, 8))
ax = Axes3D(fig)
# Set axis limits
ax.set_xlim(*axis_limits[0])
ax.set_ylim(*axis_limits[1])
ax.set_zlim(*axis_limits[2])
# Set axis labels and sizes
ax.tick_params(axis='both', which='major', labelsize=14, pad=8)
ax.set_xlabel(axis_labels[0], fontsize=16, labelpad=16)
ax.set_ylabel(axis_labels[1], fontsize=16, labelpad=16)
ax.set_zlabel(axis_labels[2], fontsize=16, labelpad=16)
# Plot pixel values with colors given in colors_rgb
ax.scatter(
pixels[:, :, 0].ravel(),
pixels[:, :, 1].ravel(),
pixels[:, :, 2].ravel(),
c=colors_rgb.reshape((-1, 3)), edgecolors='none')
return ax # return Axes3D object for further manipulation
# Read a color image
def plot3D(data, output_labels_3d, centroids):
'''
Creating a 3d Plot of the dataset
'''
fig = plt.figure(3)
ax = Axes3D(fig)
for i in range(len(output_labels_3d)):
if output_labels_3d[i] == 0:
ax.scatter(data[i, 0], data[i, 1], data[i, 2], s = 20, c = 'k')
elif output_labels_3d[i] == 1:
ax.scatter(data[i, 0], data[i, 1], data[i, 2], s = 20, c = 'r')
elif output_labels_3d[i] == 2:
ax.scatter(data[i, 0], data[i, 1], data[i, 2], s = 20, c = 'b')
elif output_labels_3d[i] == 3:
ax.scatter(data[i, 0], data[i, 1], data[i, 2], s = 20, c = 'c')
elif output_labels_3d[i] == 4:
ax.scatter(data[i, 0], data[i, 1], data[i, 2], s = 20, c = 'g')
elif output_labels_3d[i] == 5:
ax.scatter(data[i, 0], data[i, 1], data[i, 2], s = 20, c = 'y')
elif output_labels_3d[i] == 6:
ax.scatter(data[i, 0], data[i, 1], data[i, 2], s = 20, c = 'm')
elif output_labels_3d[i] == 7:
ax.scatter(data[i, 0], data[i, 1], data[i, 2], s = 25, c = 'y')
elif output_labels_3d[i] == 8:
ax.scatter(data[i, 0], data[i, 1], data[i, 2], s = 25, c = 'b')
elif output_labels_3d[i] == 9:
ax.scatter(data[i, 0], data[i, 1], data[i, 2], s = 25, c = 'k')
elif output_labels_3d[i] == 10:
ax.scatter(data[i, 0], data[i, 1], data[i, 2], s = 25, c = 'm')
elif output_labels_3d[i] == 11:
ax.scatter(data[i, 0], data[i, 1], data[i, 2], s = 25, c = 'g')
ax.scatter(centroids[:, 0], centroids[:, 1], centroids[:, 2], s = 150, c = 'r', marker = 'x', linewidth = 5)
plt.show()
return
def _plot_value_function(self, value_function, n_iter):
value_matrix = numpy.zeros((self.max_car+1, self.max_car+1), dtype='float')
for stateid in range(len(self.states)):
state = [int(t) for t in self.states[stateid].split('#')]
value_matrix[state[0], state[1]] = value_function[stateid]
fig = plt.figure()
ax = Axes3D(fig)
X, Y = numpy.meshgrid(range(self.max_car+1), range(self.max_car+1))
ax.plot_surface(Y, X, value_matrix, rstride=1, cstride=1, cmap='coolwarm')
ax.set_title('value function in iteration %i' % n_iter)
ax.set_xlabel('#cars at A')
ax.set_ylabel('#cars at B')
ax.set_zlabel('value function')
# plt.show()
fig.savefig('experiments/value%i' % n_iter)
def plotFromVF(vertices, faces):
input_vec = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))
for i, f in enumerate(faces):
for j in range(3):
input_vec.vectors[i][j] = vertices[f[j],:]
figure = plt.figure()
axes = mplot3d.Axes3D(figure)
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(input_vec.vectors))
scale = input_vec.points.flatten(-1)
axes.auto_scale_xyz(scale, scale, scale)
plt.show()
def plotFromVertices(vertices):
figure = plt.figure()
axes = mplot3d.Axes3D(figure)
axes.scatter(vertices.T[0,:],vertices.T[1,:],vertices.T[2,:])
plt.show()
def draw3D(X, Y, Z, angle):
fig = plt.figure(figsize=(15,7))
ax = Axes3D(fig)
ax.view_init(angle[0], angle[1])
ax.plot_surface(X,Y,Z,rstride=1, cstride=1, cmap='rainbow')
plt.imshow
def plot(self,title="",label=""):
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
if self.distance == None:
zlabel = "Flux (phot/s/0.1%bw/mrad2)"
xlabel = 'X [rad]'
ylabel = 'Y [rad]'
else:
zlabel = "Flux (phot/s/0.1%bw/mm2)"
xlabel = 'X [m]'
ylabel = 'Y [m]'
if self.X is None or self.Y is None:
raise Exception(" X and Y must be array for plotting")
if self.X.shape != self.Y.shape:
raise Exception(" X and Y must have the same shape")
fig = plt.figure()
if len(self.X.shape) ==2 :
ax = Axes3D(fig)
ax.plot_surface(self.X, self.Y, self.intensity, rstride=1, cstride=1,cmap='hot_r')
else :
ax = fig.gca(projection='3d')
ax.plot(self.X, self.Y, self.intensity, label=label)
ax.legend()
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_zlabel(zlabel)
plt.title(title)
plt.show()
def plot_2d(self, f, a, b, grid_size=200):
grid_x = np.linspace(a[0], b[0], num=grid_size).reshape((-1, 1))
grid_y = np.linspace(a[1], b[1], num=grid_size).reshape((-1, 1))
x, y = np.meshgrid(grid_x, grid_y)
merged = np.stack([x.flatten(), y.flatten()])
z = f(merged).reshape(x.shape)
swap = np.swapaxes(merged, 0, 1)
mu, sigma = self.utility.mean_and_std(swap)
mu = mu.reshape(x.shape)
sigma = sigma.reshape(x.shape)
points = np.asarray(self.points)
xs = points[:, 0]
ys = points[:, 1]
zs = f(np.swapaxes(points, 0, 1))
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(x, y, z, color='black', label='f', alpha=0.7,
linewidth=0, antialiased=False)
ax.plot_surface(x, y, mu, color='red', label='mu', alpha=0.5)
ax.plot_surface(x, y, mu + sigma, color='blue', label='mu+sigma', alpha=0.3)
ax.plot_surface(x, y, mu - sigma, color='blue', alpha=0.3)
ax.scatter(xs, ys, zs, color='red', marker='o', s=100)
# plt.legend()
plt.show()
Exercise13_2.py 文件源码
项目:computationalphysics_N2013301020050
作者: ShixingWang
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def plot(self):
x=np.linspace(-1,1,self.L)
y=np.linspace(-1,1,self.L)
X,Y=np.meshgrid(x,y)
fig=plt.figure()
ax=Axes3D(fig)
ax.plot_surface(X, Y, self.V, rstride=5, cstride=5, cmap='hot')
def run_draw():
#init = -sys.maxsize # for maximun case
targ = SimAnneal(target_text='max')
init = -sys.maxsize # for maximun case
#init = sys.maxsize # for minimun case
xyRange = [[-2, 2], [-2, 2]]
xRange = [[0, 10]]
t_start = time()
calculate = OptSolution(Markov_chain=1000, result=init, val_nd=[0,0])
output = calculate.soulution(SA_newV=targ.newVar, SA_preV=targ.preVar, SA_juge=targ.juge,
juge_text='max',ValueRange=xyRange, func=func2)
t_end = time()
#print(city_pos)
print('Running %.4f seconds' %(t_end-t_start))
# plot animation
fig = plt.figure()
ax = Axes3D(fig)
xv = np.linspace(xyRange[0][0], xyRange[0][1], 200)
yv = np.linspace(xyRange[1][0], xyRange[1][1], 200)
xv, yv = np.meshgrid(xv, yv)
zv = func2([xv, yv])
ax.plot_surface(xv, yv, zv, rstride=1, cstride=1, cmap='GnBu', alpha=1)
#dot = ax.scatter(0, 0, 0, 'ro')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
x, y, z = output[0][0], output[0][1], output[1]
ax.scatter(x, y, z, c='r', marker='o')
plt.savefig('SA_min0.png')
plt.show()