This commit is contained in:
guanjihuan 2021-08-30 17:41:42 +08:00
parent 6e281b9500
commit e25c08532d
19 changed files with 865 additions and 865 deletions

View File

@ -1,11 +1,11 @@
import imageio import imageio
import numpy as np import numpy as np
import os import os
os.chdir('D:/data') # 设置文件读取和保存位置 os.chdir('D:/data') # 设置文件读取和保存位置
images = [] images = []
for i in range(1000): for i in range(1000):
image = str(i)+'.jpg' image = str(i)+'.jpg'
im = imageio.imread(image) im = imageio.imread(image)
images.append(im) images.append(im)
imageio.mimsave("a.gif", images, 'GIF', duration=0.1) # durantion是延迟时间 imageio.mimsave("a.gif", images, 'GIF', duration=0.1) # durantion是延迟时间

View File

@ -1,30 +1,30 @@
import numpy as np import numpy as np
from math import * from math import *
# import os # import os
# os.chdir('D:/data') # 设置路径 # os.chdir('D:/data') # 设置路径
def main(): def main():
k1 = np.arange(-pi, pi, 0.05) k1 = np.arange(-pi, pi, 0.05)
k2 = np.arange(-pi, pi, 0.05) k2 = np.arange(-pi, pi, 0.05)
value = np.ones((k2.shape[0], k1.shape[0])) value = np.ones((k2.shape[0], k1.shape[0]))
plot_matrix(k1, k2, value) plot_matrix(k1, k2, value)
def plot_matrix(k1, k2, matrix): def plot_matrix(k1, k2, matrix):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib.ticker import LinearLocator, FormatStrFormatter
fig = plt.figure() fig = plt.figure()
ax = fig.gca(projection='3d') ax = fig.gca(projection='3d')
k1, k2 = np.meshgrid(k1, k2) k1, k2 = np.meshgrid(k1, k2)
ax.plot_surface(k1, k2, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.plot_surface(k1, k2, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False)
plt.xlabel('k1') plt.xlabel('k1')
plt.ylabel('k2') plt.ylabel('k2')
ax.set_zlabel('Z') ax.set_zlabel('Z')
plt.show() plt.show()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,31 +1,31 @@
import numpy as np import numpy as np
from math import * from math import *
# import os # import os
# os.chdir('D:/data') # 设置路径 # os.chdir('D:/data') # 设置路径
def main(): def main():
k1 = np.arange(-pi, pi, 0.05) k1 = np.arange(-pi, pi, 0.05)
k2 = np.arange(-pi, pi, 0.05) k2 = np.arange(-pi, pi, 0.05)
value = np.ones((k2.shape[0], k1.shape[0])) value = np.ones((k2.shape[0], k1.shape[0]))
write_matrix(k1, k2, value) write_matrix(k1, k2, value)
def write_matrix(k1, k2, matrix): def write_matrix(k1, k2, matrix):
with open('a.txt', 'w') as f: with open('a.txt', 'w') as f:
# np.set_printoptions(suppress=True) # 取消输出科学记数法 # np.set_printoptions(suppress=True) # 取消输出科学记数法
f.write('0 ') f.write('0 ')
for k10 in k1: for k10 in k1:
f.write(str(k10)+' ') f.write(str(k10)+' ')
f.write('\n') f.write('\n')
i0 = 0 i0 = 0
for k20 in k2: for k20 in k2:
f.write(str(k20)) f.write(str(k20))
for j0 in range(k1.shape[0]): for j0 in range(k1.shape[0]):
f.write(' '+str(matrix[i0, j0])+' ') f.write(' '+str(matrix[i0, j0])+' ')
f.write('\n') f.write('\n')
i0 += 1 i0 += 1
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,35 +1,35 @@
import numpy as np import numpy as np
from math import * from math import *
# import os # import os
# os.chdir('D:/data') # 设置路径 # os.chdir('D:/data') # 设置路径
def hamiltonian(k): def hamiltonian(k):
pass pass
def main(): def main():
k = np.arange(-pi, pi, 0.05) k = np.arange(-pi, pi, 0.05)
plot_bands_one_dimension(k, hamiltonian) plot_bands_one_dimension(k, hamiltonian)
def plot_bands_one_dimension(k, hamiltonian): def plot_bands_one_dimension(k, hamiltonian):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
dim = hamiltonian(0).shape[0] dim = hamiltonian(0).shape[0]
dim_k = k.shape[0] dim_k = k.shape[0]
eigenvalue_k = np.zeros((dim_k, dim)) eigenvalue_k = np.zeros((dim_k, dim))
i0 = 0 i0 = 0
for k0 in k: for k0 in k:
matrix0 = hamiltonian(k0) matrix0 = hamiltonian(k0)
eigenvalue, eigenvector = np.linalg.eig(matrix0) eigenvalue, eigenvector = np.linalg.eig(matrix0)
eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:])) eigenvalue_k[i0, :] = np.sort(np.real(eigenvalue[:]))
i0 += 1 i0 += 1
for dim0 in range(dim): for dim0 in range(dim):
plt.plot(k, eigenvalue_k[:, dim0], '-k') plt.plot(k, eigenvalue_k[:, dim0], '-k')
plt.xlabel('k') plt.xlabel('k')
plt.ylabel('E') plt.ylabel('E')
plt.show() plt.show()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,47 +1,47 @@
import numpy as np import numpy as np
from math import * from math import *
# import os # import os
# os.chdir('D:/data') # 设置路径 # os.chdir('D:/data') # 设置路径
def hamiltonian(k1, k2): def hamiltonian(k1, k2):
pass pass
def main(): def main():
k1 = np.arange(-pi, pi, 0.05) k1 = np.arange(-pi, pi, 0.05)
k2 = np.arange(-pi, pi, 0.05) k2 = np.arange(-pi, pi, 0.05)
plot_bands_two_dimension(k1, k2, hamiltonian) plot_bands_two_dimension(k1, k2, hamiltonian)
def plot_bands_two_dimension(k1, k2, hamiltonian): def plot_bands_two_dimension(k1, k2, hamiltonian):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib.ticker import LinearLocator, FormatStrFormatter
dim = hamiltonian(0, 0).shape[0] dim = hamiltonian(0, 0).shape[0]
dim1 = k1.shape[0] dim1 = k1.shape[0]
dim2 = k2.shape[0] dim2 = k2.shape[0]
eigenvalue_k = np.zeros((dim2, dim1, dim)) eigenvalue_k = np.zeros((dim2, dim1, dim))
i0 = 0 i0 = 0
for k20 in k2: for k20 in k2:
j0 = 0 j0 = 0
for k10 in k1: for k10 in k1:
matrix0 = hamiltonian(k10, k20) matrix0 = hamiltonian(k10, k20)
eigenvalue, eigenvector = np.linalg.eig(matrix0) eigenvalue, eigenvector = np.linalg.eig(matrix0)
eigenvalue_k[i0, j0, :] = np.sort(np.real(eigenvalue[:])) eigenvalue_k[i0, j0, :] = np.sort(np.real(eigenvalue[:]))
j0 += 1 j0 += 1
i0 += 1 i0 += 1
fig = plt.figure() fig = plt.figure()
ax = fig.gca(projection='3d') ax = fig.gca(projection='3d')
k1, k2 = np.meshgrid(k1, k2) k1, k2 = np.meshgrid(k1, k2)
for dim0 in range(dim): for dim0 in range(dim):
ax.plot_surface(k1, k2, eigenvalue_k[:, :, dim0], cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.plot_surface(k1, k2, eigenvalue_k[:, :, dim0], cmap=cm.coolwarm, linewidth=0, antialiased=False)
plt.xlabel('k1') plt.xlabel('k1')
plt.ylabel('k2') plt.ylabel('k2')
ax.set_zlabel('E') ax.set_zlabel('E')
plt.show() plt.show()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,31 +1,31 @@
import numpy as np import numpy as np
from math import * from math import *
# import os # import os
# os.chdir('D:/data') # 设置路径 # os.chdir('D:/data') # 设置路径
def hamiltonian(k): def hamiltonian(k):
pass pass
def main(): def main():
k = np.arange(-pi, pi, 0.05) k = np.arange(-pi, pi, 0.05)
write_bands_one_dimension(k, hamiltonian) write_bands_one_dimension(k, hamiltonian)
def write_bands_one_dimension(k, hamiltonian): def write_bands_one_dimension(k, hamiltonian):
dim = hamiltonian(0).shape[0] dim = hamiltonian(0).shape[0]
f = open('a.txt','w') f = open('a.txt','w')
for k0 in k: for k0 in k:
f.write(str(k0)+' ') f.write(str(k0)+' ')
matrix0 = hamiltonian(k0) matrix0 = hamiltonian(k0)
eigenvalue, eigenvector = np.linalg.eig(matrix0) eigenvalue, eigenvector = np.linalg.eig(matrix0)
eigenvalue = np.sort(np.real(eigenvalue)) eigenvalue = np.sort(np.real(eigenvalue))
for dim0 in range(dim): for dim0 in range(dim):
f.write(str(eigenvalue[dim0])+' ') f.write(str(eigenvalue[dim0])+' ')
f.write('\n') f.write('\n')
f.close() f.close()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,42 +1,42 @@
import numpy as np import numpy as np
from math import * from math import *
# import os # import os
# os.chdir('D:/data') # 设置路径 # os.chdir('D:/data') # 设置路径
def hamiltonian(k1, k2): def hamiltonian(k1, k2):
pass pass
def main(): def main():
k1 = np.arange(-pi, pi, 0.05) k1 = np.arange(-pi, pi, 0.05)
k2 = np.arange(-pi, pi, 0.05) k2 = np.arange(-pi, pi, 0.05)
write_bands_two_dimension(k1, k2, hamiltonian) write_bands_two_dimension(k1, k2, hamiltonian)
def write_bands_two_dimension(k1, k2, hamiltonian): def write_bands_two_dimension(k1, k2, hamiltonian):
f1 = open('a1.txt', 'w') f1 = open('a1.txt', 'w')
f2 = open('a2.txt', 'w') f2 = open('a2.txt', 'w')
f1.write('0 ') f1.write('0 ')
f2.write('0 ') f2.write('0 ')
for k10 in k1: for k10 in k1:
f1.write(str(k10)+' ') f1.write(str(k10)+' ')
f2.write(str(k10)+' ') f2.write(str(k10)+' ')
f1.write('\n') f1.write('\n')
f2.write('\n') f2.write('\n')
for k20 in k2: for k20 in k2:
f1.write(str(k20)+' ') f1.write(str(k20)+' ')
f2.write(str(k20)+' ') f2.write(str(k20)+' ')
for k10 in k1: for k10 in k1:
matrix0 = hamiltonian(k10, k20) matrix0 = hamiltonian(k10, k20)
eigenvalue, eigenvector = np.linalg.eig(matrix0) eigenvalue, eigenvector = np.linalg.eig(matrix0)
eigenvalue = np.sort(np.real(eigenvalue)) eigenvalue = np.sort(np.real(eigenvalue))
f1.write(str(eigenvalue[0])+' ') f1.write(str(eigenvalue[0])+' ')
f2.write(str(eigenvalue[1])+' ') f2.write(str(eigenvalue[1])+' ')
f1.write('\n') f1.write('\n')
f2.write('\n') f2.write('\n')
f1.close() f1.close()
f2.close() f2.close()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,7 +1,7 @@
import numpy as np # 导入numpy库用来存储和处理大型矩阵比python自带的嵌套列表更高效。numpy库还包含了许多数学函数库。python+numpy等同于matlab。 import numpy as np # 导入numpy库用来存储和处理大型矩阵比python自带的嵌套列表更高效。numpy库还包含了许多数学函数库。python+numpy等同于matlab。
def main(): # 主函数的内容放在这里。 def main(): # 主函数的内容放在这里。
pass pass
if __name__ == '__main__': # 如果是当前文件直接运行执行main()函数中的内容如果是import当前文件则不执行。同时将main()语句放在最后运行,可以避免书写的函数出现未定义的情况。 if __name__ == '__main__': # 如果是当前文件直接运行执行main()函数中的内容如果是import当前文件则不执行。同时将main()语句放在最后运行,可以避免书写的函数出现未定义的情况。
main() main()

View File

@ -1,4 +1,4 @@
1 1.2 2.4 1 1.2 2.4
2 5.5 3.2 2 5.5 3.2
3 6.7 7.1 3 6.7 7.1
4 3.6 4.9 4 3.6 4.9

View File

@ -1,4 +1,4 @@
0 1 2 3 4 0 1 2 3 4
1 1.3 2.7 6.7 8.3 1 1.3 2.7 6.7 8.3
2 4.3 2.9 5.4 7.4 2 4.3 2.9 5.4 7.4
3 9.1 8.2 2.6 3.1 3 9.1 8.2 2.6 3.1

View File

@ -1,47 +1,47 @@
import numpy as np import numpy as np
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
# import os # import os
# os.chdir('D:/data') # 设置路径 # os.chdir('D:/data') # 设置路径
def main(): def main():
x, y = read_one_dimension('1D_data.txt') x, y = read_one_dimension('1D_data.txt')
for dim0 in range(y.shape[1]): for dim0 in range(y.shape[1]):
plt.plot(x, y[:, dim0], '-k') plt.plot(x, y[:, dim0], '-k')
plt.show() plt.show()
def read_one_dimension(file_name): def read_one_dimension(file_name):
f = open(file_name, 'r') f = open(file_name, 'r')
text = f.read() text = f.read()
f.close() f.close()
row_list = np.array(text.split('\n')) # 根据“回车”分割成每一行 row_list = np.array(text.split('\n')) # 根据“回车”分割成每一行
# print('文本格式:') # print('文本格式:')
# print(text) # print(text)
# print('row_list:') # print('row_list:')
# print(row_list) # print(row_list)
# print('column:') # print('column:')
dim_column = np.array(row_list[0].split()).shape[0] # 列数 dim_column = np.array(row_list[0].split()).shape[0] # 列数
x = np.array([]) x = np.array([])
y = np.array([]) y = np.array([])
for row in row_list: for row in row_list:
column = np.array(row.split()) # 每一行根据“空格”继续分割 column = np.array(row.split()) # 每一行根据“空格”继续分割
# print(column) # print(column)
if column.shape[0] != 0: # 解决最后一行空白的问题 if column.shape[0] != 0: # 解决最后一行空白的问题
x = np.append(x, [float(column[0])], axis=0) # 第一列为x数据 x = np.append(x, [float(column[0])], axis=0) # 第一列为x数据
y_row = np.zeros(dim_column-1) y_row = np.zeros(dim_column-1)
for dim0 in range(dim_column-1): for dim0 in range(dim_column-1):
y_row[dim0] = float(column[dim0+1]) y_row[dim0] = float(column[dim0+1])
if np.array(y).shape[0] == 0: if np.array(y).shape[0] == 0:
y = [y_row] y = [y_row]
else: else:
y = np.append(y, [y_row], axis=0) y = np.append(y, [y_row], axis=0)
# print('x:') # print('x:')
# print(x) # print(x)
# print('y:') # print('y:')
# print(y) # print(y)
return x, y return x, y
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,69 +1,69 @@
import numpy as np import numpy as np
# import os # import os
# os.chdir('D:/data') # 设置路径 # os.chdir('D:/data') # 设置路径
def main(): def main():
x1, x2, matrix = read_two_dimension('2D_data.txt') x1, x2, matrix = read_two_dimension('2D_data.txt')
plot_matrix(x1, x2, matrix) plot_matrix(x1, x2, matrix)
def read_two_dimension(file_name): def read_two_dimension(file_name):
f = open(file_name, 'r') f = open(file_name, 'r')
text = f.read() text = f.read()
f.close() f.close()
row_list = np.array(text.split('\n')) # 根据“回车”分割成每一行 row_list = np.array(text.split('\n')) # 根据“回车”分割成每一行
# print('文本格式:') # print('文本格式:')
# print(text) # print(text)
# print('row_list:') # print('row_list:')
# print(row_list) # print(row_list)
# print('column:') # print('column:')
dim_column = np.array(row_list[0].split()).shape[0] # 列数 dim_column = np.array(row_list[0].split()).shape[0] # 列数
x1 = np.array([]) x1 = np.array([])
x2 = np.array([]) x2 = np.array([])
matrix = np.array([]) matrix = np.array([])
for i0 in range(row_list.shape[0]): for i0 in range(row_list.shape[0]):
column = np.array(row_list[i0].split()) # 每一行根据“空格”继续分割 column = np.array(row_list[i0].split()) # 每一行根据“空格”继续分割
# print(column) # print(column)
if i0 == 0: if i0 == 0:
x1_str = column[1::] # x1坐标去除第一个在角落的值 x1_str = column[1::] # x1坐标去除第一个在角落的值
x1 = np.zeros(x1_str.shape[0]) x1 = np.zeros(x1_str.shape[0])
for i00 in range(x1_str.shape[0]): for i00 in range(x1_str.shape[0]):
x1[i00] = float(x1_str[i00]) # 字符串转浮点 x1[i00] = float(x1_str[i00]) # 字符串转浮点
elif column.shape[0] != 0: # 解决最后一行空白的问题 elif column.shape[0] != 0: # 解决最后一行空白的问题
x2 = np.append(x2, [float(column[0])], axis=0) # 第一列为x数据 x2 = np.append(x2, [float(column[0])], axis=0) # 第一列为x数据
matrix_row = np.zeros(dim_column-1) matrix_row = np.zeros(dim_column-1)
for dim0 in range(dim_column-1): for dim0 in range(dim_column-1):
matrix_row[dim0] = float(column[dim0+1]) matrix_row[dim0] = float(column[dim0+1])
if np.array(matrix).shape[0] == 0: if np.array(matrix).shape[0] == 0:
matrix = [matrix_row] matrix = [matrix_row]
else: else:
matrix = np.append(matrix, [matrix_row], axis=0) matrix = np.append(matrix, [matrix_row], axis=0)
# print('x1:') # print('x1:')
# print(x1) # print(x1)
# print('x2:') # print('x2:')
# print(x2) # print(x2)
# print('matrix:') # print('matrix:')
# print(matrix) # print(matrix)
return x1, x2, matrix return x1, x2, matrix
def plot_matrix(x1, x2, matrix): def plot_matrix(x1, x2, matrix):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib.ticker import LinearLocator, FormatStrFormatter
fig = plt.figure() fig = plt.figure()
ax = fig.gca(projection='3d') ax = fig.gca(projection='3d')
x1, x2 = np.meshgrid(x1, x2) x1, x2 = np.meshgrid(x1, x2)
ax.plot_surface(x1, x2, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.plot_surface(x1, x2, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False)
plt.xlabel('x1') plt.xlabel('x1')
plt.ylabel('x2') plt.ylabel('x2')
ax.set_zlabel('z') ax.set_zlabel('z')
plt.show() plt.show()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,18 +1,18 @@
import numpy as np import numpy as np
from math import * from math import *
# import os # import os
# os.chdir('D:/data') # 设置路径 # os.chdir('D:/data') # 设置路径
f = open('a.txt', 'w') f = open('a.txt', 'w')
f.write('0 ') f.write('0 ')
for k1 in np.arange(-pi, pi, 0.05): for k1 in np.arange(-pi, pi, 0.05):
f.write(str(k1)+' ') f.write(str(k1)+' ')
f.write('\n') f.write('\n')
for k2 in np.arange(-pi, pi, 0.05): for k2 in np.arange(-pi, pi, 0.05):
f.write(str(k2)+' ') f.write(str(k2)+' ')
for k1 in np.arange(-pi, pi, 0.05): for k1 in np.arange(-pi, pi, 0.05):
data = 1000 # 运算数据 data = 1000 # 运算数据
f.write(str(data)+' ') f.write(str(data)+' ')
f.write('\n') f.write('\n')
f.close() f.close()

View File

@ -1,32 +1,32 @@
import numpy as np import numpy as np
# import os # import os
# os.chdir('D:/data') # 设置文件保存的位置 # os.chdir('D:/data') # 设置文件保存的位置
def main(): def main():
x = [4, 3, 5, 7] x = [4, 3, 5, 7]
y = [6, 1, 3, 2] y = [6, 1, 3, 2]
value = [3, 1, 10, 2] value = [3, 1, 10, 2]
Plot_2D_Scatter(x, y, value, title='Plot 2D Scatter') Plot_2D_Scatter(x, y, value, title='Plot 2D Scatter')
def Plot_2D_Scatter(x, y, value, xlabel='x', ylabel='y', title='title', filename='a'): def Plot_2D_Scatter(x, y, value, xlabel='x', ylabel='y', title='title', filename='a'):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
fig = plt.figure() fig = plt.figure()
ax = fig.add_subplot(111) ax = fig.add_subplot(111)
plt.subplots_adjust(bottom=0.2, right=0.8, left=0.2) plt.subplots_adjust(bottom=0.2, right=0.8, left=0.2)
for i in range(np.array(x).shape[0]): for i in range(np.array(x).shape[0]):
ax.scatter(x[i], y[i], marker='o', s=100*value[i], c=[(1,0,0)]) ax.scatter(x[i], y[i], marker='o', s=100*value[i], c=[(1,0,0)])
ax.set_title(title, fontsize=20, fontfamily='Times New Roman') ax.set_title(title, fontsize=20, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman')
ax.tick_params(labelsize=15) # 设置刻度值字体大小 ax.tick_params(labelsize=15) # 设置刻度值字体大小
labels = ax.get_xticklabels() + ax.get_yticklabels() labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体
# plt.savefig(filename+'.jpg', dpi=300) # plt.savefig(filename+'.jpg', dpi=300)
plt.show() plt.show()
plt.close('all') plt.close('all')
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,38 +1,38 @@
import numpy as np import numpy as np
# import os # import os
# os.chdir('D:/data') # 设置文件保存的位置 # os.chdir('D:/data') # 设置文件保存的位置
def main(): def main():
x = [1, 3, 5, 7] x = [1, 3, 5, 7]
y = [2, 4, 6, 8] y = [2, 4, 6, 8]
z = [2, 8, 6, 1] z = [2, 8, 6, 1]
value = [3, 1, 10, 2] value = [3, 1, 10, 2]
Plot_3D_Scatter(x, y, z, value, title='Plot 3D Scatter') Plot_3D_Scatter(x, y, z, value, title='Plot 3D Scatter')
def Plot_3D_Scatter(x, y, z, value, xlabel='x', ylabel='y', zlabel='z', title='title', filename='a'): def Plot_3D_Scatter(x, y, z, value, xlabel='x', ylabel='y', zlabel='z', title='title', filename='a'):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from matplotlib.ticker import LinearLocator from matplotlib.ticker import LinearLocator
fig = plt.figure() fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') ax = fig.add_subplot(111, projection='3d')
plt.subplots_adjust(bottom=0.1, right=0.8) plt.subplots_adjust(bottom=0.1, right=0.8)
for i in range(np.array(x).shape[0]): for i in range(np.array(x).shape[0]):
ax.scatter(x[i], y[i], z[i], marker='o', s=int(100*value[i]), c=[(1,0,0)]) ax.scatter(x[i], y[i], z[i], marker='o', s=int(100*value[i]), c=[(1,0,0)])
ax.set_title(title, fontsize=20, fontfamily='Times New Roman') ax.set_title(title, fontsize=20, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman')
ax.set_zlabel(zlabel, fontsize=20, fontfamily='Times New Roman') ax.set_zlabel(zlabel, fontsize=20, fontfamily='Times New Roman')
# ax.set_zlim(0, 20) # ax.set_zlim(0, 20)
# ax.zaxis.set_major_locator(LinearLocator(6)) # 设置z轴主刻度的个数 # ax.zaxis.set_major_locator(LinearLocator(6)) # 设置z轴主刻度的个数
# ax.zaxis.set_major_formatter('{x:.0f}') # 设置z轴主刻度的格式 # ax.zaxis.set_major_formatter('{x:.0f}') # 设置z轴主刻度的格式
ax.tick_params(labelsize=15) # 设置刻度值字体大小 ax.tick_params(labelsize=15) # 设置刻度值字体大小
labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels() labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()
[label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体
# plt.savefig(filename+'.jpg', dpi=300) # plt.savefig(filename+'.jpg', dpi=300)
plt.show() plt.show()
plt.close('all') plt.close('all')
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,44 +1,44 @@
import numpy as np import numpy as np
# import os # import os
# os.chdir('D:/data') # 设置文件保存的位置 # os.chdir('D:/data') # 设置文件保存的位置
def main(): def main():
x = np.arange(-5, 5, 0.25) x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25) y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(x, y) X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2) R = np.sqrt(X**2 + Y**2)
Z = np.sin(R) Z = np.sin(R)
Plot_3D_Surface(x,y,Z) Plot_3D_Surface(x,y,Z)
def Plot_3D_Surface(x,y,matrix,filename='a.jpg', titlename='Plot 3D Surface'): def Plot_3D_Surface(x,y,matrix,filename='a.jpg', titlename='Plot 3D Surface'):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from matplotlib import cm from matplotlib import cm
from matplotlib.ticker import LinearLocator from matplotlib.ticker import LinearLocator
fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
plt.subplots_adjust(bottom=0.1, right=0.65) # 调整位置 plt.subplots_adjust(bottom=0.1, right=0.65) # 调整位置
x, y = np.meshgrid(x, y) x, y = np.meshgrid(x, y)
surf = ax.plot_surface(x, y, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Plot the surface. surf = ax.plot_surface(x, y, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Plot the surface.
ax.set_title(titlename, fontsize=20, fontfamily='Times New Roman') ax.set_title(titlename, fontsize=20, fontfamily='Times New Roman')
ax.set_xlabel('x', fontsize=30, fontfamily='Times New Roman') # 坐标标签 ax.set_xlabel('x', fontsize=30, fontfamily='Times New Roman') # 坐标标签
ax.set_ylabel('y', fontsize=30, fontfamily='Times New Roman') # 坐标标签 ax.set_ylabel('y', fontsize=30, fontfamily='Times New Roman') # 坐标标签
ax.set_zlabel('z', fontsize=30, fontfamily='Times New Roman') # 坐标标签 ax.set_zlabel('z', fontsize=30, fontfamily='Times New Roman') # 坐标标签
# ax.set_zlim(-1, 1) # 设置z轴的范围 # ax.set_zlim(-1, 1) # 设置z轴的范围
ax.zaxis.set_major_locator(LinearLocator(5)) # 设置z轴主刻度的个数 ax.zaxis.set_major_locator(LinearLocator(5)) # 设置z轴主刻度的个数
ax.zaxis.set_major_formatter('{x:.2f}') # 设置z轴主刻度的格式 ax.zaxis.set_major_formatter('{x:.2f}') # 设置z轴主刻度的格式
ax.tick_params(labelsize=15) # 设置刻度值字体大小 ax.tick_params(labelsize=15) # 设置刻度值字体大小
labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels() labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()
[label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体
cax = plt.axes([0.75, 0.15, 0.05, 0.75]) # color bar的位置 [左,下,宽度, 高度] cax = plt.axes([0.75, 0.15, 0.05, 0.75]) # color bar的位置 [左,下,宽度, 高度]
cbar = fig.colorbar(surf, cax=cax) # color bar cbar = fig.colorbar(surf, cax=cax) # color bar
cbar.ax.tick_params(labelsize=15) # 设置color bar刻度的字体大小 cbar.ax.tick_params(labelsize=15) # 设置color bar刻度的字体大小
for l in cbar.ax.yaxis.get_ticklabels(): # 设置color bar刻度的字体 for l in cbar.ax.yaxis.get_ticklabels(): # 设置color bar刻度的字体
l.set_family('Times New Roman') l.set_family('Times New Roman')
# plt.savefig(filename, dpi=800) # 保存图片文件 # plt.savefig(filename, dpi=800) # 保存图片文件
plt.show() plt.show()
plt.close('all') # 关闭所有plt防止循环画图时占用内存 plt.close('all') # 关闭所有plt防止循环画图时占用内存
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,42 +1,42 @@
import numpy as np import numpy as np
# import os # import os
# os.chdir('D:/data') # 设置文件保存的位置 # os.chdir('D:/data') # 设置文件保存的位置
def main(): def main():
x = np.arange(-5, 5, 0.25) x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25) y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(x, y) X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2) R = np.sqrt(X**2 + Y**2)
Z = np.sin(R) Z = np.sin(R)
Plot_Contour(x,y,Z) Plot_Contour(x,y,Z)
def Plot_Contour(x,y,matrix,filename='a.jpg', titlename='Plot Contour'): def Plot_Contour(x,y,matrix,filename='a.jpg', titlename='Plot Contour'):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from matplotlib import cm from matplotlib import cm
from matplotlib.ticker import LinearLocator from matplotlib.ticker import LinearLocator
fig, ax = plt.subplots() fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.15, right=0.7) # 调整位置 plt.subplots_adjust(bottom=0.15, right=0.7) # 调整位置
x, y = np.meshgrid(x, y) x, y = np.meshgrid(x, y)
contour = ax.contourf(x,y,matrix,cmap='jet') contour = ax.contourf(x,y,matrix,cmap='jet')
ax.set_title(titlename, fontsize=20, fontfamily='Times New Roman') ax.set_title(titlename, fontsize=20, fontfamily='Times New Roman')
ax.set_xlabel('x', fontsize=30, fontfamily='Times New Roman') # 坐标标签 ax.set_xlabel('x', fontsize=30, fontfamily='Times New Roman') # 坐标标签
ax.set_ylabel('y', fontsize=30, fontfamily='Times New Roman') # 坐标标签 ax.set_ylabel('y', fontsize=30, fontfamily='Times New Roman') # 坐标标签
# plt.xlabel('x') # plt.xlabel('x')
# plt.ylabel('y') # plt.ylabel('y')
ax.tick_params(labelsize=15) # 设置刻度值字体大小 ax.tick_params(labelsize=15) # 设置刻度值字体大小
labels = ax.get_xticklabels() + ax.get_yticklabels() labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体
cax = plt.axes([0.75, 0.15, 0.08, 0.73]) # color bar的位置 [左,下,宽度, 高度] cax = plt.axes([0.75, 0.15, 0.08, 0.73]) # color bar的位置 [左,下,宽度, 高度]
cbar = fig.colorbar(contour, cax=cax) # color bar cbar = fig.colorbar(contour, cax=cax) # color bar
cbar.ax.tick_params(labelsize=15) # 设置color bar刻度的字体大小 cbar.ax.tick_params(labelsize=15) # 设置color bar刻度的字体大小
for l in cbar.ax.yaxis.get_ticklabels(): # 设置color bar刻度的字体 for l in cbar.ax.yaxis.get_ticklabels(): # 设置color bar刻度的字体
l.set_family('Times New Roman') l.set_family('Times New Roman')
# plt.savefig(filename, dpi=800) # 保存图片文件 # plt.savefig(filename, dpi=800) # 保存图片文件
plt.show() plt.show()
plt.close('all') # 关闭所有plt防止循环画图时占用内存 plt.close('all') # 关闭所有plt防止循环画图时占用内存
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,30 +1,30 @@
import numpy as np import numpy as np
# import os # import os
# os.chdir('D:/data') # 设置文件保存的位置 # os.chdir('D:/data') # 设置文件保存的位置
def main(): def main():
x = np.arange(0.0, 2.0, 0.01) x = np.arange(0.0, 2.0, 0.01)
y = 1 + np.sin(2 * np.pi * x) y = 1 + np.sin(2 * np.pi * x)
Plot_Line(x,y) Plot_Line(x,y)
def Plot_Line(x,y,filename='a.jpg', titlename='Plot Line'): def Plot_Line(x,y,filename='a.jpg', titlename='Plot Line'):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
fig, ax = plt.subplots() fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.20, left=0.16) plt.subplots_adjust(bottom=0.20, left=0.16)
ax.plot(x, y, '-o') ax.plot(x, y, '-o')
ax.grid() ax.grid()
ax.set_title(titlename, fontsize=20, fontfamily='Times New Roman') ax.set_title(titlename, fontsize=20, fontfamily='Times New Roman')
ax.set_xlabel('x', fontsize=30, fontfamily='Times New Roman') # 坐标标签 ax.set_xlabel('x', fontsize=30, fontfamily='Times New Roman') # 坐标标签
ax.set_ylabel('y', fontsize=30, fontfamily='Times New Roman') # 坐标标签 ax.set_ylabel('y', fontsize=30, fontfamily='Times New Roman') # 坐标标签
ax.tick_params(labelsize=20) # 设置刻度值字体大小 ax.tick_params(labelsize=20) # 设置刻度值字体大小
labels = ax.get_xticklabels() + ax.get_yticklabels() labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体 [label.set_fontname('Times New Roman') for label in labels] # 设置刻度值字体
# plt.savefig(filename, dpi=800) # 保存图片文件 # plt.savefig(filename, dpi=800) # 保存图片文件
plt.show() plt.show()
plt.close('all') # 关闭所有plt防止循环画图时占用内存 plt.close('all') # 关闭所有plt防止循环画图时占用内存
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1,322 +1,322 @@
""" """
This code is supported by the website: https://www.guanjihuan.com This code is supported by the website: https://www.guanjihuan.com
The newest version of this code is on the web page: https://www.guanjihuan.com/archives/8734 The newest version of this code is on the web page: https://www.guanjihuan.com/archives/8734
函数调用目录 函数调用目录
1. x, y = read_one_dimensional_data(filename='a') 1. x, y = read_one_dimensional_data(filename='a')
2. x, y, matrix = read_two_dimensional_data(filename='a') 2. x, y, matrix = read_two_dimensional_data(filename='a')
3. write_one_dimensional_data(x, y, filename='a') 3. write_one_dimensional_data(x, y, filename='a')
4. write_two_dimensional_data(x, y, matrix, filename='a') 4. write_two_dimensional_data(x, y, matrix, filename='a')
5. plot(x, y, xlabel='x', ylabel='y', title='', filename='a') 5. plot(x, y, xlabel='x', ylabel='y', title='', filename='a')
6. plot_3d_surface(x, y, matrix, xlabel='x', ylabel='y', zlabel='z', title='', filename='a') 6. plot_3d_surface(x, y, matrix, xlabel='x', ylabel='y', zlabel='z', title='', filename='a')
7. plot_contour(x, y, matrix, xlabel='x', ylabel='y', title='', filename='a') 7. plot_contour(x, y, matrix, xlabel='x', ylabel='y', title='', filename='a')
8. plot_2d_scatter(x, y, value, xlabel='x', ylabel='y', title='', filename='a') 8. plot_2d_scatter(x, y, value, xlabel='x', ylabel='y', title='', filename='a')
9. plot_3d_surface(x, y, z, value, xlabel='x', ylabel='y', zlabel='z', title='', filename='a') 9. plot_3d_surface(x, y, z, value, xlabel='x', ylabel='y', zlabel='z', title='', filename='a')
10. creat_animation(image_names, duration_time=0.5, filename='a') 10. creat_animation(image_names, duration_time=0.5, filename='a')
11. eigenvalue_array = calculate_eigenvalue_with_one_paramete(x, matrix) 11. eigenvalue_array = calculate_eigenvalue_with_one_paramete(x, matrix)
12. eigenvalue_array = calculate_eigenvalue_with_two_parameters(x, y, matrix) 12. eigenvalue_array = calculate_eigenvalue_with_two_parameters(x, y, matrix)
函数对应的功能 函数对应的功能
1. 读取filename.txt文件中的一维数据y(x) 1. 读取filename.txt文件中的一维数据y(x)
2. 读取filename.txt文件中的二维数据matrix(x,y) 2. 读取filename.txt文件中的二维数据matrix(x,y)
3. 把一维数据y(x)写入filename.txt文件 3. 把一维数据y(x)写入filename.txt文件
4. 把二维数据matrix(x,y)写入filename.txt文件 4. 把二维数据matrix(x,y)写入filename.txt文件
5. 画y(x)并保存到filename.jpg文件具体画图格式可在函数中修改 5. 画y(x)并保存到filename.jpg文件具体画图格式可在函数中修改
6. 画3d_surface图并保存到filename.jpg文件具体画图格式可在函数中修改 6. 画3d_surface图并保存到filename.jpg文件具体画图格式可在函数中修改
7. 画contour图并保存到filename.jpg文件具体画图格式可在函数中修改 7. 画contour图并保存到filename.jpg文件具体画图格式可在函数中修改
8. 画2d_scatter图并保存到filename.jpg文件具体画图格式可在函数中修改 8. 画2d_scatter图并保存到filename.jpg文件具体画图格式可在函数中修改
9. 画3d_scatter图并保存到filename.jpg文件具体画图格式可在函数中修改 9. 画3d_scatter图并保存到filename.jpg文件具体画图格式可在函数中修改
10. 制作动画 10. 制作动画
11. 在参数x下计算matrix函数的本征值eigenvalue_array[:, index] 11. 在参数x下计算matrix函数的本征值eigenvalue_array[:, index]
12. 在参数(x,y)计算matrix函数的本征值eigenvalue_array[:, :, index] 12. 在参数(x,y)计算matrix函数的本征值eigenvalue_array[:, :, index]
""" """
import numpy as np import numpy as np
# import os # import os
# os.chdir('D:/data') # os.chdir('D:/data')
def main(): def main():
pass # 读取数据 + 数据处理 + 保存新数据 pass # 读取数据 + 数据处理 + 保存新数据
# 1. 读取filename.txt文件中的一维数据y(x) # 1. 读取filename.txt文件中的一维数据y(x)
def read_one_dimensional_data(filename='a'): def read_one_dimensional_data(filename='a'):
f = open(filename+'.txt', 'r') f = open(filename+'.txt', 'r')
text = f.read() text = f.read()
f.close() f.close()
row_list = np.array(text.split('\n')) row_list = np.array(text.split('\n'))
dim_column = np.array(row_list[0].split()).shape[0] dim_column = np.array(row_list[0].split()).shape[0]
x = np.array([]) x = np.array([])
y = np.array([]) y = np.array([])
for row in row_list: for row in row_list:
column = np.array(row.split()) column = np.array(row.split())
if column.shape[0] != 0: if column.shape[0] != 0:
x = np.append(x, [float(column[0])], axis=0) x = np.append(x, [float(column[0])], axis=0)
y_row = np.zeros(dim_column-1) y_row = np.zeros(dim_column-1)
for dim0 in range(dim_column-1): for dim0 in range(dim_column-1):
y_row[dim0] = float(column[dim0+1]) y_row[dim0] = float(column[dim0+1])
if np.array(y).shape[0] == 0: if np.array(y).shape[0] == 0:
y = [y_row] y = [y_row]
else: else:
y = np.append(y, [y_row], axis=0) y = np.append(y, [y_row], axis=0)
return x, y return x, y
# 2. 读取filename.txt文件中的二维数据matrix(x,y) # 2. 读取filename.txt文件中的二维数据matrix(x,y)
def read_two_dimensional_data(filename='a'): def read_two_dimensional_data(filename='a'):
f = open(filename+'.txt', 'r') f = open(filename+'.txt', 'r')
text = f.read() text = f.read()
f.close() f.close()
row_list = np.array(text.split('\n')) row_list = np.array(text.split('\n'))
dim_column = np.array(row_list[0].split()).shape[0] dim_column = np.array(row_list[0].split()).shape[0]
x = np.array([]) x = np.array([])
y = np.array([]) y = np.array([])
matrix = np.array([]) matrix = np.array([])
for i0 in range(row_list.shape[0]): for i0 in range(row_list.shape[0]):
column = np.array(row_list[i0].split()) column = np.array(row_list[i0].split())
if i0 == 0: if i0 == 0:
x_str = column[1::] x_str = column[1::]
x = np.zeros(x_str.shape[0]) x = np.zeros(x_str.shape[0])
for i00 in range(x_str.shape[0]): for i00 in range(x_str.shape[0]):
x[i00] = float(x_str[i00]) x[i00] = float(x_str[i00])
elif column.shape[0] != 0: elif column.shape[0] != 0:
y = np.append(y, [float(column[0])], axis=0) y = np.append(y, [float(column[0])], axis=0)
matrix_row = np.zeros(dim_column-1) matrix_row = np.zeros(dim_column-1)
for dim0 in range(dim_column-1): for dim0 in range(dim_column-1):
matrix_row[dim0] = float(column[dim0+1]) matrix_row[dim0] = float(column[dim0+1])
if np.array(matrix).shape[0] == 0: if np.array(matrix).shape[0] == 0:
matrix = [matrix_row] matrix = [matrix_row]
else: else:
matrix = np.append(matrix, [matrix_row], axis=0) matrix = np.append(matrix, [matrix_row], axis=0)
return x, y, matrix return x, y, matrix
# 3. 把一维数据y(x)写入filename.txt文件 # 3. 把一维数据y(x)写入filename.txt文件
def write_one_dimensional_data(x, y, filename='a'): def write_one_dimensional_data(x, y, filename='a'):
with open(filename+'.txt', 'w') as f: with open(filename+'.txt', 'w') as f:
i0 = 0 i0 = 0
for x0 in x: for x0 in x:
f.write(str(x0)+' ') f.write(str(x0)+' ')
if len(y.shape) == 1: if len(y.shape) == 1:
f.write(str(y[i0])+'\n') f.write(str(y[i0])+'\n')
elif len(y.shape) == 2: elif len(y.shape) == 2:
for j0 in range(y.shape[1]): for j0 in range(y.shape[1]):
f.write(str(y[i0, j0])+' ') f.write(str(y[i0, j0])+' ')
f.write('\n') f.write('\n')
i0 += 1 i0 += 1
# 4. 把二维数据matrix(x,y)写入filename.txt文件 # 4. 把二维数据matrix(x,y)写入filename.txt文件
def write_two_dimensional_data(x, y, matrix, filename='a'): def write_two_dimensional_data(x, y, matrix, filename='a'):
with open(filename+'.txt', 'w') as f: with open(filename+'.txt', 'w') as f:
f.write('0 ') f.write('0 ')
for x0 in x: for x0 in x:
f.write(str(x0)+' ') f.write(str(x0)+' ')
f.write('\n') f.write('\n')
i0 = 0 i0 = 0
for y0 in y: for y0 in y:
f.write(str(y0)) f.write(str(y0))
j0 = 0 j0 = 0
for x0 in x: for x0 in x:
f.write(' '+str(matrix[i0, j0])+' ') f.write(' '+str(matrix[i0, j0])+' ')
j0 += 1 j0 += 1
f.write('\n') f.write('\n')
i0 += 1 i0 += 1
# 5. 画y(x)图并保存到filename.jpg文件。具体画图格式可在函数中修改。 # 5. 画y(x)图并保存到filename.jpg文件。具体画图格式可在函数中修改。
def plot(x, y, xlabel='x', ylabel='y', title='', filename='a', show=1, save=0): def plot(x, y, xlabel='x', ylabel='y', title='', filename='a', show=1, save=0):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
fig, ax = plt.subplots() fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.20, left=0.18) plt.subplots_adjust(bottom=0.20, left=0.18)
ax.plot(x, y, '-o') ax.plot(x, y, '-o')
ax.grid() ax.grid()
ax.set_title(title, fontsize=20, fontfamily='Times New Roman') ax.set_title(title, fontsize=20, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman')
ax.tick_params(labelsize=20) ax.tick_params(labelsize=20)
labels = ax.get_xticklabels() + ax.get_yticklabels() labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels] [label.set_fontname('Times New Roman') for label in labels]
if save == 1: if save == 1:
plt.savefig(filename+'.jpg', dpi=300) plt.savefig(filename+'.jpg', dpi=300)
if show == 1: if show == 1:
plt.show() plt.show()
plt.close('all') plt.close('all')
# 6. 画3d_surface图并保存到filename.jpg文件。具体画图格式可在函数中修改。 # 6. 画3d_surface图并保存到filename.jpg文件。具体画图格式可在函数中修改。
def plot_3d_surface(x, y, matrix, xlabel='x', ylabel='y', zlabel='z', title='', filename='a', show=1, save=0): def plot_3d_surface(x, y, matrix, xlabel='x', ylabel='y', zlabel='z', title='', filename='a', show=1, save=0):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from matplotlib import cm from matplotlib import cm
from matplotlib.ticker import LinearLocator from matplotlib.ticker import LinearLocator
fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
plt.subplots_adjust(bottom=0.1, right=0.65) plt.subplots_adjust(bottom=0.1, right=0.65)
x, y = np.meshgrid(x, y) x, y = np.meshgrid(x, y)
if len(matrix.shape) == 2: if len(matrix.shape) == 2:
surf = ax.plot_surface(x, y, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False) surf = ax.plot_surface(x, y, matrix, cmap=cm.coolwarm, linewidth=0, antialiased=False)
elif len(matrix.shape) == 3: elif len(matrix.shape) == 3:
for i0 in range(matrix.shape[2]): for i0 in range(matrix.shape[2]):
surf = ax.plot_surface(x, y, matrix[:,:,i0], cmap=cm.coolwarm, linewidth=0, antialiased=False) surf = ax.plot_surface(x, y, matrix[:,:,i0], cmap=cm.coolwarm, linewidth=0, antialiased=False)
ax.set_title(title, fontsize=20, fontfamily='Times New Roman') ax.set_title(title, fontsize=20, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman')
ax.set_zlabel(zlabel, fontsize=20, fontfamily='Times New Roman') ax.set_zlabel(zlabel, fontsize=20, fontfamily='Times New Roman')
ax.zaxis.set_major_locator(LinearLocator(5)) ax.zaxis.set_major_locator(LinearLocator(5))
ax.zaxis.set_major_formatter('{x:.2f}') ax.zaxis.set_major_formatter('{x:.2f}')
ax.tick_params(labelsize=15) ax.tick_params(labelsize=15)
labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels() labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()
[label.set_fontname('Times New Roman') for label in labels] [label.set_fontname('Times New Roman') for label in labels]
cax = plt.axes([0.80, 0.15, 0.05, 0.75]) cax = plt.axes([0.80, 0.15, 0.05, 0.75])
cbar = fig.colorbar(surf, cax=cax) cbar = fig.colorbar(surf, cax=cax)
cbar.ax.tick_params(labelsize=15) cbar.ax.tick_params(labelsize=15)
for l in cbar.ax.yaxis.get_ticklabels(): for l in cbar.ax.yaxis.get_ticklabels():
l.set_family('Times New Roman') l.set_family('Times New Roman')
if save == 1: if save == 1:
plt.savefig(filename+'.jpg', dpi=300) plt.savefig(filename+'.jpg', dpi=300)
if show == 1: if show == 1:
plt.show() plt.show()
plt.close('all') plt.close('all')
# 7. 画plot_contour图并保存到filename.jpg文件。具体画图格式可在函数中修改。 # 7. 画plot_contour图并保存到filename.jpg文件。具体画图格式可在函数中修改。
def plot_contour(x, y, matrix, xlabel='x', ylabel='y', title='', filename='a', show=1, save=0): def plot_contour(x, y, matrix, xlabel='x', ylabel='y', title='', filename='a', show=1, save=0):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from matplotlib import cm from matplotlib import cm
from matplotlib.ticker import LinearLocator from matplotlib.ticker import LinearLocator
fig, ax = plt.subplots() fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2, right=0.75, left = 0.16) plt.subplots_adjust(bottom=0.2, right=0.75, left = 0.16)
x, y = np.meshgrid(x, y) x, y = np.meshgrid(x, y)
contour = ax.contourf(x,y,matrix,cmap='jet') contour = ax.contourf(x,y,matrix,cmap='jet')
ax.set_title(title, fontsize=20, fontfamily='Times New Roman') ax.set_title(title, fontsize=20, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman')
ax.tick_params(labelsize=15) ax.tick_params(labelsize=15)
labels = ax.get_xticklabels() + ax.get_yticklabels() labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels] [label.set_fontname('Times New Roman') for label in labels]
cax = plt.axes([0.78, 0.17, 0.08, 0.71]) cax = plt.axes([0.78, 0.17, 0.08, 0.71])
cbar = fig.colorbar(contour, cax=cax) cbar = fig.colorbar(contour, cax=cax)
cbar.ax.tick_params(labelsize=15) cbar.ax.tick_params(labelsize=15)
for l in cbar.ax.yaxis.get_ticklabels(): for l in cbar.ax.yaxis.get_ticklabels():
l.set_family('Times New Roman') l.set_family('Times New Roman')
if save == 1: if save == 1:
plt.savefig(filename+'.jpg', dpi=300) plt.savefig(filename+'.jpg', dpi=300)
if show == 1: if show == 1:
plt.show() plt.show()
plt.close('all') plt.close('all')
# 8. 画2d_scatter图并保存到filename.jpg文件。具体画图格式可在函数中修改 # 8. 画2d_scatter图并保存到filename.jpg文件。具体画图格式可在函数中修改
def plot_2d_scatter(x, y, value, xlabel='x', ylabel='y', title='', filename='a', show=1, save=0): def plot_2d_scatter(x, y, value, xlabel='x', ylabel='y', title='', filename='a', show=1, save=0):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from matplotlib.axes._axes import _log as matplotlib_axes_logger from matplotlib.axes._axes import _log as matplotlib_axes_logger
matplotlib_axes_logger.setLevel('ERROR') matplotlib_axes_logger.setLevel('ERROR')
fig = plt.figure() fig = plt.figure()
ax = fig.add_subplot(111) ax = fig.add_subplot(111)
plt.subplots_adjust(bottom=0.2, right=0.8, left=0.2) plt.subplots_adjust(bottom=0.2, right=0.8, left=0.2)
for i in range(np.array(x).shape[0]): for i in range(np.array(x).shape[0]):
ax.scatter(x[i], y[i], marker='o', s=100*value[i], c=(1,0,0)) ax.scatter(x[i], y[i], marker='o', s=100*value[i], c=(1,0,0))
ax.set_title(title, fontsize=20, fontfamily='Times New Roman') ax.set_title(title, fontsize=20, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman')
ax.tick_params(labelsize=15) ax.tick_params(labelsize=15)
labels = ax.get_xticklabels() + ax.get_yticklabels() labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels] [label.set_fontname('Times New Roman') for label in labels]
if save == 1: if save == 1:
plt.savefig(filename+'.jpg', dpi=300) plt.savefig(filename+'.jpg', dpi=300)
if show == 1: if show == 1:
plt.show() plt.show()
plt.close('all') plt.close('all')
# 9. 画3d_scatter图并保存到filename.jpg文件。具体画图格式可在函数中修改 # 9. 画3d_scatter图并保存到filename.jpg文件。具体画图格式可在函数中修改
def plot_3d_scatter(x, y, z, value, xlabel='x', ylabel='y', zlabel='z', title='', filename='a', show=1, save=0): def plot_3d_scatter(x, y, z, value, xlabel='x', ylabel='y', zlabel='z', title='', filename='a', show=1, save=0):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from matplotlib.ticker import LinearLocator from matplotlib.ticker import LinearLocator
from matplotlib.axes._axes import _log as matplotlib_axes_logger from matplotlib.axes._axes import _log as matplotlib_axes_logger
matplotlib_axes_logger.setLevel('ERROR') matplotlib_axes_logger.setLevel('ERROR')
fig = plt.figure() fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') ax = fig.add_subplot(111, projection='3d')
plt.subplots_adjust(bottom=0.1, right=0.8) plt.subplots_adjust(bottom=0.1, right=0.8)
for i in range(np.array(x).shape[0]): for i in range(np.array(x).shape[0]):
ax.scatter(x[i], y[i], z[i], marker='o', s=int(100*value[i]), c=(1,0,0)) ax.scatter(x[i], y[i], z[i], marker='o', s=int(100*value[i]), c=(1,0,0))
ax.set_title(title, fontsize=20, fontfamily='Times New Roman') ax.set_title(title, fontsize=20, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman') ax.set_xlabel(xlabel, fontsize=20, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman') ax.set_ylabel(ylabel, fontsize=20, fontfamily='Times New Roman')
ax.set_zlabel(zlabel, fontsize=20, fontfamily='Times New Roman') ax.set_zlabel(zlabel, fontsize=20, fontfamily='Times New Roman')
ax.tick_params(labelsize=15) ax.tick_params(labelsize=15)
labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels() labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()
[label.set_fontname('Times New Roman') for label in labels] [label.set_fontname('Times New Roman') for label in labels]
if save == 1: if save == 1:
plt.savefig(filename+'.jpg', dpi=300) plt.savefig(filename+'.jpg', dpi=300)
if show == 1: if show == 1:
plt.show() plt.show()
plt.close('all') plt.close('all')
# 10. 制作动画 # 10. 制作动画
def creat_animation(image_names, duration_time=0.5, filename='a'): def creat_animation(image_names, duration_time=0.5, filename='a'):
import imageio import imageio
images = [] images = []
for name in image_names: for name in image_names:
image = name+'.jpg' image = name+'.jpg'
im = imageio.imread(image) im = imageio.imread(image)
images.append(im) images.append(im)
imageio.mimsave(filename+'.gif', images, 'GIF', duration=duration_time) # durantion是延迟时间 imageio.mimsave(filename+'.gif', images, 'GIF', duration=duration_time) # durantion是延迟时间
# 11. 在参数x下计算matrix函数的本征值eigenvalue_array[:, index] # 11. 在参数x下计算matrix函数的本征值eigenvalue_array[:, index]
def calculate_eigenvalue_with_one_parameter(x, matrix): def calculate_eigenvalue_with_one_parameter(x, matrix):
dim_x = np.array(x).shape[0] dim_x = np.array(x).shape[0]
i0 = 0 i0 = 0
if np.array(matrix(0)).shape==(): if np.array(matrix(0)).shape==():
eigenvalue_array = np.zeros((dim_x, 1)) eigenvalue_array = np.zeros((dim_x, 1))
for x0 in x: for x0 in x:
matrix0 = matrix(x0) matrix0 = matrix(x0)
eigenvalue_array[i0, 0] = np.real(matrix0) eigenvalue_array[i0, 0] = np.real(matrix0)
i0 += 1 i0 += 1
else: else:
dim = np.array(matrix(0)).shape[0] dim = np.array(matrix(0)).shape[0]
eigenvalue_array = np.zeros((dim_x, dim)) eigenvalue_array = np.zeros((dim_x, dim))
for x0 in x: for x0 in x:
matrix0 = matrix(x0) matrix0 = matrix(x0)
eigenvalue, eigenvector = np.linalg.eig(matrix0) eigenvalue, eigenvector = np.linalg.eig(matrix0)
eigenvalue_array[i0, :] = np.sort(np.real(eigenvalue[:])) eigenvalue_array[i0, :] = np.sort(np.real(eigenvalue[:]))
i0 += 1 i0 += 1
return eigenvalue_array return eigenvalue_array
# 12. 在参数(x,y)下计算matrix函数的本征值eigenvalue_array[:, :, index] # 12. 在参数(x,y)下计算matrix函数的本征值eigenvalue_array[:, :, index]
def calculate_eigenvalue_with_two_parameters(x, y, matrix): def calculate_eigenvalue_with_two_parameters(x, y, matrix):
dim_x = np.array(x).shape[0] dim_x = np.array(x).shape[0]
dim_y = np.array(y).shape[0] dim_y = np.array(y).shape[0]
if np.array(matrix(0,0)).shape==(): if np.array(matrix(0,0)).shape==():
eigenvalue_array = np.zeros((dim_y, dim_x, 1)) eigenvalue_array = np.zeros((dim_y, dim_x, 1))
i0 = 0 i0 = 0
for y0 in y: for y0 in y:
j0 = 0 j0 = 0
for x0 in x: for x0 in x:
matrix0 = matrix(x0, y0) matrix0 = matrix(x0, y0)
eigenvalue_array[i0, j0, 0] = np.real(matrix0) eigenvalue_array[i0, j0, 0] = np.real(matrix0)
j0 += 1 j0 += 1
i0 += 1 i0 += 1
else: else:
dim = np.array(matrix(0, 0)).shape[0] dim = np.array(matrix(0, 0)).shape[0]
eigenvalue_array = np.zeros((dim_y, dim_x, dim)) eigenvalue_array = np.zeros((dim_y, dim_x, dim))
i0 = 0 i0 = 0
for y0 in y: for y0 in y:
j0 = 0 j0 = 0
for x0 in x: for x0 in x:
matrix0 = matrix(x0, y0) matrix0 = matrix(x0, y0)
eigenvalue, eigenvector = np.linalg.eig(matrix0) eigenvalue, eigenvector = np.linalg.eig(matrix0)
eigenvalue_array[i0, j0, :] = np.sort(np.real(eigenvalue[:])) eigenvalue_array[i0, j0, :] = np.sort(np.real(eigenvalue[:]))
j0 += 1 j0 += 1
i0 += 1 i0 += 1
return eigenvalue_array return eigenvalue_array
if __name__ == "__main__": if __name__ == "__main__":
main() main()