test
test()
测试
查看源码
def test():
import guan
current_version = guan.get_current_version('guan')
print(f'Congratulations on successfully installing Guan package! The installed version is guan-{current_version}.')
testtest()
测试
def test():
import guan
current_version = guan.get_current_version('guan')
print(f'Congratulations on successfully installing Guan package! The installed version is guan-{current_version}.')
fundamental_constantsfundamental_constants()
基本常数
def fundamental_constants():
constants = {}
constants['c'] = 2.99792458e8 # 真空光速,单位:m/s(米每秒)
constants['h'] = 6.62607015e-34 # 普朗克常数,单位:J·s(焦耳·秒)
constants['hbar'] = 1.054571817e-34 # 约化普朗克常数 ħ = h / (2π),单位:J·s(焦耳·秒)
constants['q'] = 1.602176634e-19 # 基本电荷(元电荷),单位:C(库仑)
constants['eV'] = 1.602176634e-19 # 1 电子伏特(eV)对应的焦耳值,即 1 eV = q J
constants['k'] = 1.380649e-23 # 玻尔兹曼常数,单位:J/K(焦耳每开尔文)
constants['NA'] = 6.02214076e23 # 阿伏伽德罗常数,单位:mol⁻¹(每摩尔的粒子数)
constants['G'] = 6.67430e-11 # 万有引力常数,单位:m³/(kg·s²)
constants['mu0'] = 1.25663706212e-6 # 真空磁导率 μ₀ ≈ 4π × 10⁻⁷,单位:H/m(亨利每米)
constants['eps0'] = 8.8541878128e-12 # 真空介电常数 ε₀ = 1 / (μ₀ c²),单位:F/m(法拉每米)
constants['me'] = 9.1093837015e-31 # 电子静止质量,单位:kg(千克)
constants['mp'] = 1.67262192595e-27 # 质子静止质量,单位:kg(千克)
constants['mn'] = 1.67492749804e-27 # 中子静止质量,单位:kg(千克)
constants['alpha'] = 7.2973525693e-3 # 精细结构常数 α = e² / (4π ε₀ ħ c) ≈ 1/137,无量纲
constants['a0'] = 5.29177210903e-11 # 玻尔半径,单位:m
constants['T0'] = 273.15 # 标准温度参考点(0°C 对应的开尔文温度偏移),单位:K(开尔文)
return constants
sigma_0sigma_0()
泡利矩阵
def sigma_0():
import numpy as np
return np.eye(2)
sigma_xsigma_x()
def sigma_x():
import numpy as np
return np.array([[0, 1],[1, 0]])
sigma_ysigma_y()
def sigma_y():
import numpy as np
return np.array([[0, -1j],[1j, 0]])
sigma_zsigma_z()
def sigma_z():
import numpy as np
return np.array([[1, 0],[0, -1]])
sigma_00sigma_00()
泡利矩阵的张量积
调用了:guan.sigma_0
def sigma_00():
import numpy as np
import guan
return np.kron(guan.sigma_0(), guan.sigma_0())
sigma_0xsigma_0x()
调用了:guan.sigma_0, guan.sigma_x
def sigma_0x():
import numpy as np
import guan
return np.kron(guan.sigma_0(), guan.sigma_x())
sigma_0ysigma_0y()
调用了:guan.sigma_0, guan.sigma_y
def sigma_0y():
import numpy as np
import guan
return np.kron(guan.sigma_0(), guan.sigma_y())
sigma_0zsigma_0z()
调用了:guan.sigma_0, guan.sigma_z
def sigma_0z():
import numpy as np
import guan
return np.kron(guan.sigma_0(), guan.sigma_z())
sigma_x0sigma_x0()
调用了:guan.sigma_x, guan.sigma_0
def sigma_x0():
import numpy as np
import guan
return np.kron(guan.sigma_x(), guan.sigma_0())
sigma_xxsigma_xx()
调用了:guan.sigma_x
def sigma_xx():
import numpy as np
import guan
return np.kron(guan.sigma_x(), guan.sigma_x())
sigma_xysigma_xy()
调用了:guan.sigma_x, guan.sigma_y
def sigma_xy():
import numpy as np
import guan
return np.kron(guan.sigma_x(), guan.sigma_y())
sigma_xzsigma_xz()
调用了:guan.sigma_x, guan.sigma_z
def sigma_xz():
import numpy as np
import guan
return np.kron(guan.sigma_x(), guan.sigma_z())
sigma_y0sigma_y0()
调用了:guan.sigma_y, guan.sigma_0
def sigma_y0():
import numpy as np
import guan
return np.kron(guan.sigma_y(), guan.sigma_0())
sigma_yxsigma_yx()
调用了:guan.sigma_y, guan.sigma_x
def sigma_yx():
import numpy as np
import guan
return np.kron(guan.sigma_y(), guan.sigma_x())
sigma_yysigma_yy()
调用了:guan.sigma_y
def sigma_yy():
import numpy as np
import guan
return np.kron(guan.sigma_y(), guan.sigma_y())
sigma_yzsigma_yz()
调用了:guan.sigma_y, guan.sigma_z
def sigma_yz():
import numpy as np
import guan
return np.kron(guan.sigma_y(), guan.sigma_z())
sigma_z0sigma_z0()
调用了:guan.sigma_z, guan.sigma_0
def sigma_z0():
import numpy as np
import guan
return np.kron(guan.sigma_z(), guan.sigma_0())
sigma_zxsigma_zx()
调用了:guan.sigma_z, guan.sigma_x
def sigma_zx():
import numpy as np
import guan
return np.kron(guan.sigma_z(), guan.sigma_x())
sigma_zysigma_zy()
调用了:guan.sigma_z, guan.sigma_y
def sigma_zy():
import numpy as np
import guan
return np.kron(guan.sigma_z(), guan.sigma_y())
sigma_zzsigma_zz()
调用了:guan.sigma_z
def sigma_zz():
import numpy as np
import guan
return np.kron(guan.sigma_z(), guan.sigma_z())
one_dimensional_fourier_transformone_dimensional_fourier_transform(k, unit_cell, hopping)
通过元胞和跃迁项得到一维的哈密顿量(需要输入k值)
| 参数 | 类型 | 默认值 |
|---|---|---|
k | 必填 | |
unit_cell | 必填 | |
hopping | 必填 |
def one_dimensional_fourier_transform(k, unit_cell, hopping):
import numpy as np
import cmath
unit_cell = np.array(unit_cell)
hopping = np.array(hopping)
hamiltonian = unit_cell+hopping*cmath.exp(1j*k)+hopping.transpose().conj()*cmath.exp(-1j*k)
return hamiltonian
two_dimensional_fourier_transform_for_square_latticetwo_dimensional_fourier_transform_for_square_lattice(k1, k2, unit_cell, hopping_1, hopping_2)
通过元胞和跃迁项得到二维方格子的哈密顿量(需要输入k值)
| 参数 | 类型 | 默认值 |
|---|---|---|
k1 | 必填 | |
k2 | 必填 | |
unit_cell | 必填 | |
hopping_1 | 必填 | |
hopping_2 | 必填 |
def two_dimensional_fourier_transform_for_square_lattice(k1, k2, unit_cell, hopping_1, hopping_2):
import numpy as np
import cmath
unit_cell = np.array(unit_cell)
hopping_1 = np.array(hopping_1)
hopping_2 = np.array(hopping_2)
hamiltonian = unit_cell+hopping_1*cmath.exp(1j*k1)+hopping_1.transpose().conj()*cmath.exp(-1j*k1)+hopping_2*cmath.exp(1j*k2)+hopping_2.transpose().conj()*cmath.exp(-1j*k2)
return hamiltonian
three_dimensional_fourier_transform_for_cubic_latticethree_dimensional_fourier_transform_for_cubic_lattice(k1, k2, k3, unit_cell, hopping_1, hopping_2, hopping_3)
通过元胞和跃迁项得到三维立方格子的哈密顿量(需要输入k值)
| 参数 | 类型 | 默认值 |
|---|---|---|
k1 | 必填 | |
k2 | 必填 | |
k3 | 必填 | |
unit_cell | 必填 | |
hopping_1 | 必填 | |
hopping_2 | 必填 | |
hopping_3 | 必填 |
def three_dimensional_fourier_transform_for_cubic_lattice(k1, k2, k3, unit_cell, hopping_1, hopping_2, hopping_3):
import numpy as np
import cmath
unit_cell = np.array(unit_cell)
hopping_1 = np.array(hopping_1)
hopping_2 = np.array(hopping_2)
hopping_3 = np.array(hopping_3)
hamiltonian = unit_cell+hopping_1*cmath.exp(1j*k1)+hopping_1.transpose().conj()*cmath.exp(-1j*k1)+hopping_2*cmath.exp(1j*k2)+hopping_2.transpose().conj()*cmath.exp(-1j*k2)+hopping_3*cmath.exp(1j*k3)+hopping_3.transpose().conj()*cmath.exp(-1j*k3)
return hamiltonian
one_dimensional_fourier_transform_with_kone_dimensional_fourier_transform_with_k(unit_cell, hopping)
通过元胞和跃迁项得到一维的哈密顿量(返回的哈密顿量为携带k的函数)
| 参数 | 类型 | 默认值 |
|---|---|---|
unit_cell | 必填 | |
hopping | 必填 |
def one_dimensional_fourier_transform_with_k(unit_cell, hopping):
import functools
import guan
hamiltonian_function = functools.partial(guan.one_dimensional_fourier_transform, unit_cell=unit_cell, hopping=hopping)
return hamiltonian_function
two_dimensional_fourier_transform_for_square_lattice_with_k1_k2two_dimensional_fourier_transform_for_square_lattice_with_k1_k2(unit_cell, hopping_1, hopping_2)
通过元胞和跃迁项得到二维方格子的哈密顿量(返回的哈密顿量为携带k的函数)
| 参数 | 类型 | 默认值 |
|---|---|---|
unit_cell | 必填 | |
hopping_1 | 必填 | |
hopping_2 | 必填 |
def two_dimensional_fourier_transform_for_square_lattice_with_k1_k2(unit_cell, hopping_1, hopping_2):
import functools
import guan
hamiltonian_function = functools.partial(guan.two_dimensional_fourier_transform_for_square_lattice, unit_cell=unit_cell, hopping_1=hopping_1, hopping_2=hopping_2)
return hamiltonian_function
three_dimensional_fourier_transform_for_cubic_lattice_with_k1_k2_k3three_dimensional_fourier_transform_for_cubic_lattice_with_k1_k2_k3(unit_cell, hopping_1, hopping_2, hopping_3)
通过元胞和跃迁项得到三维立方格子的哈密顿量(返回的哈密顿量为携带k的函数)
| 参数 | 类型 | 默认值 |
|---|---|---|
unit_cell | 必填 | |
hopping_1 | 必填 | |
hopping_2 | 必填 | |
hopping_3 | 必填 |
def three_dimensional_fourier_transform_for_cubic_lattice_with_k1_k2_k3(unit_cell, hopping_1, hopping_2, hopping_3):
import functools
import guan
hamiltonian_function = functools.partial(guan.three_dimensional_fourier_transform_for_cubic_lattice, unit_cell=unit_cell, hopping_1=hopping_1, hopping_2=hopping_2, hopping_3=hopping_3)
return hamiltonian_function
calculate_one_dimensional_reciprocal_lattice_vectorcalculate_one_dimensional_reciprocal_lattice_vector(a1)
由实空间格矢得到倒空间格矢(一维)
| 参数 | 类型 | 默认值 |
|---|---|---|
a1 | 必填 |
def calculate_one_dimensional_reciprocal_lattice_vector(a1):
import numpy as np
b1 = 2*np.pi/a1
return b1
calculate_two_dimensional_reciprocal_lattice_vectorscalculate_two_dimensional_reciprocal_lattice_vectors(a1, a2)
由实空间格矢得到倒空间格矢(二维)
| 参数 | 类型 | 默认值 |
|---|---|---|
a1 | 必填 | |
a2 | 必填 |
def calculate_two_dimensional_reciprocal_lattice_vectors(a1, a2):
import numpy as np
a1 = np.array(a1)
a2 = np.array(a2)
a1 = np.append(a1, 0)
a2 = np.append(a2, 0)
a3 = np.array([0, 0, 1])
b1 = 2*np.pi*np.cross(a2, a3)/np.dot(a1, np.cross(a2, a3))
b2 = 2*np.pi*np.cross(a3, a1)/np.dot(a1, np.cross(a2, a3))
b1 = np.delete(b1, 2)
b2 = np.delete(b2, 2)
return b1, b2
calculate_three_dimensional_reciprocal_lattice_vectorscalculate_three_dimensional_reciprocal_lattice_vectors(a1, a2, a3)
由实空间格矢得到倒空间格矢(三维)
| 参数 | 类型 | 默认值 |
|---|---|---|
a1 | 必填 | |
a2 | 必填 | |
a3 | 必填 |
def calculate_three_dimensional_reciprocal_lattice_vectors(a1, a2, a3):
import numpy as np
a1 = np.array(a1)
a2 = np.array(a2)
a3 = np.array(a3)
b1 = 2*np.pi*np.cross(a2, a3)/np.dot(a1, np.cross(a2, a3))
b2 = 2*np.pi*np.cross(a3, a1)/np.dot(a1, np.cross(a2, a3))
b3 = 2*np.pi*np.cross(a1, a2)/np.dot(a1, np.cross(a2, a3))
return b1, b2, b3
calculate_one_dimensional_reciprocal_lattice_vector_with_sympycalculate_one_dimensional_reciprocal_lattice_vector_with_sympy(a1)
由实空间格矢得到倒空间格矢(一维),这里为符号运算
| 参数 | 类型 | 默认值 |
|---|---|---|
a1 | 必填 |
def calculate_one_dimensional_reciprocal_lattice_vector_with_sympy(a1):
import sympy
b1 = 2*sympy.pi/a1
return b1
calculate_two_dimensional_reciprocal_lattice_vectors_with_sympycalculate_two_dimensional_reciprocal_lattice_vectors_with_sympy(a1, a2)
由实空间格矢得到倒空间格矢(二维),这里为符号运算
| 参数 | 类型 | 默认值 |
|---|---|---|
a1 | 必填 | |
a2 | 必填 |
def calculate_two_dimensional_reciprocal_lattice_vectors_with_sympy(a1, a2):
import sympy
a1 = sympy.Matrix(1, 3, [a1[0], a1[1], 0])
a2 = sympy.Matrix(1, 3, [a2[0], a2[1], 0])
a3 = sympy.Matrix(1, 3, [0, 0, 1])
cross_a2_a3 = a2.cross(a3)
cross_a3_a1 = a3.cross(a1)
b1 = 2*sympy.pi*cross_a2_a3/a1.dot(cross_a2_a3)
b2 = 2*sympy.pi*cross_a3_a1/a1.dot(cross_a2_a3)
b1 = sympy.Matrix(1, 2, [b1[0], b1[1]])
b2 = sympy.Matrix(1, 2, [b2[0], b2[1]])
return b1, b2
calculate_three_dimensional_reciprocal_lattice_vectors_with_sympycalculate_three_dimensional_reciprocal_lattice_vectors_with_sympy(a1, a2, a3)
由实空间格矢得到倒空间格矢(三维),这里为符号运算
| 参数 | 类型 | 默认值 |
|---|---|---|
a1 | 必填 | |
a2 | 必填 | |
a3 | 必填 |
def calculate_three_dimensional_reciprocal_lattice_vectors_with_sympy(a1, a2, a3):
import sympy
cross_a2_a3 = a2.cross(a3)
cross_a3_a1 = a3.cross(a1)
cross_a1_a2 = a1.cross(a2)
b1 = 2*sympy.pi*cross_a2_a3/a1.dot(cross_a2_a3)
b2 = 2*sympy.pi*cross_a3_a1/a1.dot(cross_a2_a3)
b3 = 2*sympy.pi*cross_a1_a2/a1.dot(cross_a2_a3)
return b1, b2, b3
hamiltonian_of_finite_size_system_along_one_directionhamiltonian_of_finite_size_system_along_one_direction(N, on_site=0, hopping=1, period=0)
构建一维的有限尺寸体系哈密顿量(可设置是否为周期边界条件)
| 参数 | 类型 | 默认值 |
|---|---|---|
N | 必填 | |
on_site | 0 | |
hopping | 1 | |
period | 0 |
def hamiltonian_of_finite_size_system_along_one_direction(N, on_site=0, hopping=1, period=0):
import numpy as np
on_site = np.array(on_site)
hopping = np.array(hopping)
if on_site.shape==():
dim = 1
else:
dim = on_site.shape[0]
hamiltonian = np.zeros((N*dim, N*dim), dtype=complex)
for i0 in range(N):
hamiltonian[i0*dim+0:i0*dim+dim, i0*dim+0:i0*dim+dim] = on_site
for i0 in range(N-1):
hamiltonian[i0*dim+0:i0*dim+dim, (i0+1)*dim+0:(i0+1)*dim+dim] = hopping
hamiltonian[(i0+1)*dim+0:(i0+1)*dim+dim, i0*dim+0:i0*dim+dim] = hopping.transpose().conj()
if period == 1:
hamiltonian[(N-1)*dim+0:(N-1)*dim+dim, 0:dim] = hopping
hamiltonian[0:dim, (N-1)*dim+0:(N-1)*dim+dim] = hopping.transpose().conj()
return hamiltonian
hamiltonian_of_finite_size_system_along_two_directions_for_square_latticehamiltonian_of_finite_size_system_along_two_directions_for_square_lattice(N1, N2, on_site=0, hopping_1=1, hopping_2=1, period_1=0, period_2=0)
构建二维的方格子有限尺寸体系哈密顿量(可设置是否为周期边界条件)
| 参数 | 类型 | 默认值 |
|---|---|---|
N1 | 必填 | |
N2 | 必填 | |
on_site | 0 | |
hopping_1 | 1 | |
hopping_2 | 1 | |
period_1 | 0 | |
period_2 | 0 |
def hamiltonian_of_finite_size_system_along_two_directions_for_square_lattice(N1, N2, on_site=0, hopping_1=1, hopping_2=1, period_1=0, period_2=0):
import numpy as np
on_site = np.array(on_site)
hopping_1 = np.array(hopping_1)
hopping_2 = np.array(hopping_2)
if on_site.shape==():
dim = 1
else:
dim = on_site.shape[0]
hamiltonian = np.zeros((N1*N2*dim, N1*N2*dim), dtype=complex)
for i1 in range(N1):
for i2 in range(N2):
hamiltonian[i1*N2*dim+i2*dim+0:i1*N2*dim+i2*dim+dim, i1*N2*dim+i2*dim+0:i1*N2*dim+i2*dim+dim] = on_site
for i1 in range(N1-1):
for i2 in range(N2):
hamiltonian[i1*N2*dim+i2*dim+0:i1*N2*dim+i2*dim+dim, (i1+1)*N2*dim+i2*dim+0:(i1+1)*N2*dim+i2*dim+dim] = hopping_1
hamiltonian[(i1+1)*N2*dim+i2*dim+0:(i1+1)*N2*dim+i2*dim+dim, i1*N2*dim+i2*dim+0:i1*N2*dim+i2*dim+dim] = hopping_1.transpose().conj()
for i1 in range(N1):
for i2 in range(N2-1):
hamiltonian[i1*N2*dim+i2*dim+0:i1*N2*dim+i2*dim+dim, i1*N2*dim+(i2+1)*dim+0:i1*N2*dim+(i2+1)*dim+dim] = hopping_2
hamiltonian[i1*N2*dim+(i2+1)*dim+0:i1*N2*dim+(i2+1)*dim+dim, i1*N2*dim+i2*dim+0:i1*N2*dim+i2*dim+dim] = hopping_2.transpose().conj()
if period_1 == 1:
for i2 in range(N2):
hamiltonian[(N1-1)*N2*dim+i2*dim+0:(N1-1)*N2*dim+i2*dim+dim, i2*dim+0:i2*dim+dim] = hopping_1
hamiltonian[i2*dim+0:i2*dim+dim, (N1-1)*N2*dim+i2*dim+0:(N1-1)*N2*dim+i2*dim+dim] = hopping_1.transpose().conj()
if period_2 == 1:
for i1 in range(N1):
hamiltonian[i1*N2*dim+(N2-1)*dim+0:i1*N2*dim+(N2-1)*dim+dim, i1*N2*dim+0:i1*N2*dim+dim] = hopping_2
hamiltonian[i1*N2*dim+0:i1*N2*dim+dim, i1*N2*dim+(N2-1)*dim+0:i1*N2*dim+(N2-1)*dim+dim] = hopping_2.transpose().conj()
return hamiltonian
hamiltonian_of_finite_size_system_along_three_directions_for_cubic_latticehamiltonian_of_finite_size_system_along_three_directions_for_cubic_lattice(N1, N2, N3, on_site=0, hopping_1=1, hopping_2=1, hopping_3=1, period_1=0, period_2=0, period_3=0)
构建三维的立方格子有限尺寸体系哈密顿量(可设置是否为周期边界条件)
| 参数 | 类型 | 默认值 |
|---|---|---|
N1 | 必填 | |
N2 | 必填 | |
N3 | 必填 | |
on_site | 0 | |
hopping_1 | 1 | |
hopping_2 | 1 | |
hopping_3 | 1 | |
period_1 | 0 | |
period_2 | 0 | |
period_3 | 0 |
def hamiltonian_of_finite_size_system_along_three_directions_for_cubic_lattice(N1, N2, N3, on_site=0, hopping_1=1, hopping_2=1, hopping_3=1, period_1=0, period_2=0, period_3=0):
import numpy as np
on_site = np.array(on_site)
hopping_1 = np.array(hopping_1)
hopping_2 = np.array(hopping_2)
hopping_3 = np.array(hopping_3)
if on_site.shape==():
dim = 1
else:
dim = on_site.shape[0]
hamiltonian = np.zeros((N1*N2*N3*dim, N1*N2*N3*dim), dtype=complex)
for i1 in range(N1):
for i2 in range(N2):
for i3 in range(N3):
hamiltonian[i1*N2*N3*dim+i2*N3*dim+i3*dim+0:i1*N2*N3*dim+i2*N3*dim+i3*dim+dim, i1*N2*N3*dim+i2*N3*dim+i3*dim+0:i1*N2*N3*dim+i2*N3*dim+i3*dim+dim] = on_site
for i1 in range(N1-1):
for i2 in range(N2):
for i3 in range(N3):
hamiltonian[i1*N2*N3*dim+i2*N3*dim+i3*dim+0:i1*N2*N3*dim+i2*N3*dim+i3*dim+dim, (i1+1)*N2*N3*dim+i2*N3*dim+i3*dim+0:(i1+1)*N2*N3*dim+i2*N3*dim+i3*dim+dim] = hopping_1
hamiltonian[(i1+1)*N2*N3*dim+i2*N3*dim+i3*dim+0:(i1+1)*N2*N3*dim+i2*N3*dim+i3*dim+dim, i1*N2*N3*dim+i2*N3*dim+i3*dim+0:i1*N2*N3*dim+i2*N3*dim+i3*dim+dim] = hopping_1.transpose().conj()
for i1 in range(N1):
for i2 in range(N2-1):
for i3 in range(N3):
hamiltonian[i1*N2*N3*dim+i2*N3*dim+i3*dim+0:i1*N2*N3*dim+i2*N3*dim+i3*dim+dim, i1*N2*N3*dim+(i2+1)*N3*dim+i3*dim+0:i1*N2*N3*dim+(i2+1)*N3*dim+i3*dim+dim] = hopping_2
hamiltonian[i1*N2*N3*dim+(i2+1)*N3*dim+i3*dim+0:i1*N2*N3*dim+(i2+1)*N3*dim+i3*dim+dim, i1*N2*N3*dim+i2*N3*dim+i3*dim+0:i1*N2*N3*dim+i2*N3*dim+i3*dim+dim] = hopping_2.transpose().conj()
for i1 in range(N1):
for i2 in range(N2):
for i3 in range(N3-1):
hamiltonian[i1*N2*N3*dim+i2*N3*dim+i3*dim+0:i1*N2*N3*dim+i2*N3*dim+i3*dim+dim, i1*N2*N3*dim+i2*N3*dim+(i3+1)*dim+0:i1*N2*N3*dim+i2*N3*dim+(i3+1)*dim+dim] = hopping_3
hamiltonian[i1*N2*N3*dim+i2*N3*dim+(i3+1)*dim+0:i1*N2*N3*dim+i2*N3*dim+(i3+1)*dim+dim, i1*N2*N3*dim+i2*N3*dim+i3*dim+0:i1*N2*N3*dim+i2*N3*dim+i3*dim+dim] = hopping_3.transpose().conj()
if period_1 == 1:
for i2 in range(N2):
for i3 in range(N3):
hamiltonian[(N1-1)*N2*N3*dim+i2*N3*dim+i3*dim+0:(N1-1)*N2*N3*dim+i2*N3*dim+i3*dim+dim, i2*N3*dim+i3*dim+0:i2*N3*dim+i3*dim+dim] = hopping_1
hamiltonian[i2*N3*dim+i3*dim+0:i2*N3*dim+i3*dim+dim, (N1-1)*N2*N3*dim+i2*N3*dim+i3*dim+0:(N1-1)*N2*N3*dim+i2*N3*dim+i3*dim+dim] = hopping_1.transpose().conj()
if period_2 == 1:
for i1 in range(N1):
for i3 in range(N3):
hamiltonian[i1*N2*N3*dim+(N2-1)*N3*dim+i3*dim+0:i1*N2*N3*dim+(N2-1)*N3*dim+i3*dim+dim, i1*N2*N3*dim+i3*dim+0:i1*N2*N3*dim+i3*dim+dim] = hopping_2
hamiltonian[i1*N2*N3*dim+i3*dim+0:i1*N2*N3*dim+i3*dim+dim, i1*N2*N3*dim+(N2-1)*N3*dim+i3*dim+0:i1*N2*N3*dim+(N2-1)*N3*dim+i3*dim+dim] = hopping_2.transpose().conj()
if period_3 == 1:
for i1 in range(N1):
for i2 in range(N2):
hamiltonian[i1*N2*N3*dim+i2*N3*dim+(N3-1)*dim+0:i1*N2*N3*dim+i2*N3*dim+(N3-1)*dim+dim, i1*N2*N3*dim+i2*N3*dim+0:i1*N2*N3*dim+i2*N3*dim+dim] = hopping_3
hamiltonian[i1*N2*N3*dim+i2*N3*dim+0:i1*N2*N3*dim+i2*N3*dim+dim, i1*N2*N3*dim+i2*N3*dim+(N3-1)*dim+0:i1*N2*N3*dim+i2*N3*dim+(N3-1)*dim+dim] = hopping_3.transpose().conj()
return hamiltonian
hamiltonian_of_finite_size_ssh_modelhamiltonian_of_finite_size_ssh_model(N, v=0.6, w=1, onsite_1=0, onsite_2=0, period=1)
构建有限尺寸的SSH模型哈密顿量
| 参数 | 类型 | 默认值 |
|---|---|---|
N | 必填 | |
v | 0.6 | |
w | 1 | |
onsite_1 | 0 | |
onsite_2 | 0 | |
period | 1 |
def hamiltonian_of_finite_size_ssh_model(N, v=0.6, w=1, onsite_1=0, onsite_2=0, period=1):
import numpy as np
hamiltonian = np.zeros((2*N, 2*N))
for i in range(N):
hamiltonian[i*2+0, i*2+0] = onsite_1
hamiltonian[i*2+1, i*2+1] = onsite_2
hamiltonian[i*2+0, i*2+1] = v
hamiltonian[i*2+1, i*2+0] = v
for i in range(N-1):
hamiltonian[i*2+1, (i+1)*2+0] = w
hamiltonian[(i+1)*2+0, i*2+1] = w
if period==1:
hamiltonian[0, 2*N-1] = w
hamiltonian[2*N-1, 0] = w
return hamiltonian
get_hopping_term_of_graphene_ribbon_along_zigzag_directionget_hopping_term_of_graphene_ribbon_along_zigzag_direction(N, eta=0)
获取Zigzag边的石墨烯条带的元胞间跃迁
| 参数 | 类型 | 默认值 |
|---|---|---|
N | 必填 | |
eta | 0 |
def get_hopping_term_of_graphene_ribbon_along_zigzag_direction(N, eta=0):
import numpy as np
hopping = np.zeros((4*N, 4*N), dtype=complex)
for i0 in range(N):
hopping[4*i0+0, 4*i0+0] = eta
hopping[4*i0+1, 4*i0+1] = eta
hopping[4*i0+2, 4*i0+2] = eta
hopping[4*i0+3, 4*i0+3] = eta
hopping[4*i0+1, 4*i0+0] = 1
hopping[4*i0+2, 4*i0+3] = 1
return hopping
hamiltonian_of_finite_size_system_along_two_directions_for_graphenehamiltonian_of_finite_size_system_along_two_directions_for_graphene(N1, N2, period_1=0, period_2=0)
构建有限尺寸的石墨烯哈密顿量(可设置是否为周期边界条件)
| 参数 | 类型 | 默认值 |
|---|---|---|
N1 | 必填 | |
N2 | 必填 | |
period_1 | 0 | |
period_2 | 0 |
调用了:guan.hamiltonian_of_finite_size_system_along_one_direction, guan.get_hopping_term_of_graphene_ribbon_along_zigzag_direction, guan.hamiltonian_of_finite_size_system_along_two_directions_for_square_lattice
def hamiltonian_of_finite_size_system_along_two_directions_for_graphene(N1, N2, period_1=0, period_2=0):
import numpy as np
import guan
on_site = guan.hamiltonian_of_finite_size_system_along_one_direction(4)
hopping_1 = guan.get_hopping_term_of_graphene_ribbon_along_zigzag_direction(1)
hopping_2 = np.zeros((4, 4), dtype=complex)
hopping_2[3, 0] = 1
hamiltonian = guan.hamiltonian_of_finite_size_system_along_two_directions_for_square_lattice(N1, N2, on_site, hopping_1, hopping_2, period_1, period_2)
return hamiltonian
get_onsite_and_hopping_terms_of_2d_effective_graphene_along_one_directionget_onsite_and_hopping_terms_of_2d_effective_graphene_along_one_direction(qy, t=1, staggered_potential=0, eta=0, valley_index=0)
获取石墨烯有效模型沿着x方向的在位能和跃迁项(其中,动量qy为参数)
| 参数 | 类型 | 默认值 |
|---|---|---|
qy | 必填 | |
t | 1 | |
staggered_potential | 0 | |
eta | 0 | |
valley_index | 0 |
def get_onsite_and_hopping_terms_of_2d_effective_graphene_along_one_direction(qy, t=1, staggered_potential=0, eta=0, valley_index=0):
import numpy as np
constant = -np.sqrt(3)/2
h00 = np.zeros((2, 2), dtype=complex)
h00[0, 0] = staggered_potential
h00[1, 1] = -staggered_potential
h00[0, 1] = -1j*constant*t*np.sin(qy)
h00[1, 0] = 1j*constant*t*np.sin(qy)
h01 = np.zeros((2, 2), dtype=complex)
h01[0, 0] = eta
h01[1, 1] = eta
if valley_index == 0:
h01[0, 1] = constant*t*(-1j/2)
h01[1, 0] = constant*t*(-1j/2)
else:
h01[0, 1] = constant*t*(1j/2)
h01[1, 0] = constant*t*(1j/2)
return h00, h01
get_onsite_and_hopping_terms_of_bhz_modelget_onsite_and_hopping_terms_of_bhz_model(A=0.3645 / 5, B=-0.686 / 25, C=0, D=-0.512 / 25, M=-0.01, a=1)
获取BHZ模型的在位能和跃迁项
| 参数 | 类型 | 默认值 |
|---|---|---|
A | 0.3645 / 5 | |
B | -0.686 / 25 | |
C | 0 | |
D | -0.512 / 25 | |
M | -0.01 | |
a | 1 |
def get_onsite_and_hopping_terms_of_bhz_model(A=0.3645/5, B=-0.686/25, C=0, D=-0.512/25, M=-0.01, a=1):
import numpy as np
E_s = C+M-4*(D+B)/(a**2)
E_p = C-M-4*(D-B)/(a**2)
V_ss = (D+B)/(a**2)
V_pp = (D-B)/(a**2)
V_sp = -1j*A/(2*a)
H0 = np.zeros((4, 4), dtype=complex)
H1 = np.zeros((4, 4), dtype=complex)
H2 = np.zeros((4, 4), dtype=complex)
H0[0, 0] = E_s
H0[1, 1] = E_p
H0[2, 2] = E_s
H0[3, 3] = E_p
H1[0, 0] = V_ss
H1[1, 1] = V_pp
H1[2, 2] = V_ss
H1[3, 3] = V_pp
H1[0, 1] = V_sp
H1[1, 0] = -np.conj(V_sp)
H1[2, 3] = np.conj(V_sp)
H1[3, 2] = -V_sp
H2[0, 0] = V_ss
H2[1, 1] = V_pp
H2[2, 2] = V_ss
H2[3, 3] = V_pp
H2[0, 1] = 1j*V_sp
H2[1, 0] = 1j*np.conj(V_sp)
H2[2, 3] = -1j*np.conj(V_sp)
H2[3, 2] = -1j*V_sp
return H0, H1, H2
get_onsite_and_hopping_terms_of_half_bhz_model_for_spin_upget_onsite_and_hopping_terms_of_half_bhz_model_for_spin_up(A=0.3645 / 5, B=-0.686 / 25, C=0, D=-0.512 / 25, M=-0.01, a=1)
获取半个BHZ模型的在位能和跃迁项(自旋向上)
| 参数 | 类型 | 默认值 |
|---|---|---|
A | 0.3645 / 5 | |
B | -0.686 / 25 | |
C | 0 | |
D | -0.512 / 25 | |
M | -0.01 | |
a | 1 |
def get_onsite_and_hopping_terms_of_half_bhz_model_for_spin_up(A=0.3645/5, B=-0.686/25, C=0, D=-0.512/25, M=-0.01, a=1):
import numpy as np
E_s = C+M-4*(D+B)/(a**2)
E_p = C-M-4*(D-B)/(a**2)
V_ss = (D+B)/(a**2)
V_pp = (D-B)/(a**2)
V_sp = -1j*A/(2*a)
H0 = np.zeros((2, 2), dtype=complex)
H1 = np.zeros((2, 2), dtype=complex)
H2 = np.zeros((2, 2), dtype=complex)
H0[0, 0] = E_s
H0[1, 1] = E_p
H1[0, 0] = V_ss
H1[1, 1] = V_pp
H1[0, 1] = V_sp
H1[1, 0] = -np.conj(V_sp)
H2[0, 0] = V_ss
H2[1, 1] = V_pp
H2[0, 1] = 1j*V_sp
H2[1, 0] = 1j*np.conj(V_sp)
return H0, H1, H2
get_onsite_and_hopping_terms_of_half_bhz_model_for_spin_downget_onsite_and_hopping_terms_of_half_bhz_model_for_spin_down(A=0.3645 / 5, B=-0.686 / 25, C=0, D=-0.512 / 25, M=-0.01, a=1)
获取半个BHZ模型的在位能和跃迁项(自旋向下)
| 参数 | 类型 | 默认值 |
|---|---|---|
A | 0.3645 / 5 | |
B | -0.686 / 25 | |
C | 0 | |
D | -0.512 / 25 | |
M | -0.01 | |
a | 1 |
def get_onsite_and_hopping_terms_of_half_bhz_model_for_spin_down(A=0.3645/5, B=-0.686/25, C=0, D=-0.512/25, M=-0.01, a=1):
import numpy as np
E_s = C+M-4*(D+B)/(a**2)
E_p = C-M-4*(D-B)/(a**2)
V_ss = (D+B)/(a**2)
V_pp = (D-B)/(a**2)
V_sp = -1j*A/(2*a)
H0 = np.zeros((2, 2), dtype=complex)
H1 = np.zeros((2, 2), dtype=complex)
H2 = np.zeros((2, 2), dtype=complex)
H0[0, 0] = E_s
H0[1, 1] = E_p
H1[0, 0] = V_ss
H1[1, 1] = V_pp
H1[0, 1] = np.conj(V_sp)
H1[1, 0] = -V_sp
H2[0, 0] = V_ss
H2[1, 1] = V_pp
H2[0, 1] = -1j*np.conj(V_sp)
H2[1, 0] = -1j*V_sp
return H0, H1, H2
hamiltonian_of_simple_chainhamiltonian_of_simple_chain(k)
一维链的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
k | 必填 |
调用了:guan.one_dimensional_fourier_transform
def hamiltonian_of_simple_chain(k):
import guan
hamiltonian = guan.one_dimensional_fourier_transform(k, unit_cell=0, hopping=1)
return hamiltonian
hamiltonian_of_square_latticehamiltonian_of_square_lattice(k1, k2)
二维方格子的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
k1 | 必填 | |
k2 | 必填 |
调用了:guan.two_dimensional_fourier_transform_for_square_lattice
def hamiltonian_of_square_lattice(k1, k2):
import guan
hamiltonian = guan.two_dimensional_fourier_transform_for_square_lattice(k1, k2, unit_cell=0, hopping_1=1, hopping_2=1)
return hamiltonian
hamiltonian_of_square_lattice_in_quasi_one_dimensionhamiltonian_of_square_lattice_in_quasi_one_dimension(k, N=10, period=0)
准一维方格子条带的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
k | 必填 | |
N | 10 | |
period | 0 |
调用了:guan.one_dimensional_fourier_transform
def hamiltonian_of_square_lattice_in_quasi_one_dimension(k, N=10, period=0):
import numpy as np
import guan
h00 = np.zeros((N, N), dtype=complex) # hopping in a unit cell
h01 = np.zeros((N, N), dtype=complex) # hopping between unit cells
for i in range(N-1):
h00[i, i+1] = 1
h00[i+1, i] = 1
if period == 1:
h00[N-1, 0] = 1
h00[0, N-1] = 1
for i in range(N):
h01[i, i] = 1
hamiltonian = guan.one_dimensional_fourier_transform(k, unit_cell=h00, hopping=h01)
return hamiltonian
hamiltonian_of_cubic_latticehamiltonian_of_cubic_lattice(k1, k2, k3)
三维立方格子的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
k1 | 必填 | |
k2 | 必填 | |
k3 | 必填 |
调用了:guan.three_dimensional_fourier_transform_for_cubic_lattice
def hamiltonian_of_cubic_lattice(k1, k2, k3):
import guan
hamiltonian = guan.three_dimensional_fourier_transform_for_cubic_lattice(k1, k2, k3, unit_cell=0, hopping_1=1, hopping_2=1, hopping_3=1)
return hamiltonian
hamiltonian_of_ssh_modelhamiltonian_of_ssh_model(k, v=0.6, w=1)
SSH模型的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
k | 必填 | |
v | 0.6 | |
w | 1 |
def hamiltonian_of_ssh_model(k, v=0.6, w=1):
import numpy as np
import cmath
hamiltonian = np.zeros((2, 2), dtype=complex)
hamiltonian[0,1] = v+w*cmath.exp(-1j*k)
hamiltonian[1,0] = v+w*cmath.exp(1j*k)
return hamiltonian
hamiltonian_of_graphenehamiltonian_of_graphene(k1, k2, staggered_potential=0, t=1, a='default')
石墨烯的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
k1 | 必填 | |
k2 | 必填 | |
staggered_potential | 0 | |
t | 1 | |
a | 'default' |
def hamiltonian_of_graphene(k1, k2, staggered_potential=0, t=1, a='default'):
import numpy as np
import cmath
import math
if a == 'default':
a = 1/math.sqrt(3)
h0 = np.zeros((2, 2), dtype=complex) # mass term
h1 = np.zeros((2, 2), dtype=complex) # nearest hopping
h0[0, 0] = staggered_potential
h0[1, 1] = -staggered_potential
h1[1, 0] = t*(cmath.exp(1j*k2*a)+cmath.exp(1j*math.sqrt(3)/2*k1*a-1j/2*k2*a)+cmath.exp(-1j*math.sqrt(3)/2*k1*a-1j/2*k2*a))
h1[0, 1] = h1[1, 0].conj()
hamiltonian = h0 + h1
return hamiltonian
effective_hamiltonian_of_grapheneeffective_hamiltonian_of_graphene(qx, qy, t=1, staggered_potential=0, valley_index=0)
石墨烯有效模型的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
qx | 必填 | |
qy | 必填 | |
t | 1 | |
staggered_potential | 0 | |
valley_index | 0 |
def effective_hamiltonian_of_graphene(qx, qy, t=1, staggered_potential=0, valley_index=0):
import numpy as np
hamiltonian = np.zeros((2, 2), dtype=complex)
hamiltonian[0, 0] = staggered_potential
hamiltonian[1, 1] = -staggered_potential
constant = -np.sqrt(3)/2
if valley_index == 0:
hamiltonian[0, 1] = constant*t*(qx-1j*qy)
hamiltonian[1, 0] = constant*t*(qx+1j*qy)
else:
hamiltonian[0, 1] = constant*t*(-qx-1j*qy)
hamiltonian[1, 0] = constant*t*(-qx+1j*qy)
return hamiltonian
effective_hamiltonian_of_graphene_after_discretizationeffective_hamiltonian_of_graphene_after_discretization(qx, qy, t=1, staggered_potential=0, valley_index=0)
石墨烯有效模型离散化后的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
qx | 必填 | |
qy | 必填 | |
t | 1 | |
staggered_potential | 0 | |
valley_index | 0 |
def effective_hamiltonian_of_graphene_after_discretization(qx, qy, t=1, staggered_potential=0, valley_index=0):
import numpy as np
hamiltonian = np.zeros((2, 2), dtype=complex)
hamiltonian[0, 0] = staggered_potential
hamiltonian[1, 1] = -staggered_potential
constant = -np.sqrt(3)/2
if valley_index == 0:
hamiltonian[0, 1] = constant*t*(np.sin(qx)-1j*np.sin(qy))
hamiltonian[1, 0] = constant*t*(np.sin(qx)+1j*np.sin(qy))
else:
hamiltonian[0, 1] = constant*t*(-np.sin(qx)-1j*np.sin(qy))
hamiltonian[1, 0] = constant*t*(-np.sin(qx)+1j*np.sin(qy))
return hamiltonian
hamiltonian_of_graphene_with_zigzag_in_quasi_one_dimensionhamiltonian_of_graphene_with_zigzag_in_quasi_one_dimension(k, N=10, M=0, t=1, period=0)
准一维Zigzag边石墨烯条带的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
k | 必填 | |
N | 10 | |
M | 0 | |
t | 1 | |
period | 0 |
调用了:guan.one_dimensional_fourier_transform
def hamiltonian_of_graphene_with_zigzag_in_quasi_one_dimension(k, N=10, M=0, t=1, period=0):
import numpy as np
import guan
h00 = np.zeros((4*N, 4*N), dtype=complex) # hopping in a unit cell
h01 = np.zeros((4*N, 4*N), dtype=complex) # hopping between unit cells
for i in range(N):
h00[i*4+0, i*4+0] = M
h00[i*4+1, i*4+1] = -M
h00[i*4+2, i*4+2] = M
h00[i*4+3, i*4+3] = -M
h00[i*4+0, i*4+1] = t
h00[i*4+1, i*4+0] = t
h00[i*4+1, i*4+2] = t
h00[i*4+2, i*4+1] = t
h00[i*4+2, i*4+3] = t
h00[i*4+3, i*4+2] = t
for i in range(N-1):
h00[i*4+3, (i+1)*4+0] = t
h00[(i+1)*4+0, i*4+3] = t
if period == 1:
h00[(N-1)*4+3, 0] = t
h00[0, (N-1)*4+3] = t
for i in range(N):
h01[i*4+1, i*4+0] = t
h01[i*4+2, i*4+3] = t
hamiltonian = guan.one_dimensional_fourier_transform(k, unit_cell=h00, hopping=h01)
return hamiltonian
hamiltonian_of_haldane_modelhamiltonian_of_haldane_model(k1, k2, M=2 / 3, t1=1, t2=1 / 3, phi='default', a='default')
Haldane模型的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
k1 | 必填 | |
k2 | 必填 | |
M | 2 / 3 | |
t1 | 1 | |
t2 | 1 / 3 | |
phi | 'default' | |
a | 'default' |
def hamiltonian_of_haldane_model(k1, k2, M=2/3, t1=1, t2=1/3, phi='default', a='default'):
import numpy as np
import cmath
import math
if phi == 'default':
phi=math.pi/4
if a == 'default':
a=1/math.sqrt(3)
h0 = np.zeros((2, 2), dtype=complex) # mass term
h1 = np.zeros((2, 2), dtype=complex) # nearest hopping
h2 = np.zeros((2, 2), dtype=complex) # next nearest hopping
h0[0, 0] = M
h0[1, 1] = -M
h1[1, 0] = t1*(cmath.exp(1j*k2*a)+cmath.exp(1j*math.sqrt(3)/2*k1*a-1j/2*k2*a)+cmath.exp(-1j*math.sqrt(3)/2*k1*a-1j/2*k2*a))
h1[0, 1] = h1[1, 0].conj()
h2[0, 0] = t2*cmath.exp(-1j*phi)*(cmath.exp(1j*math.sqrt(3)*k1*a)+cmath.exp(-1j*math.sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*math.sqrt(3)/2*k1*a-1j*3/2*k2*a))
h2[1, 1] = t2*cmath.exp(1j*phi)*(cmath.exp(1j*math.sqrt(3)*k1*a)+cmath.exp(-1j*math.sqrt(3)/2*k1*a+1j*3/2*k2*a)+cmath.exp(-1j*math.sqrt(3)/2*k1*a-1j*3/2*k2*a))
hamiltonian = h0 + h1 + h2 + h2.transpose().conj()
return hamiltonian
hamiltonian_of_haldane_model_in_quasi_one_dimensionhamiltonian_of_haldane_model_in_quasi_one_dimension(k, N=10, M=2 / 3, t1=1, t2=1 / 3, phi='default', period=0)
准一维Haldane模型条带的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
k | 必填 | |
N | 10 | |
M | 2 / 3 | |
t1 | 1 | |
t2 | 1 / 3 | |
phi | 'default' | |
period | 0 |
def hamiltonian_of_haldane_model_in_quasi_one_dimension(k, N=10, M=2/3, t1=1, t2=1/3, phi='default', period=0):
import numpy as np
import cmath
import math
if phi == 'default':
phi=math.pi/4
h00 = np.zeros((4*N, 4*N), dtype=complex) # hopping in a unit cell
h01 = np.zeros((4*N, 4*N), dtype=complex) # hopping between unit cells
for i in range(N):
h00[i*4+0, i*4+0] = M
h00[i*4+1, i*4+1] = -M
h00[i*4+2, i*4+2] = M
h00[i*4+3, i*4+3] = -M
h00[i*4+0, i*4+1] = t1
h00[i*4+1, i*4+0] = t1
h00[i*4+1, i*4+2] = t1
h00[i*4+2, i*4+1] = t1
h00[i*4+2, i*4+3] = t1
h00[i*4+3, i*4+2] = t1
h00[i*4+0, i*4+2] = t2*cmath.exp(-1j*phi)
h00[i*4+2, i*4+0] = h00[i*4+0, i*4+2].conj()
h00[i*4+1, i*4+3] = t2*cmath.exp(-1j*phi)
h00[i*4+3, i*4+1] = h00[i*4+1, i*4+3].conj()
for i in range(N-1):
h00[i*4+3, (i+1)*4+0] = t1
h00[(i+1)*4+0, i*4+3] = t1
h00[i*4+2, (i+1)*4+0] = t2*cmath.exp(1j*phi)
h00[(i+1)*4+0, i*4+2] = h00[i*4+2, (i+1)*4+0].conj()
h00[i*4+3, (i+1)*4+1] = t2*cmath.exp(1j*phi)
h00[(i+1)*4+1, i*4+3] = h00[i*4+3, (i+1)*4+1].conj()
if period == 1:
h00[(N-1)*4+3, 0] = t1
h00[0, (N-1)*4+3] = t1
h00[(N-1)*4+2, 0] = t2*cmath.exp(1j*phi)
h00[0, (N-1)*4+2] = h00[(N-1)*4+2, 0].conj()
h00[(N-1)*4+3, 1] = t2*cmath.exp(1j*phi)
h00[1, (N-1)*4+3] = h00[(N-1)*4+3, 1].conj()
for i in range(N):
h01[i*4+1, i*4+0] = t1
h01[i*4+2, i*4+3] = t1
h01[i*4+0, i*4+0] = t2*cmath.exp(1j*phi)
h01[i*4+1, i*4+1] = t2*cmath.exp(-1j*phi)
h01[i*4+2, i*4+2] = t2*cmath.exp(1j*phi)
h01[i*4+3, i*4+3] = t2*cmath.exp(-1j*phi)
h01[i*4+1, i*4+3] = t2*cmath.exp(1j*phi)
h01[i*4+2, i*4+0] = t2*cmath.exp(-1j*phi)
if i != 0:
h01[i*4+1, (i-1)*4+3] = t2*cmath.exp(1j*phi)
for i in range(N-1):
h01[i*4+2, (i+1)*4+0] = t2*cmath.exp(-1j*phi)
hamiltonian = h00 + h01*cmath.exp(1j*k) + h01.transpose().conj()*cmath.exp(-1j*k)
return hamiltonian
hamiltonian_of_one_QAH_modelhamiltonian_of_one_QAH_model(k1, k2, t1=1, t2=1, t3=0.5, m=-1)
一个量子反常霍尔效应的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
k1 | 必填 | |
k2 | 必填 | |
t1 | 1 | |
t2 | 1 | |
t3 | 0.5 | |
m | -1 |
def hamiltonian_of_one_QAH_model(k1, k2, t1=1, t2=1, t3=0.5, m=-1):
import numpy as np
import math
hamiltonian = np.zeros((2, 2), dtype=complex)
hamiltonian[0, 1] = 2*t1*math.cos(k1)-1j*2*t1*math.cos(k2)
hamiltonian[1, 0] = 2*t1*math.cos(k1)+1j*2*t1*math.cos(k2)
hamiltonian[0, 0] = m+2*t3*math.sin(k1)+2*t3*math.sin(k2)+2*t2*math.cos(k1+k2)
hamiltonian[1, 1] = -(m+2*t3*math.sin(k1)+2*t3*math.sin(k2)+2*t2*math.cos(k1+k2))
return hamiltonian
hamiltonian_of_bhz_modelhamiltonian_of_bhz_model(kx, ky, A=0.3645 / 5, B=-0.686 / 25, C=0, D=-0.512 / 25, M=-0.01)
BHZ模型的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
kx | 必填 | |
ky | 必填 | |
A | 0.3645 / 5 | |
B | -0.686 / 25 | |
C | 0 | |
D | -0.512 / 25 | |
M | -0.01 |
def hamiltonian_of_bhz_model(kx, ky, A=0.3645/5, B=-0.686/25, C=0, D=-0.512/25, M=-0.01):
import numpy as np
import math
hamiltonian = np.zeros((4, 4), dtype=complex)
varepsilon = C-2*D*(2-math.cos(kx)-math.cos(ky))
d3 = -2*B*(2-(M/2/B)-math.cos(kx)-math.cos(ky))
d1_d2 = A*(math.sin(kx)+1j*math.sin(ky))
hamiltonian[0, 0] = varepsilon+d3
hamiltonian[1, 1] = varepsilon-d3
hamiltonian[0, 1] = np.conj(d1_d2)
hamiltonian[1, 0] = d1_d2
hamiltonian[2, 2] = varepsilon+d3
hamiltonian[3, 3] = varepsilon-d3
hamiltonian[2, 3] = -d1_d2
hamiltonian[3, 2] = -np.conj(d1_d2)
return hamiltonian
hamiltonian_of_half_bhz_model_for_spin_uphamiltonian_of_half_bhz_model_for_spin_up(kx, ky, A=0.3645 / 5, B=-0.686 / 25, C=0, D=-0.512 / 25, M=-0.01)
半BHZ模型的哈密顿量(自旋向上)(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
kx | 必填 | |
ky | 必填 | |
A | 0.3645 / 5 | |
B | -0.686 / 25 | |
C | 0 | |
D | -0.512 / 25 | |
M | -0.01 |
def hamiltonian_of_half_bhz_model_for_spin_up(kx, ky, A=0.3645/5, B=-0.686/25, C=0, D=-0.512/25, M=-0.01):
import numpy as np
import math
hamiltonian = np.zeros((2, 2), dtype=complex)
varepsilon = C-2*D*(2-math.cos(kx)-math.cos(ky))
d3 = -2*B*(2-(M/2/B)-math.cos(kx)-math.cos(ky))
d1_d2 = A*(math.sin(kx)+1j*math.sin(ky))
hamiltonian[0, 0] = varepsilon+d3
hamiltonian[1, 1] = varepsilon-d3
hamiltonian[0, 1] = np.conj(d1_d2)
hamiltonian[1, 0] = d1_d2
return hamiltonian
hamiltonian_of_half_bhz_model_for_spin_downhamiltonian_of_half_bhz_model_for_spin_down(kx, ky, A=0.3645 / 5, B=-0.686 / 25, C=0, D=-0.512 / 25, M=-0.01)
半BHZ模型的哈密顿量(自旋向下)(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
kx | 必填 | |
ky | 必填 | |
A | 0.3645 / 5 | |
B | -0.686 / 25 | |
C | 0 | |
D | -0.512 / 25 | |
M | -0.01 |
def hamiltonian_of_half_bhz_model_for_spin_down(kx, ky, A=0.3645/5, B=-0.686/25, C=0, D=-0.512/25, M=-0.01):
import numpy as np
import math
hamiltonian = np.zeros((2, 2), dtype=complex)
varepsilon = C-2*D*(2-math.cos(kx)-math.cos(ky))
d3 = -2*B*(2-(M/2/B)-math.cos(kx)-math.cos(ky))
d1_d2 = A*(math.sin(kx)+1j*math.sin(ky))
hamiltonian[0, 0] = varepsilon+d3
hamiltonian[1, 1] = varepsilon-d3
hamiltonian[0, 1] = -d1_d2
hamiltonian[1, 0] = -np.conj(d1_d2)
return hamiltonian
hamiltonian_of_bbh_modelhamiltonian_of_bbh_model(kx, ky, gamma_x=0.5, gamma_y=0.5, lambda_x=1, lambda_y=1)
BBH模型的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
kx | 必填 | |
ky | 必填 | |
gamma_x | 0.5 | |
gamma_y | 0.5 | |
lambda_x | 1 | |
lambda_y | 1 |
def hamiltonian_of_bbh_model(kx, ky, gamma_x=0.5, gamma_y=0.5, lambda_x=1, lambda_y=1):
import numpy as np
import cmath
# label of atoms in a unit cell
# (2) —— (0)
# | |
# (1) —— (3)
hamiltonian = np.zeros((4, 4), dtype=complex)
hamiltonian[0, 2] = gamma_x+lambda_x*cmath.exp(1j*kx)
hamiltonian[1, 3] = gamma_x+lambda_x*cmath.exp(-1j*kx)
hamiltonian[0, 3] = gamma_y+lambda_y*cmath.exp(1j*ky)
hamiltonian[1, 2] = -gamma_y-lambda_y*cmath.exp(-1j*ky)
hamiltonian[2, 0] = np.conj(hamiltonian[0, 2])
hamiltonian[3, 1] = np.conj(hamiltonian[1, 3])
hamiltonian[3, 0] = np.conj(hamiltonian[0, 3])
hamiltonian[2, 1] = np.conj(hamiltonian[1, 2])
return hamiltonian
hamiltonian_of_kagome_latticehamiltonian_of_kagome_lattice(kx, ky, t=1)
Kagome模型的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
kx | 必填 | |
ky | 必填 | |
t | 1 |
def hamiltonian_of_kagome_lattice(kx, ky, t=1):
import numpy as np
import math
k1_dot_a1 = kx
k2_dot_a2 = kx/2+ky*math.sqrt(3)/2
k3_dot_a3 = -kx/2+ky*math.sqrt(3)/2
hamiltonian = np.zeros((3, 3), dtype=complex)
hamiltonian[0, 1] = 2*math.cos(k1_dot_a1)
hamiltonian[0, 2] = 2*math.cos(k2_dot_a2)
hamiltonian[1, 2] = 2*math.cos(k3_dot_a3)
hamiltonian = hamiltonian + hamiltonian.transpose().conj()
hamiltonian = -t*hamiltonian
return hamiltonian
hamiltonian_of_hyperhoneycomb_latticehamiltonian_of_hyperhoneycomb_lattice(kx, ky, kz, t=1, a=1)
超蜂窝晶格的哈密顿量(倒空间)
| 参数 | 类型 | 默认值 |
|---|---|---|
kx | 必填 | |
ky | 必填 | |
kz | 必填 | |
t | 1 | |
a | 1 |
def hamiltonian_of_hyperhoneycomb_lattice(kx, ky, kz, t=1, a=1):
import cmath
import numpy as np
hamiltonian = np.zeros((4, 4), dtype=complex)
fx = (t*cmath.exp(1j*np.sqrt(3)/2*kx*a)+t*cmath.exp(-1j*np.sqrt(3)/2*kx*a))*cmath.exp(1j*kz/2*a)
fy = (t*cmath.exp(1j*np.sqrt(3)/2*ky*a)+t*cmath.exp(-1j*np.sqrt(3)/2*ky*a))*cmath.exp(1j*kz/2*a)
fz = cmath.exp(1j*kz*a)
hamiltonian[0, 1] = fx
hamiltonian[1, 0] = np.conj(fx)
hamiltonian[2, 3] = fy
hamiltonian[3, 2] = np.conj(fy)
hamiltonian[1, 2] = fz
hamiltonian[2, 1] = np.conj(fz)
hamiltonian[3, 0] = fz
hamiltonian[0, 3] = np.conj(fz)
return hamiltonian
calculate_eigenvaluecalculate_eigenvalue(hamiltonian, hermitian=True)
计算哈密顿量的本征值
| 参数 | 类型 | 默认值 |
|---|---|---|
hamiltonian | 必填 | |
hermitian | True |
def calculate_eigenvalue(hamiltonian, hermitian=True):
import numpy as np
if np.array(hamiltonian).shape==():
eigenvalue = np.real(hamiltonian)
else:
if hermitian:
eigenvalue, eigenvector = np.linalg.eigh(hamiltonian)
else:
eigenvalue, eigenvector = np.linalg.eig(hamiltonian)
return eigenvalue
calculate_eigenvalue_with_one_parametercalculate_eigenvalue_with_one_parameter(x_array, hamiltonian_function, print_show=0)
输入哈密顿量函数(带一组参数),计算一组参数下的本征值,返回本征值向量组
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
hamiltonian_function | 必填 | |
print_show | 0 |
def calculate_eigenvalue_with_one_parameter(x_array, hamiltonian_function, print_show=0):
import numpy as np
dim_x = np.array(x_array).shape[0]
i0 = 0
if np.array(hamiltonian_function(0)).shape==():
eigenvalue_array = np.zeros((dim_x, 1))
for x0 in x_array:
hamiltonian = hamiltonian_function(x0)
eigenvalue_array[i0, 0] = np.real(hamiltonian)
i0 += 1
else:
dim = np.array(hamiltonian_function(0)).shape[0]
eigenvalue_array = np.zeros((dim_x, dim))
for x0 in x_array:
if print_show==1:
print(x0)
hamiltonian = hamiltonian_function(x0)
eigenvalue, eigenvector = np.linalg.eigh(hamiltonian)
eigenvalue_array[i0, :] = eigenvalue
i0 += 1
return eigenvalue_array
calculate_eigenvalue_with_two_parameterscalculate_eigenvalue_with_two_parameters(x_array, y_array, hamiltonian_function, print_show=0, print_show_more=0)
输入哈密顿量函数(带两组参数),计算两组参数下的本征值,返回本征值向量组
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
hamiltonian_function | 必填 | |
print_show | 0 | |
print_show_more | 0 |
def calculate_eigenvalue_with_two_parameters(x_array, y_array, hamiltonian_function, print_show=0, print_show_more=0):
import numpy as np
dim_x = np.array(x_array).shape[0]
dim_y = np.array(y_array).shape[0]
if np.array(hamiltonian_function(0,0)).shape==():
eigenvalue_array = np.zeros((dim_y, dim_x, 1))
i0 = 0
for y0 in y_array:
j0 = 0
for x0 in x_array:
hamiltonian = hamiltonian_function(x0, y0)
eigenvalue_array[i0, j0, 0] = np.real(hamiltonian)
j0 += 1
i0 += 1
else:
dim = np.array(hamiltonian_function(0, 0)).shape[0]
eigenvalue_array = np.zeros((dim_y, dim_x, dim))
i0 = 0
for y0 in y_array:
j0 = 0
if print_show==1:
print(y0)
for x0 in x_array:
if print_show_more==1:
print(x0)
hamiltonian = hamiltonian_function(x0, y0)
eigenvalue, eigenvector = np.linalg.eigh(hamiltonian)
eigenvalue_array[i0, j0, :] = eigenvalue
j0 += 1
i0 += 1
return eigenvalue_array
calculate_eigenvectorcalculate_eigenvector(hamiltonian, hermitian=True)
计算哈密顿量的本征矢
| 参数 | 类型 | 默认值 |
|---|---|---|
hamiltonian | 必填 | |
hermitian | True |
def calculate_eigenvector(hamiltonian, hermitian=True):
import numpy as np
if hermitian:
eigenvalue, eigenvector = np.linalg.eigh(hamiltonian)
else:
eigenvalue, eigenvector = np.linalg.eig(hamiltonian)
return eigenvector
schmidt_orthogonalizationschmidt_orthogonalization(eigenvector)
施密特正交化
| 参数 | 类型 | 默认值 |
|---|---|---|
eigenvector | 必填 |
def schmidt_orthogonalization(eigenvector):
import numpy as np
num = eigenvector.shape[1]
for i in range(num):
for i0 in range(i):
eigenvector[:, i] = eigenvector[:, i] - eigenvector[:, i0]*np.dot(eigenvector[:, i].transpose().conj(), eigenvector[:, i0])/(np.dot(eigenvector[:, i0].transpose().conj(),eigenvector[:, i0]))
eigenvector[:, i] = eigenvector[:, i]/np.linalg.norm(eigenvector[:, i])
return eigenvector
orthogonalization_with_qrorthogonalization_with_qr(eigenvector)
通过QR分解正交化
| 参数 | 类型 | 默认值 |
|---|---|---|
eigenvector | 必填 |
def orthogonalization_with_qr(eigenvector):
import numpy as np
Q, R = np.linalg.qr(eigenvector)
return Q
orthogonalization_with_svdorthogonalization_with_svd(eigenvector)
通过SVD正交化
| 参数 | 类型 | 默认值 |
|---|---|---|
eigenvector | 必填 |
def orthogonalization_with_svd(eigenvector):
import numpy as np
U, sigma, VT = np.linalg.svd(eigenvector)
return U
orthogonalization_with_scipy_linalg_orthorthogonalization_with_scipy_linalg_orth(eigenvector)
通过scipy.linalg.orth正交化
| 参数 | 类型 | 默认值 |
|---|---|---|
eigenvector | 必填 |
def orthogonalization_with_scipy_linalg_orth(eigenvector):
import scipy
Q = scipy.linalg.orth(eigenvector)
return Q
verify_orthogonalityverify_orthogonality(eigenvector)
验证是否正交
| 参数 | 类型 | 默认值 |
|---|---|---|
eigenvector | 必填 |
def verify_orthogonality(eigenvector):
import numpy as np
identity = np.eye(eigenvector.shape[1])
product = np.dot(eigenvector.transpose().conj(), eigenvector)
return np.allclose(product, identity)
find_vector_with_the_same_gauge_with_binary_searchfind_vector_with_the_same_gauge_with_binary_search(vector_target, vector_ref, show_error=1, show_times=0, show_phase=0, n_test=1000, precision=1e-06)
通过二分查找的方法获取和相邻波函数一样规范的波函数
| 参数 | 类型 | 默认值 |
|---|---|---|
vector_target | 必填 | |
vector_ref | 必填 | |
show_error | 1 | |
show_times | 0 | |
show_phase | 0 | |
n_test | 1000 | |
precision | 1e-06 |
def find_vector_with_the_same_gauge_with_binary_search(vector_target, vector_ref, show_error=1, show_times=0, show_phase=0, n_test=1000, precision=1e-6):
import numpy as np
import cmath
phase_1_pre = 0
phase_2_pre = np.pi
for i0 in range(n_test):
test_1 = np.sum(np.abs(vector_target*cmath.exp(1j*phase_1_pre) - vector_ref))
test_2 = np.sum(np.abs(vector_target*cmath.exp(1j*phase_2_pre) - vector_ref))
if test_1 < precision:
phase = phase_1_pre
if show_times==1:
print('Binary search times=', i0)
break
if i0 == n_test-1:
phase = phase_1_pre
if show_error==1:
print('Gauge not found with binary search times=', i0)
if test_1 < test_2:
if i0 == 0:
phase_1 = phase_1_pre-(phase_2_pre-phase_1_pre)/2
phase_2 = phase_1_pre+(phase_2_pre-phase_1_pre)/2
else:
phase_1 = phase_1_pre
phase_2 = phase_1_pre+(phase_2_pre-phase_1_pre)/2
else:
if i0 == 0:
phase_1 = phase_2_pre-(phase_2_pre-phase_1_pre)/2
phase_2 = phase_2_pre+(phase_2_pre-phase_1_pre)/2
else:
phase_1 = phase_2_pre-(phase_2_pre-phase_1_pre)/2
phase_2 = phase_2_pre
phase_1_pre = phase_1
phase_2_pre = phase_2
vector_target = vector_target*cmath.exp(1j*phase)
if show_phase==1:
print('Phase=', phase)
return vector_target
find_vector_with_fixed_gauge_by_making_one_component_realfind_vector_with_fixed_gauge_by_making_one_component_real(vector, index=None)
通过乘一个相反的相位角,实现波函数的一个非零分量为实数,从而得到固定规范的波函数
| 参数 | 类型 | 默认值 |
|---|---|---|
vector | 必填 | |
index | None |
def find_vector_with_fixed_gauge_by_making_one_component_real(vector, index=None):
import numpy as np
import cmath
vector = np.array(vector)
if index == None:
index = np.argmax(np.abs(vector))
angle = cmath.phase(vector[index])
vector = vector*cmath.exp(-1j*angle)
return vector
find_vector_array_with_fixed_gauge_by_making_one_component_realfind_vector_array_with_fixed_gauge_by_making_one_component_real(vector_array)
通过乘一个相反的相位角,实现波函数的一个非零分量为实数,从而得到固定规范的波函数(在一组波函数中选取最大的那个分量)
| 参数 | 类型 | 默认值 |
|---|---|---|
vector_array | 必填 |
调用了:guan.find_vector_with_fixed_gauge_by_making_one_component_real
def find_vector_array_with_fixed_gauge_by_making_one_component_real(vector_array):
import numpy as np
import guan
vector_sum = 0
Num_k = np.array(vector_array).shape[0]
for i0 in range(Num_k):
vector_sum += np.abs(vector_array[i0])
index = np.argmax(np.abs(vector_sum))
for i0 in range(Num_k):
vector_array[i0] = guan.find_vector_with_fixed_gauge_by_making_one_component_real(vector_array[i0], index=index)
return vector_array
loop_find_vector_with_fixed_gauge_by_making_one_component_realloop_find_vector_with_fixed_gauge_by_making_one_component_real(vector, precision=0.005, index=None)
循环查找规范使得波函数的一个非零分量为实数,得到固定规范的波函数
| 参数 | 类型 | 默认值 |
|---|---|---|
vector | 必填 | |
precision | 0.005 | |
index | None |
def loop_find_vector_with_fixed_gauge_by_making_one_component_real(vector, precision=0.005, index=None):
import numpy as np
import cmath
vector = np.array(vector)
if index == None:
index = np.argmax(np.abs(vector))
sign_pre = np.sign(np.imag(vector[index]))
for phase in np.arange(0, 2*np.pi, precision):
sign = np.sign(np.imag(vector[index]*cmath.exp(1j*phase)))
if np.abs(np.imag(vector[index]*cmath.exp(1j*phase))) < 1e-9 or sign == -sign_pre:
break
sign_pre = sign
vector = vector*cmath.exp(1j*phase)
if np.real(vector[index]) < 0:
vector = -vector
return vector
loop_find_vector_array_with_fixed_gauge_by_making_one_component_realloop_find_vector_array_with_fixed_gauge_by_making_one_component_real(vector_array, precision=0.005)
循环查找规范使得波函数的一个非零分量为实数,得到固定规范的波函数(在一组波函数中选取最大的那个分量)
| 参数 | 类型 | 默认值 |
|---|---|---|
vector_array | 必填 | |
precision | 0.005 |
调用了:guan.loop_find_vector_with_fixed_gauge_by_making_one_component_real
def loop_find_vector_array_with_fixed_gauge_by_making_one_component_real(vector_array, precision=0.005):
import numpy as np
import guan
vector_sum = 0
Num_k = np.array(vector_array).shape[0]
for i0 in range(Num_k):
vector_sum += np.abs(vector_array[i0])
index = np.argmax(np.abs(vector_sum))
for i0 in range(Num_k):
vector_array[i0] = guan.loop_find_vector_with_fixed_gauge_by_making_one_component_real(vector_array[i0], precision=precision, index=index)
return vector_array
rotation_of_degenerate_vectorsrotation_of_degenerate_vectors(vector1, vector2, index1=None, index2=None, precision=0.01, criterion=0.01, show_theta=0)
旋转两个简并的波函数(说明:参数比较多,算法效率不高)
| 参数 | 类型 | 默认值 |
|---|---|---|
vector1 | 必填 | |
vector2 | 必填 | |
index1 | None | |
index2 | None | |
precision | 0.01 | |
criterion | 0.01 | |
show_theta | 0 |
def rotation_of_degenerate_vectors(vector1, vector2, index1=None, index2=None, precision=0.01, criterion=0.01, show_theta=0):
import numpy as np
import math
import cmath
vector1 = np.array(vector1)
vector2 = np.array(vector2)
if index1 == None:
index1 = np.argmax(np.abs(vector1))
if index2 == None:
index2 = np.argmax(np.abs(vector2))
if np.abs(vector1[index2])>criterion or np.abs(vector2[index1])>criterion:
for theta in np.arange(0, 2*math.pi, precision):
if show_theta==1:
print(theta)
for phi1 in np.arange(0, 2*math.pi, precision):
for phi2 in np.arange(0, 2*math.pi, precision):
vector1_test = cmath.exp(1j*phi1)*vector1*math.cos(theta)+cmath.exp(1j*phi2)*vector2*math.sin(theta)
vector2_test = -cmath.exp(-1j*phi2)*vector1*math.sin(theta)+cmath.exp(-1j*phi1)*vector2*math.cos(theta)
if np.abs(vector1_test[index2])<criterion and np.abs(vector2_test[index1])<criterion:
vector1 = vector1_test
vector2 = vector2_test
break
if np.abs(vector1_test[index2])<criterion and np.abs(vector2_test[index1])<criterion:
break
if np.abs(vector1_test[index2])<criterion and np.abs(vector2_test[index1])<criterion:
break
return vector1, vector2
rotation_of_degenerate_vectors_arrayrotation_of_degenerate_vectors_array(vector1_array, vector2_array, precision=0.01, criterion=0.01, show_theta=0)
旋转两个简并的波函数向量组(说明:参数比较多,算法效率不高)
| 参数 | 类型 | 默认值 |
|---|---|---|
vector1_array | 必填 | |
vector2_array | 必填 | |
precision | 0.01 | |
criterion | 0.01 | |
show_theta | 0 |
调用了:guan.rotation_of_degenerate_vectors
def rotation_of_degenerate_vectors_array(vector1_array, vector2_array, precision=0.01, criterion=0.01, show_theta=0):
import numpy as np
import guan
Num_k = np.array(vector1_array).shape[0]
vector1_sum = 0
for i0 in range(Num_k):
vector1_sum += np.abs(vector1_array[i0])
index1 = np.argmax(np.abs(vector1_sum))
vector2_sum = 0
for i0 in range(Num_k):
vector2_sum += np.abs(vector2_array[i0])
index2 = np.argmax(np.abs(vector2_sum))
for i0 in range(Num_k):
vector1_array[i0], vector2_array[i0] = guan.rotation_of_degenerate_vectors(vector1=vector1_array[i0], vector2=vector2_array[i0], index1=index1, index2=index2, precision=precision, criterion=criterion, show_theta=show_theta)
return vector1_array, vector2_array
find_close_values_in_one_arrayfind_close_values_in_one_array(array, precision=0.01)
在一组数据中找到数值相近的数
| 参数 | 类型 | 默认值 |
|---|---|---|
array | 必填 | |
precision | 0.01 |
def find_close_values_in_one_array(array, precision=1e-2):
new_array = []
i0 = 0
for a1 in array:
j0 = 0
for a2 in array:
if j0>i0 and abs(a1-a2)<precision:
new_array.append([a1, a2])
j0 +=1
i0 += 1
return new_array
find_degenerate_pointsfind_degenerate_points(k_array, eigenvalue_array, precision=0.01)
寻找能带的简并点
| 参数 | 类型 | 默认值 |
|---|---|---|
k_array | 必填 | |
eigenvalue_array | 必填 | |
precision | 0.01 |
调用了:guan.find_close_values_in_one_array
def find_degenerate_points(k_array, eigenvalue_array, precision=1e-2):
import guan
degenerate_k_array = []
degenerate_eigenvalue_array = []
i0 = 0
for k in k_array:
degenerate_points = guan.find_close_values_in_one_array(eigenvalue_array[i0], precision=precision)
if len(degenerate_points) != 0:
degenerate_k_array.append(k)
degenerate_eigenvalue_array.append(degenerate_points)
i0 += 1
return degenerate_k_array, degenerate_eigenvalue_array
green_functiongreen_function(fermi_energy, hamiltonian, broadening, self_energy=0)
输入哈密顿量,得到格林函数
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
hamiltonian | 必填 | |
broadening | 必填 | |
self_energy | 0 |
def green_function(fermi_energy, hamiltonian, broadening, self_energy=0):
import numpy as np
if np.array(hamiltonian).shape==():
dim = 1
else:
dim = np.array(hamiltonian).shape[0]
green = np.linalg.inv((fermi_energy+broadening*1j)*np.eye(dim)-hamiltonian-self_energy)
return green
green_function_nn_ngreen_function_nn_n(fermi_energy, h00, h01, green_nn_n_minus, broadening, self_energy=0)
在Dyson方程中的一个中间格林函数G_{nn}^{n}
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
green_nn_n_minus | 必填 | |
broadening | 必填 | |
self_energy | 0 |
def green_function_nn_n(fermi_energy, h00, h01, green_nn_n_minus, broadening, self_energy=0):
import numpy as np
h01 = np.array(h01)
if np.array(h00).shape==():
dim = 1
else:
dim = np.array(h00).shape[0]
green_nn_n = np.linalg.inv((fermi_energy+broadening*1j)*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), green_nn_n_minus), h01)-self_energy)
return green_nn_n
green_function_in_ngreen_function_in_n(green_in_n_minus, h01, green_nn_n)
在Dyson方程中的一个中间格林函数G_{in}^{n}
| 参数 | 类型 | 默认值 |
|---|---|---|
green_in_n_minus | 必填 | |
h01 | 必填 | |
green_nn_n | 必填 |
def green_function_in_n(green_in_n_minus, h01, green_nn_n):
import numpy as np
green_in_n = np.dot(np.dot(green_in_n_minus, h01), green_nn_n)
return green_in_n
green_function_ni_ngreen_function_ni_n(green_nn_n, h01, green_ni_n_minus)
在Dyson方程中的一个中间格林函数G_{ni}^{n}
| 参数 | 类型 | 默认值 |
|---|---|---|
green_nn_n | 必填 | |
h01 | 必填 | |
green_ni_n_minus | 必填 |
def green_function_ni_n(green_nn_n, h01, green_ni_n_minus):
import numpy as np
h01 = np.array(h01)
green_ni_n = np.dot(np.dot(green_nn_n, h01.transpose().conj()), green_ni_n_minus)
return green_ni_n
green_function_ii_ngreen_function_ii_n(green_ii_n_minus, green_in_n_minus, h01, green_nn_n, green_ni_n_minus)
在Dyson方程中的一个中间格林函数G_{ii}^{n}
| 参数 | 类型 | 默认值 |
|---|---|---|
green_ii_n_minus | 必填 | |
green_in_n_minus | 必填 | |
h01 | 必填 | |
green_nn_n | 必填 | |
green_ni_n_minus | 必填 |
def green_function_ii_n(green_ii_n_minus, green_in_n_minus, h01, green_nn_n, green_ni_n_minus):
import numpy as np
green_ii_n = green_ii_n_minus+np.dot(np.dot(np.dot(np.dot(green_in_n_minus, h01), green_nn_n), h01.transpose().conj()),green_ni_n_minus)
return green_ii_n
transfer_matrixtransfer_matrix(fermi_energy, h00, h01)
计算转移矩阵(该矩阵可以用来计算表面格林函数)
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 |
def transfer_matrix(fermi_energy, h00, h01):
import numpy as np
h01 = np.array(h01)
if np.array(h00).shape==():
dim = 1
else:
dim = np.array(h00).shape[0]
transfer = np.zeros((2*dim, 2*dim), dtype=complex)
if dim == 1:
transfer[0:dim, 0:dim] = np.dot(1/h01, fermi_energy*np.identity(dim)-h00)
transfer[0:dim, dim:2*dim] = np.dot(-1/h01, h01.transpose().conj())
else:
transfer[0:dim, 0:dim] = np.dot(np.linalg.inv(h01), fermi_energy*np.identity(dim)-h00)
transfer[0:dim, dim:2*dim] = np.dot(-1*np.linalg.inv(h01), h01.transpose().conj())
transfer[dim:2*dim, 0:dim] = np.identity(dim)
transfer[dim:2*dim, dim:2*dim] = 0
return transfer
surface_green_function_of_leadsurface_green_function_of_lead(fermi_energy, h00, h01)
计算电极的表面格林函数
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 |
def surface_green_function_of_lead(fermi_energy, h00, h01):
import numpy as np
h01 = np.array(h01)
if np.array(h00).shape==():
dim = 1
else:
dim = np.array(h00).shape[0]
fermi_energy = fermi_energy+1e-9*1j
transfer = transfer_matrix(fermi_energy, h00, h01)
eigenvalue, eigenvector = np.linalg.eig(transfer)
ind = np.argsort(np.abs(eigenvalue))
temp = np.zeros((2*dim, 2*dim), dtype=complex)
i0 = 0
for ind0 in ind:
temp[:, i0] = eigenvector[:, ind0]
i0 += 1
s1 = temp[dim:2*dim, 0:dim]
s2 = temp[0:dim, 0:dim]
s3 = temp[dim:2*dim, dim:2*dim]
s4 = temp[0:dim, dim:2*dim]
right_lead_surface = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01, s2), np.linalg.inv(s1)))
left_lead_surface = np.linalg.inv(fermi_energy*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), s3), np.linalg.inv(s4)))
return right_lead_surface, left_lead_surface
self_energy_of_leadself_energy_of_lead(fermi_energy, h00, h01)
计算电极的自能(基于Dyson方程的小矩阵形式)
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 |
调用了:guan.surface_green_function_of_lead
def self_energy_of_lead(fermi_energy, h00, h01):
import numpy as np
import guan
h01 = np.array(h01)
right_lead_surface, left_lead_surface = guan.surface_green_function_of_lead(fermi_energy, h00, h01)
right_self_energy = np.dot(np.dot(h01, right_lead_surface), h01.transpose().conj())
left_self_energy = np.dot(np.dot(h01.transpose().conj(), left_lead_surface), h01)
gamma_right = (right_self_energy - right_self_energy.transpose().conj())*1j
gamma_left = (left_self_energy - left_self_energy.transpose().conj())*1j
return right_self_energy, left_self_energy, gamma_right, gamma_left
self_energy_of_lead_with_h_LC_and_h_CRself_energy_of_lead_with_h_LC_and_h_CR(fermi_energy, h00, h01, h_LC, h_CR)
计算电极的自能(基于中心区整体的大矩阵形式)
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
h_LC | 必填 | |
h_CR | 必填 |
调用了:guan.surface_green_function_of_lead
def self_energy_of_lead_with_h_LC_and_h_CR(fermi_energy, h00, h01, h_LC, h_CR):
import numpy as np
import guan
h_LC = np.array(h_LC)
h_CR = np.array(h_CR)
right_lead_surface, left_lead_surface = guan.surface_green_function_of_lead(fermi_energy, h00, h01)
right_self_energy = np.dot(np.dot(h_CR, right_lead_surface), h_CR.transpose().conj())
left_self_energy = np.dot(np.dot(h_LC.transpose().conj(), left_lead_surface), h_LC)
gamma_right = (right_self_energy - right_self_energy.transpose().conj())*1j
gamma_left = (left_self_energy - left_self_energy.transpose().conj())*1j
return right_self_energy, left_self_energy, gamma_right, gamma_left
self_energy_of_lead_with_h_lead_to_centerself_energy_of_lead_with_h_lead_to_center(fermi_energy, h00, h01, h_lead_to_center)
计算电极的自能(基于中心区整体的大矩阵形式,可适用于多端电导的计算)
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
h_lead_to_center | 必填 |
调用了:guan.surface_green_function_of_lead
def self_energy_of_lead_with_h_lead_to_center(fermi_energy, h00, h01, h_lead_to_center):
import numpy as np
import guan
h_lead_to_center = np.array(h_lead_to_center)
right_lead_surface, left_lead_surface = guan.surface_green_function_of_lead(fermi_energy, h00, h01)
self_energy = np.dot(np.dot(h_lead_to_center.transpose().conj(), right_lead_surface), h_lead_to_center)
gamma = (self_energy - self_energy.transpose().conj())*1j
return self_energy, gamma
green_function_with_leadsgreen_function_with_leads(fermi_energy, h00, h01, h_LC, h_CR, center_hamiltonian)
计算考虑电极自能后的中心区的格林函数
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
h_LC | 必填 | |
h_CR | 必填 | |
center_hamiltonian | 必填 |
调用了:guan.self_energy_of_lead_with_h_LC_and_h_CR
def green_function_with_leads(fermi_energy, h00, h01, h_LC, h_CR, center_hamiltonian):
import numpy as np
import guan
dim = np.array(center_hamiltonian).shape[0]
right_self_energy, left_self_energy, gamma_right, gamma_left = guan.self_energy_of_lead_with_h_LC_and_h_CR(fermi_energy, h00, h01, h_LC, h_CR)
green = np.linalg.inv(fermi_energy*np.identity(dim)-center_hamiltonian-left_self_energy-right_self_energy)
return green, gamma_right, gamma_left
electron_correlation_function_green_n_for_local_currentelectron_correlation_function_green_n_for_local_current(fermi_energy, h00, h01, h_LC, h_CR, center_hamiltonian)
计算用于计算局域电流的格林函数G_n
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
h_LC | 必填 | |
h_CR | 必填 | |
center_hamiltonian | 必填 |
调用了:guan.self_energy_of_lead_with_h_LC_and_h_CR, guan.green_function
def electron_correlation_function_green_n_for_local_current(fermi_energy, h00, h01, h_LC, h_CR, center_hamiltonian):
import numpy as np
import guan
right_self_energy, left_self_energy, gamma_right, gamma_left = guan.self_energy_of_lead_with_h_LC_and_h_CR(fermi_energy, h00, h01, h_LC, h_CR)
green = guan.green_function(fermi_energy, center_hamiltonian, broadening=0, self_energy=left_self_energy+right_self_energy)
G_n = np.imag(np.dot(np.dot(green, gamma_left), green.transpose().conj()))
return G_n
total_density_of_statestotal_density_of_states(fermi_energy, hamiltonian, broadening=0.01)
计算体系的总态密度
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
hamiltonian | 必填 | |
broadening | 0.01 |
def total_density_of_states(fermi_energy, hamiltonian, broadening=0.01):
import numpy as np
import math
import guan
green = guan.green_function(fermi_energy, hamiltonian, broadening)
total_dos = -np.trace(np.imag(green))/math.pi
return total_dos
total_density_of_states_with_fermi_energy_arraytotal_density_of_states_with_fermi_energy_array(fermi_energy_array, hamiltonian, broadening=0.01, print_show=0)
对于不同费米能,计算体系的总态密度
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy_array | 必填 | |
hamiltonian | 必填 | |
broadening | 0.01 | |
print_show | 0 |
调用了:guan.total_density_of_states
def total_density_of_states_with_fermi_energy_array(fermi_energy_array, hamiltonian, broadening=0.01, print_show=0):
import numpy as np
import guan
dim = np.array(fermi_energy_array).shape[0]
total_dos_array = np.zeros(dim)
i0 = 0
for fermi_energy in fermi_energy_array:
if print_show == 1:
print(fermi_energy)
total_dos_array[i0] = guan.total_density_of_states(fermi_energy, hamiltonian, broadening)
i0 += 1
return total_dos_array
local_density_of_states_for_square_latticelocal_density_of_states_for_square_lattice(fermi_energy, hamiltonian, N1, N2, internal_degree=1, broadening=0.01)
计算方格子的局域态密度(其中,哈密顿量的维度为:dim_hamiltonian = N1*N2*internal_degree)
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
hamiltonian | 必填 | |
N1 | 必填 | |
N2 | 必填 | |
internal_degree | 1 | |
broadening | 0.01 |
def local_density_of_states_for_square_lattice(fermi_energy, hamiltonian, N1, N2, internal_degree=1, broadening=0.01):
import numpy as np
import math
import guan
green = guan.green_function(fermi_energy, hamiltonian, broadening)
local_dos = np.zeros((N2, N1))
for i1 in range(N1):
for i2 in range(N2):
for i in range(internal_degree):
local_dos[i2, i1] = local_dos[i2, i1]-np.imag(green[i1*N2*internal_degree+i2*internal_degree+i, i1*N2*internal_degree+i2*internal_degree+i])/math.pi
return local_dos
local_density_of_states_for_cubic_latticelocal_density_of_states_for_cubic_lattice(fermi_energy, hamiltonian, N1, N2, N3, internal_degree=1, broadening=0.01)
计算立方格子的局域态密度(其中,哈密顿量的维度为:dim_hamiltonian = N1*N2*N3*internal_degree)
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
hamiltonian | 必填 | |
N1 | 必填 | |
N2 | 必填 | |
N3 | 必填 | |
internal_degree | 1 | |
broadening | 0.01 |
def local_density_of_states_for_cubic_lattice(fermi_energy, hamiltonian, N1, N2, N3, internal_degree=1, broadening=0.01):
import numpy as np
import math
import guan
green = guan.green_function(fermi_energy, hamiltonian, broadening)
local_dos = np.zeros((N3, N2, N1))
for i1 in range(N1):
for i2 in range(N2):
for i3 in range(N3):
for i in range(internal_degree):
local_dos[i3, i2, i1] = local_dos[i3, i2, i1]-np.imag(green[i1*N2*N3*internal_degree+i2*N3*internal_degree+i3*internal_degree+i, i1*N2*N3*internal_degree+i2*N3*internal_degree+i3*internal_degree+i])/math.pi
return local_dos
local_density_of_states_for_square_lattice_using_dyson_equationlocal_density_of_states_for_square_lattice_using_dyson_equation(fermi_energy, h00, h01, N2, N1, internal_degree=1, broadening=0.01)
使用Dyson方程,计算方格子的局域态密度(其中,h00的维度为:dim_h00 = N2*internal_degree)
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
N2 | 必填 | |
N1 | 必填 | |
internal_degree | 1 | |
broadening | 0.01 |
调用了:guan.green_function, guan.green_function_nn_n, guan.green_function_ii_n, guan.green_function_in_n, guan.green_function_ni_n
def local_density_of_states_for_square_lattice_using_dyson_equation(fermi_energy, h00, h01, N2, N1, internal_degree=1, broadening=0.01):
import numpy as np
import math
import guan
local_dos = np.zeros((N2, N1))
green_11_1 = guan.green_function(fermi_energy, h00, broadening)
for i1 in range(N1):
green_nn_n_minus = green_11_1
green_in_n_minus = green_11_1
green_ni_n_minus = green_11_1
green_ii_n_minus = green_11_1
for _ in range(i1):
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n_minus, broadening)
green_nn_n_minus = green_nn_n
if i1!=0:
green_in_n_minus = green_nn_n
green_ni_n_minus = green_nn_n
green_ii_n_minus = green_nn_n
for _ in range(N1-1-i1):
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n_minus, broadening)
green_nn_n_minus = green_nn_n
green_ii_n = guan.green_function_ii_n(green_ii_n_minus, green_in_n_minus, h01, green_nn_n, green_ni_n_minus)
green_ii_n_minus = green_ii_n
green_in_n = guan.green_function_in_n(green_in_n_minus, h01, green_nn_n)
green_in_n_minus = green_in_n
green_ni_n = guan.green_function_ni_n(green_nn_n, h01, green_ni_n_minus)
green_ni_n_minus = green_ni_n
for i2 in range(N2):
for i in range(internal_degree):
local_dos[i2, i1] = local_dos[i2, i1] - np.imag(green_ii_n_minus[i2*internal_degree+i, i2*internal_degree+i])/math.pi
return local_dos
local_density_of_states_for_square_lattice_using_dyson_equation_with_second_methodlocal_density_of_states_for_square_lattice_using_dyson_equation_with_second_method(fermi_energy, h00, h01, N2, N1, internal_degree=1, broadening=0.01)
使用Dyson方程,计算方格子的局域态密度,方法二(其中,h00的维度为:dim_h00 = N2*internal_degree)
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
N2 | 必填 | |
N1 | 必填 | |
internal_degree | 1 | |
broadening | 0.01 |
调用了:guan.green_function, guan.green_function_nn_n
def local_density_of_states_for_square_lattice_using_dyson_equation_with_second_method(fermi_energy, h00, h01, N2, N1, internal_degree=1, broadening=0.01):
import numpy as np
import math
import guan
h01 = np.array(h01)
if np.array(h00).shape==():
dim = 1
else:
dim = np.array(h00).shape[0]
local_dos = np.zeros((N2, N1))
green_11_1 = guan.green_function(fermi_energy, h00, broadening)
for i1 in range(N1):
green_nn_n_right_minus = green_11_1
green_nn_n_left_minus = green_11_1
if i1!=0:
for _ in range(i1-1):
green_nn_n_right = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n_right_minus, broadening)
green_nn_n_right_minus = green_nn_n_right
if i1!=N1-1:
for _ in range(N1-i1-2):
G_nn_n_left = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n_left_minus, broadening)
green_nn_n_left_minus = G_nn_n_left
if i1==0:
green_ii_n = np.linalg.inv((fermi_energy+broadening*1j)*np.identity(dim)-h00-np.dot(np.dot(h01, green_nn_n_left_minus), h01.transpose().conj()))
elif i1!=0 and i1!=N1-1:
green_ii_n = np.linalg.inv((fermi_energy+broadening*1j)*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), green_nn_n_right_minus), h01)-np.dot(np.dot(h01, green_nn_n_left_minus), h01.transpose().conj()))
elif i1==N1-1:
green_ii_n = np.linalg.inv((fermi_energy+broadening*1j)*np.identity(dim)-h00-np.dot(np.dot(h01.transpose().conj(), green_nn_n_right_minus), h01))
for i2 in range(N2):
for i in range(internal_degree):
local_dos[i2, i1] = local_dos[i2, i1] - np.imag(green_ii_n[i2*internal_degree+i, i2*internal_degree+i])/math.pi
return local_dos
local_density_of_states_for_cubic_lattice_using_dyson_equationlocal_density_of_states_for_cubic_lattice_using_dyson_equation(fermi_energy, h00, h01, N3, N2, N1, internal_degree=1, broadening=0.01)
使用Dyson方程,计算立方格子的局域态密度(其中,h00的维度为:dim_h00 = N2*N3*internal_degree)
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
N3 | 必填 | |
N2 | 必填 | |
N1 | 必填 | |
internal_degree | 1 | |
broadening | 0.01 |
调用了:guan.green_function, guan.green_function_nn_n, guan.green_function_ii_n, guan.green_function_in_n, guan.green_function_ni_n
def local_density_of_states_for_cubic_lattice_using_dyson_equation(fermi_energy, h00, h01, N3, N2, N1, internal_degree=1, broadening=0.01):
import numpy as np
import math
import guan
local_dos = np.zeros((N3, N2, N1))
green_11_1 = guan.green_function(fermi_energy, h00, broadening)
for i1 in range(N1):
green_nn_n_minus = green_11_1
green_in_n_minus = green_11_1
green_ni_n_minus = green_11_1
green_ii_n_minus = green_11_1
for _ in range(i1):
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n_minus, broadening)
green_nn_n_minus = green_nn_n
if i1!=0:
green_in_n_minus = green_nn_n
green_ni_n_minus = green_nn_n
green_ii_n_minus = green_nn_n
for _ in range(N1-1-i1):
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n_minus, broadening)
green_nn_n_minus = green_nn_n
green_ii_n = guan.green_function_ii_n(green_ii_n_minus, green_in_n_minus, h01, green_nn_n, green_ni_n_minus)
green_ii_n_minus = green_ii_n
green_in_n = guan.green_function_in_n(green_in_n_minus, h01, green_nn_n)
green_in_n_minus = green_in_n
green_ni_n = guan.green_function_ni_n(green_nn_n, h01, green_ni_n_minus)
green_ni_n_minus = green_ni_n
for i2 in range(N2):
for i3 in range(N3):
for i in range(internal_degree):
local_dos[i3, i2, i1] = local_dos[i3, i2, i1] -np.imag(green_ii_n_minus[i2*N3*internal_degree+i3*internal_degree+i, i2*N3*internal_degree+i3*internal_degree+i])/math.pi
return local_dos
local_density_of_states_for_square_lattice_with_self_energy_using_dyson_equationlocal_density_of_states_for_square_lattice_with_self_energy_using_dyson_equation(fermi_energy, h00, h01, N2, N1, right_self_energy, left_self_energy, internal_degree=1, broadening=0.01)
使用Dyson方程,计算方格子条带(考虑了电极自能)的局域态密度(其中,h00的维度为:dim_h00 = N2*internal_degree)
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
N2 | 必填 | |
N1 | 必填 | |
right_self_energy | 必填 | |
left_self_energy | 必填 | |
internal_degree | 1 | |
broadening | 0.01 |
调用了:guan.green_function, guan.green_function_nn_n, guan.green_function_ii_n, guan.green_function_in_n, guan.green_function_ni_n
def local_density_of_states_for_square_lattice_with_self_energy_using_dyson_equation(fermi_energy, h00, h01, N2, N1, right_self_energy, left_self_energy, internal_degree=1, broadening=0.01):
import numpy as np
import math
import guan
local_dos = np.zeros((N2, N1))
green_11_1 = guan.green_function(fermi_energy, h00+left_self_energy, broadening)
for i1 in range(N1):
green_nn_n_minus = green_11_1
green_in_n_minus = green_11_1
green_ni_n_minus = green_11_1
green_ii_n_minus = green_11_1
for i2_0 in range(i1):
if i2_0 == N1-1-1:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00+right_self_energy, h01, green_nn_n_minus, broadening)
else:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n_minus, broadening)
green_nn_n_minus = green_nn_n
if i1!=0:
green_in_n_minus = green_nn_n
green_ni_n_minus = green_nn_n
green_ii_n_minus = green_nn_n
for size_0 in range(N1-1-i1):
if size_0 == N1-1-i1-1:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00+right_self_energy, h01, green_nn_n_minus, broadening)
else:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n_minus, broadening)
green_nn_n_minus = green_nn_n
green_ii_n = guan.green_function_ii_n(green_ii_n_minus, green_in_n_minus, h01, green_nn_n, green_ni_n_minus)
green_ii_n_minus = green_ii_n
green_in_n = guan.green_function_in_n(green_in_n_minus, h01, green_nn_n)
green_in_n_minus = green_in_n
green_ni_n = guan.green_function_ni_n(green_nn_n, h01, green_ni_n_minus)
green_ni_n_minus = green_ni_n
for i2 in range(N2):
for i in range(internal_degree):
local_dos[i2, i1] = local_dos[i2, i1] - np.imag(green_ii_n_minus[i2*internal_degree+i, i2*internal_degree+i])/math.pi
return local_dos
calculate_conductancecalculate_conductance(fermi_energy, h00, h01, length=100)
计算电导
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
length | 100 |
调用了:guan.self_energy_of_lead, guan.green_function, guan.green_function_nn_n, guan.green_function_in_n
def calculate_conductance(fermi_energy, h00, h01, length=100):
import numpy as np
import copy
import guan
right_self_energy, left_self_energy, gamma_right, gamma_left = guan.self_energy_of_lead(fermi_energy, h00, h01)
for ix in range(length):
if ix == 0:
green_nn_n = guan.green_function(fermi_energy, h00, broadening=0, self_energy=left_self_energy)
green_0n_n = copy.deepcopy(green_nn_n)
elif ix != length-1:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n, broadening=0)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
else:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n, broadening=0, self_energy=right_self_energy)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
dim = np.array(h00).shape[0]
if dim == 1:
conductance = np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj())
if conductance.shape == ():
pass
else:
conductance = conductance[0][0]
else:
conductance = np.trace(np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj()))
return conductance
calculate_conductance_with_fermi_energy_arraycalculate_conductance_with_fermi_energy_array(fermi_energy_array, h00, h01, length=100, print_show=0)
计算不同费米能下的电导
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy_array | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
length | 100 | |
print_show | 0 |
调用了:guan.calculate_conductance
def calculate_conductance_with_fermi_energy_array(fermi_energy_array, h00, h01, length=100, print_show=0):
import numpy as np
import guan
dim = np.array(fermi_energy_array).shape[0]
conductance_array = np.zeros(dim)
i0 = 0
for fermi_energy in fermi_energy_array:
conductance_array[i0] = np.real(guan.calculate_conductance(fermi_energy, h00, h01, length))
if print_show == 1:
print(fermi_energy, conductance_array[i0])
i0 += 1
return conductance_array
calculate_conductance_with_barriercalculate_conductance_with_barrier(fermi_energy, h00, h01, length=100, barrier_length=20, barrier_potential=1)
计算在势垒散射下的电导
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
length | 100 | |
barrier_length | 20 | |
barrier_potential | 1 |
调用了:guan.self_energy_of_lead, guan.green_function, guan.green_function_nn_n, guan.green_function_in_n
def calculate_conductance_with_barrier(fermi_energy, h00, h01, length=100, barrier_length=20, barrier_potential=1):
import numpy as np
import copy
import guan
right_self_energy, left_self_energy, gamma_right, gamma_left = guan.self_energy_of_lead(fermi_energy, h00, h01)
dim = np.array(h00).shape[0]
for ix in range(length):
if ix == 0:
green_nn_n = guan.green_function(fermi_energy, h00, broadening=0, self_energy=left_self_energy)
green_0n_n = copy.deepcopy(green_nn_n)
elif int(length/2-barrier_length/2)<=ix<int(length/2+barrier_length/2):
green_nn_n = guan.green_function_nn_n(fermi_energy, h00+barrier_potential*np.identity(dim), h01, green_nn_n, broadening=0)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
elif ix != length-1:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n, broadening=0)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
else:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n, broadening=0, self_energy=right_self_energy)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
if dim == 1:
conductance = np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj())
if conductance.shape == ():
pass
else:
conductance = conductance[0][0]
else:
conductance = np.trace(np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj()))
return conductance
calculate_conductance_with_disordercalculate_conductance_with_disorder(fermi_energy, h00, h01, disorder_intensity=2.0, disorder_concentration=1.0, length=100, calculation_times=1)
计算在无序散射下的电导
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
disorder_intensity | 2.0 | |
disorder_concentration | 1.0 | |
length | 100 | |
calculation_times | 1 |
调用了:guan.self_energy_of_lead, guan.green_function, guan.green_function_nn_n, guan.green_function_in_n
def calculate_conductance_with_disorder(fermi_energy, h00, h01, disorder_intensity=2.0, disorder_concentration=1.0, length=100, calculation_times=1):
import numpy as np
import copy
import guan
right_self_energy, left_self_energy, gamma_right, gamma_left = guan.self_energy_of_lead(fermi_energy, h00, h01)
dim = np.array(h00).shape[0]
conductance_averaged = 0
for times in range(calculation_times):
for ix in range(length+2):
disorder = np.zeros((dim, dim))
for dim0 in range(dim):
if np.random.uniform(0, 1)<=disorder_concentration:
disorder[dim0, dim0] = np.random.uniform(-disorder_intensity, disorder_intensity)
if ix == 0:
green_nn_n = guan.green_function(fermi_energy, h00, broadening=0, self_energy=left_self_energy)
green_0n_n = copy.deepcopy(green_nn_n)
elif ix != length+1:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00+disorder, h01, green_nn_n, broadening=0)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
else:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n, broadening=0, self_energy=right_self_energy)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
if dim == 1:
conductance = np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj())
if conductance.shape == ():
pass
else:
conductance = conductance[0][0]
else:
conductance = np.trace(np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj()))
conductance_averaged += conductance
conductance_averaged = conductance_averaged/calculation_times
return conductance_averaged
calculate_conductance_with_disorder_arraycalculate_conductance_with_disorder_array(fermi_energy, h00, h01, disorder_array, length=100)
计算在无序散射下的电导(需要输入无序数组)
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
disorder_array | 必填 | |
length | 100 |
调用了:guan.self_energy_of_lead, guan.green_function, guan.green_function_nn_n, guan.green_function_in_n
def calculate_conductance_with_disorder_array(fermi_energy, h00, h01, disorder_array, length=100):
import numpy as np
import copy
import guan
right_self_energy, left_self_energy, gamma_right, gamma_left = guan.self_energy_of_lead(fermi_energy, h00, h01)
dim = np.array(h00).shape[0]
i0 = 0
for ix in range(length+2):
if ix == 0:
green_nn_n = guan.green_function(fermi_energy, h00, broadening=0, self_energy=left_self_energy)
green_0n_n = copy.deepcopy(green_nn_n)
elif ix != length+1:
disorder = np.diag(disorder_array[i0*dim:(i0+1)*dim])
i0 += 1
green_nn_n = guan.green_function_nn_n(fermi_energy, h00+disorder, h01, green_nn_n, broadening=0)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
else:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n, broadening=0, self_energy=right_self_energy)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
if dim == 1:
conductance = np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj())
if conductance.shape == ():
pass
else:
conductance = conductance[0][0]
else:
conductance = np.trace(np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj()))
return conductance
calculate_conductance_with_slice_disordercalculate_conductance_with_slice_disorder(fermi_energy, h00, h01, disorder_intensity=2.0, disorder_concentration=1.0, length=100)
计算在无序垂直切片的散射下的电导
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
disorder_intensity | 2.0 | |
disorder_concentration | 1.0 | |
length | 100 |
调用了:guan.self_energy_of_lead, guan.green_function, guan.green_function_nn_n, guan.green_function_in_n
def calculate_conductance_with_slice_disorder(fermi_energy, h00, h01, disorder_intensity=2.0, disorder_concentration=1.0, length=100):
import numpy as np
import copy
import guan
right_self_energy, left_self_energy, gamma_right, gamma_left = guan.self_energy_of_lead(fermi_energy, h00, h01)
dim = np.array(h00).shape[0]
for ix in range(length+2):
disorder = np.zeros((dim, dim))
if np.random.uniform(0, 1)<=disorder_concentration:
disorder = np.random.uniform(-disorder_intensity, disorder_intensity)*np.eye(dim)
if ix == 0:
green_nn_n = guan.green_function(fermi_energy, h00, broadening=0, self_energy=left_self_energy)
green_0n_n = copy.deepcopy(green_nn_n)
elif ix != length+1:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00+disorder, h01, green_nn_n, broadening=0)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
else:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n, broadening=0, self_energy=right_self_energy)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
if dim == 1:
conductance = np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj())
if conductance.shape == ():
pass
else:
conductance = conductance[0][0]
else:
conductance = np.trace(np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj()))
return conductance
calculate_conductance_with_disorder_inside_unit_cell_which_keeps_translational_symmetrycalculate_conductance_with_disorder_inside_unit_cell_which_keeps_translational_symmetry(fermi_energy, h00, h01, disorder_intensity=2.0, disorder_concentration=1.0, length=100)
计算在无序水平切片的散射下的电导
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
disorder_intensity | 2.0 | |
disorder_concentration | 1.0 | |
length | 100 |
调用了:guan.self_energy_of_lead, guan.green_function, guan.green_function_nn_n, guan.green_function_in_n
def calculate_conductance_with_disorder_inside_unit_cell_which_keeps_translational_symmetry(fermi_energy, h00, h01, disorder_intensity=2.0, disorder_concentration=1.0, length=100):
import numpy as np
import copy
import guan
right_self_energy, left_self_energy, gamma_right, gamma_left = guan.self_energy_of_lead(fermi_energy, h00, h01)
dim = np.array(h00).shape[0]
disorder = np.zeros((dim, dim))
for dim0 in range(dim):
if np.random.uniform(0, 1)<=disorder_concentration:
disorder[dim0, dim0] = np.random.uniform(-disorder_intensity, disorder_intensity)
for ix in range(length+2):
if ix == 0:
green_nn_n = guan.green_function(fermi_energy, h00, broadening=0, self_energy=left_self_energy)
green_0n_n = copy.deepcopy(green_nn_n)
elif ix != length+1:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00+disorder, h01, green_nn_n, broadening=0)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
else:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n, broadening=0, self_energy=right_self_energy)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
if dim == 1:
conductance = np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj())
if conductance.shape == ():
pass
else:
conductance = conductance[0][0]
else:
conductance = np.trace(np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj()))
return conductance
calculate_conductance_with_random_vacancycalculate_conductance_with_random_vacancy(fermi_energy, h00, h01, vacancy_concentration=0.5, vacancy_potential=1000000000.0, length=100)
计算在随机空位的散射下的电导
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
vacancy_concentration | 0.5 | |
vacancy_potential | 1000000000.0 | |
length | 100 |
调用了:guan.self_energy_of_lead, guan.green_function, guan.green_function_nn_n, guan.green_function_in_n
def calculate_conductance_with_random_vacancy(fermi_energy, h00, h01, vacancy_concentration=0.5, vacancy_potential=1e9, length=100):
import numpy as np
import copy
import guan
right_self_energy, left_self_energy, gamma_right, gamma_left = guan.self_energy_of_lead(fermi_energy, h00, h01)
dim = np.array(h00).shape[0]
for ix in range(length+2):
random_vacancy = np.zeros((dim, dim))
for dim0 in range(dim):
if np.random.uniform(0, 1)<=vacancy_concentration:
random_vacancy[dim0, dim0] = vacancy_potential
if ix == 0:
green_nn_n = guan.green_function(fermi_energy, h00, broadening=0, self_energy=left_self_energy)
green_0n_n = copy.deepcopy(green_nn_n)
elif ix != length+1:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00+random_vacancy, h01, green_nn_n, broadening=0)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
else:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n, broadening=0, self_energy=right_self_energy)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
if dim == 1:
conductance = np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj())
if conductance.shape == ():
pass
else:
conductance = conductance[0][0]
else:
conductance = np.trace(np.dot(np.dot(np.dot(gamma_left, green_0n_n), gamma_right), green_0n_n.transpose().conj()))
return conductance
calculate_conductance_with_disorder_intensity_arraycalculate_conductance_with_disorder_intensity_array(fermi_energy, h00, h01, disorder_intensity_array, disorder_concentration=1.0, length=100, calculation_times=1, print_show=0)
计算在不同无序散射强度下的电导
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
disorder_intensity_array | 必填 | |
disorder_concentration | 1.0 | |
length | 100 | |
calculation_times | 1 | |
print_show | 0 |
调用了:guan.calculate_conductance_with_disorder
def calculate_conductance_with_disorder_intensity_array(fermi_energy, h00, h01, disorder_intensity_array, disorder_concentration=1.0, length=100, calculation_times=1, print_show=0):
import numpy as np
import guan
dim = np.array(disorder_intensity_array).shape[0]
conductance_array = np.zeros(dim)
i0 = 0
for disorder_intensity in disorder_intensity_array:
for times in range(calculation_times):
conductance_array[i0] = conductance_array[i0]+np.real(guan.calculate_conductance_with_disorder(fermi_energy, h00, h01, disorder_intensity=disorder_intensity, disorder_concentration=disorder_concentration, length=length))
if print_show == 1:
print(disorder_intensity, conductance_array[i0]/calculation_times)
i0 += 1
conductance_array = conductance_array/calculation_times
return conductance_array
calculate_conductance_with_disorder_concentration_arraycalculate_conductance_with_disorder_concentration_array(fermi_energy, h00, h01, disorder_concentration_array, disorder_intensity=2.0, length=100, calculation_times=1, print_show=0)
计算在不同无序浓度下的电导
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
disorder_concentration_array | 必填 | |
disorder_intensity | 2.0 | |
length | 100 | |
calculation_times | 1 | |
print_show | 0 |
调用了:guan.calculate_conductance_with_disorder
def calculate_conductance_with_disorder_concentration_array(fermi_energy, h00, h01, disorder_concentration_array, disorder_intensity=2.0, length=100, calculation_times=1, print_show=0):
import numpy as np
import guan
dim = np.array(disorder_concentration_array).shape[0]
conductance_array = np.zeros(dim)
i0 = 0
for disorder_concentration in disorder_concentration_array:
for times in range(calculation_times):
conductance_array[i0] = conductance_array[i0]+np.real(guan.calculate_conductance_with_disorder(fermi_energy, h00, h01, disorder_intensity=disorder_intensity, disorder_concentration=disorder_concentration, length=length))
if print_show == 1:
print(disorder_concentration, conductance_array[i0]/calculation_times)
i0 += 1
conductance_array = conductance_array/calculation_times
return conductance_array
calculate_conductance_with_scattering_length_arraycalculate_conductance_with_scattering_length_array(fermi_energy, h00, h01, length_array, disorder_intensity=2.0, disorder_concentration=1.0, calculation_times=1, print_show=0)
计算在不同无序散射长度下的电导
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
length_array | 必填 | |
disorder_intensity | 2.0 | |
disorder_concentration | 1.0 | |
calculation_times | 1 | |
print_show | 0 |
调用了:guan.calculate_conductance_with_disorder
def calculate_conductance_with_scattering_length_array(fermi_energy, h00, h01, length_array, disorder_intensity=2.0, disorder_concentration=1.0, calculation_times=1, print_show=0):
import numpy as np
import guan
dim = np.array(length_array).shape[0]
conductance_array = np.zeros(dim)
i0 = 0
for length in length_array:
for times in range(calculation_times):
conductance_array[i0] = conductance_array[i0]+np.real(guan.calculate_conductance_with_disorder(fermi_energy, h00, h01, disorder_intensity=disorder_intensity, disorder_concentration=disorder_concentration, length=length))
if print_show == 1:
print(length, conductance_array[i0]/calculation_times)
i0 += 1
conductance_array = conductance_array/calculation_times
return conductance_array
get_gamma_array_and_green_for_six_terminal_transmissionget_gamma_array_and_green_for_six_terminal_transmission(fermi_energy, h00_for_lead_4, h01_for_lead_4, h00_for_lead_2, h01_for_lead_2, center_hamiltonian, width=10, length=50, internal_degree=1, moving_step_of_leads=10)
计算得到Gamma矩阵和格林函数,用于计算六端口的量子输运
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00_for_lead_4 | 必填 | |
h01_for_lead_4 | 必填 | |
h00_for_lead_2 | 必填 | |
h01_for_lead_2 | 必填 | |
center_hamiltonian | 必填 | |
width | 10 | |
length | 50 | |
internal_degree | 1 | |
moving_step_of_leads | 10 |
调用了:guan.self_energy_of_lead_with_h_lead_to_center
def get_gamma_array_and_green_for_six_terminal_transmission(fermi_energy, h00_for_lead_4, h01_for_lead_4, h00_for_lead_2, h01_for_lead_2, center_hamiltonian, width=10, length=50, internal_degree=1, moving_step_of_leads=10):
import numpy as np
import guan
# ---------------- Geometry ----------------
# lead2 lead3
# lead1(L) lead4(R)
# lead6 lead5
h00_for_lead_1 = h00_for_lead_4
h00_for_lead_2 = h00_for_lead_2
h00_for_lead_3 = h00_for_lead_2
h00_for_lead_5 = h00_for_lead_2
h00_for_lead_6 = h00_for_lead_2
h00_for_lead_4 = h00_for_lead_4
h01_for_lead_1 = h01_for_lead_4.transpose().conj()
h01_for_lead_2 = h01_for_lead_2
h01_for_lead_3 = h01_for_lead_2
h01_for_lead_4 = h01_for_lead_4
h01_for_lead_5 = h01_for_lead_2.transpose().conj()
h01_for_lead_6 = h01_for_lead_2.transpose().conj()
h_lead1_to_center = np.zeros((internal_degree*width, internal_degree*width*length), dtype=complex)
h_lead2_to_center = np.zeros((internal_degree*width, internal_degree*width*length), dtype=complex)
h_lead3_to_center = np.zeros((internal_degree*width, internal_degree*width*length), dtype=complex)
h_lead4_to_center = np.zeros((internal_degree*width, internal_degree*width*length), dtype=complex)
h_lead5_to_center = np.zeros((internal_degree*width, internal_degree*width*length), dtype=complex)
h_lead6_to_center = np.zeros((internal_degree*width, internal_degree*width*length), dtype=complex)
move = moving_step_of_leads # the step of leads 2,3,6,5 moving to center
h_lead1_to_center[0:internal_degree*width, 0:internal_degree*width] = h01_for_lead_1.transpose().conj()
h_lead4_to_center[0:internal_degree*width, internal_degree*width*(length-1):internal_degree*width*length] = h01_for_lead_4.transpose().conj()
for i0 in range(width):
begin_index = internal_degree*i0+0
end_index = internal_degree*i0+internal_degree
h_lead2_to_center[begin_index:end_index, internal_degree*(width*(move+i0)+(width-1))+0:internal_degree*(width*(move+i0)+(width-1))+internal_degree] = h01_for_lead_2.transpose().conj()[begin_index:end_index, begin_index:end_index]
h_lead3_to_center[begin_index:end_index, internal_degree*(width*(length-move-1-i0)+(width-1))+0:internal_degree*(width*(length-move-1-i0)+(width-1))+internal_degree] = h01_for_lead_3.transpose().conj()[begin_index:end_index, begin_index:end_index]
h_lead5_to_center[begin_index:end_index, internal_degree*(width*(length-move-1-i0)+0)+0:internal_degree*(width*(length-move-1-i0)+0)+internal_degree] = h01_for_lead_5.transpose().conj()[begin_index:end_index, begin_index:end_index]
h_lead6_to_center[begin_index:end_index, internal_degree*(width*(i0+move)+0)+0:internal_degree*(width*(i0+move)+0)+internal_degree] = h01_for_lead_6.transpose().conj()[begin_index:end_index, begin_index:end_index]
self_energy1, gamma1 = guan.self_energy_of_lead_with_h_lead_to_center(fermi_energy, h00_for_lead_1, h01_for_lead_1, h_lead1_to_center)
self_energy2, gamma2 = guan.self_energy_of_lead_with_h_lead_to_center(fermi_energy, h00_for_lead_2, h01_for_lead_1, h_lead2_to_center)
self_energy3, gamma3 = guan.self_energy_of_lead_with_h_lead_to_center(fermi_energy, h00_for_lead_3, h01_for_lead_1, h_lead3_to_center)
self_energy4, gamma4 = guan.self_energy_of_lead_with_h_lead_to_center(fermi_energy, h00_for_lead_4, h01_for_lead_1, h_lead4_to_center)
self_energy5, gamma5 = guan.self_energy_of_lead_with_h_lead_to_center(fermi_energy, h00_for_lead_5, h01_for_lead_1, h_lead5_to_center)
self_energy6, gamma6 = guan.self_energy_of_lead_with_h_lead_to_center(fermi_energy, h00_for_lead_6, h01_for_lead_1, h_lead6_to_center)
gamma_array = [gamma1, gamma2, gamma3, gamma4, gamma5, gamma6]
green = np.linalg.inv(fermi_energy*np.eye(internal_degree*width*length)-center_hamiltonian-self_energy1-self_energy2-self_energy3-self_energy4-self_energy5-self_energy6)
return gamma_array, green
Geometry
calculate_six_terminal_transmission_matrixcalculate_six_terminal_transmission_matrix(fermi_energy, h00_for_lead_4, h01_for_lead_4, h00_for_lead_2, h01_for_lead_2, center_hamiltonian, width=10, length=50, internal_degree=1, moving_step_of_leads=10)
计算六端口的透射矩阵
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00_for_lead_4 | 必填 | |
h01_for_lead_4 | 必填 | |
h00_for_lead_2 | 必填 | |
h01_for_lead_2 | 必填 | |
center_hamiltonian | 必填 | |
width | 10 | |
length | 50 | |
internal_degree | 1 | |
moving_step_of_leads | 10 |
调用了:guan.get_gamma_array_and_green_for_six_terminal_transmission, guan.calculate_conductance
def calculate_six_terminal_transmission_matrix(fermi_energy, h00_for_lead_4, h01_for_lead_4, h00_for_lead_2, h01_for_lead_2, center_hamiltonian, width=10, length=50, internal_degree=1, moving_step_of_leads=10):
import numpy as np
import guan
gamma_array, green = guan.get_gamma_array_and_green_for_six_terminal_transmission(fermi_energy, h00_for_lead_4, h01_for_lead_4, h00_for_lead_2, h01_for_lead_2, center_hamiltonian, width, length, internal_degree, moving_step_of_leads)
transmission_matrix = np.zeros((6, 6), dtype=complex)
channel_lead_4 = guan.calculate_conductance(fermi_energy, h00_for_lead_4, h01_for_lead_4, length=3)
channel_lead_2 = guan.calculate_conductance(fermi_energy, h00_for_lead_2, h01_for_lead_2, length=3)
for i0 in range(6):
for j0 in range(6):
if j0!=i0:
transmission_matrix[i0, j0] = np.trace(np.dot(np.dot(np.dot(gamma_array[i0], green), gamma_array[j0]), green.transpose().conj()))
for i0 in range(6):
if i0 == 0 or i0 == 3:
transmission_matrix[i0, i0] = channel_lead_4
else:
transmission_matrix[i0, i0] = channel_lead_2
for i0 in range(6):
for j0 in range(6):
if j0!=i0:
transmission_matrix[i0, i0] = transmission_matrix[i0, i0]-transmission_matrix[i0, j0]
transmission_matrix = np.real(transmission_matrix)
return transmission_matrix
Geometry
calculate_six_terminal_transmissions_from_lead_1calculate_six_terminal_transmissions_from_lead_1(fermi_energy, h00_for_lead_4, h01_for_lead_4, h00_for_lead_2, h01_for_lead_2, center_hamiltonian, width=10, length=50, internal_degree=1, moving_step_of_leads=10)
计算从电极1出发的透射系数
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00_for_lead_4 | 必填 | |
h01_for_lead_4 | 必填 | |
h00_for_lead_2 | 必填 | |
h01_for_lead_2 | 必填 | |
center_hamiltonian | 必填 | |
width | 10 | |
length | 50 | |
internal_degree | 1 | |
moving_step_of_leads | 10 |
调用了:guan.get_gamma_array_and_green_for_six_terminal_transmission
def calculate_six_terminal_transmissions_from_lead_1(fermi_energy, h00_for_lead_4, h01_for_lead_4, h00_for_lead_2, h01_for_lead_2, center_hamiltonian, width=10, length=50, internal_degree=1, moving_step_of_leads=10):
import numpy as np
import guan
gamma_array, green = guan.get_gamma_array_and_green_for_six_terminal_transmission(fermi_energy, h00_for_lead_4, h01_for_lead_4, h00_for_lead_2, h01_for_lead_2, center_hamiltonian, width, length, internal_degree, moving_step_of_leads)
transmission_12 = np.real(np.trace(np.dot(np.dot(np.dot(gamma_array[0], green), gamma_array[1]), green.transpose().conj())))
transmission_13 = np.real(np.trace(np.dot(np.dot(np.dot(gamma_array[0], green), gamma_array[2]), green.transpose().conj())))
transmission_14 = np.real(np.trace(np.dot(np.dot(np.dot(gamma_array[0], green), gamma_array[3]), green.transpose().conj())))
transmission_15 = np.real(np.trace(np.dot(np.dot(np.dot(gamma_array[0], green), gamma_array[4]), green.transpose().conj())))
transmission_16 = np.real(np.trace(np.dot(np.dot(np.dot(gamma_array[0], green), gamma_array[5]), green.transpose().conj())))
return transmission_12, transmission_13, transmission_14, transmission_15, transmission_16
Geometry
if_active_channelif_active_channel(k_of_channel)
通过动量k的虚部,判断通道为传播通道还是衰减通道
| 参数 | 类型 | 默认值 |
|---|---|---|
k_of_channel | 必填 |
def if_active_channel(k_of_channel):
import numpy as np
if np.abs(np.imag(k_of_channel))<1e-6:
if_active = 1
else:
if_active = 0
return if_active
Geometry
get_k_and_velocity_of_channelget_k_and_velocity_of_channel(fermi_energy, h00, h01)
获取通道的动量和速度,用于计算散射矩阵
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 |
def get_k_and_velocity_of_channel(fermi_energy, h00, h01):
import numpy as np
import math
import copy
import guan
if np.array(h00).shape==():
dim = 1
else:
dim = np.array(h00).shape[0]
transfer = guan.transfer_matrix(fermi_energy, h00, h01)
eigenvalue, eigenvector = np.linalg.eig(transfer)
k_of_channel = np.log(eigenvalue)/1j
ind = np.argsort(np.real(k_of_channel))
k_of_channel = np.sort(k_of_channel)
temp = np.zeros((2*dim, 2*dim), dtype=complex)
temp2 = np.zeros((2*dim), dtype=complex)
i0 = 0
for ind0 in ind:
temp[:, i0] = eigenvector[:, ind0]
temp2[i0] = eigenvalue[ind0]
i0 += 1
eigenvalue = copy.deepcopy(temp2)
temp = temp[0:dim, :]
factor = np.zeros(2*dim)
for dim0 in range(dim):
factor = factor+np.square(np.abs(temp[dim0, :]))
for dim0 in range(2*dim):
temp[:, dim0] = temp[:, dim0]/math.sqrt(factor[dim0])
velocity_of_channel = np.zeros((2*dim), dtype=complex)
for dim0 in range(2*dim):
velocity_of_channel[dim0] = eigenvalue[dim0]*np.dot(np.dot(temp[0:dim, :].transpose().conj(), h01),temp[0:dim, :])[dim0, dim0]
velocity_of_channel = -2*np.imag(velocity_of_channel)
eigenvector = copy.deepcopy(temp)
return k_of_channel, velocity_of_channel, eigenvalue, eigenvector
Geometry
get_classified_k_velocity_u_and_fget_classified_k_velocity_u_and_f(fermi_energy, h00, h01)
获取分类后的动量和速度,以及U和F,用于计算散射矩阵
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 |
调用了:guan.get_k_and_velocity_of_channel, guan.if_active_channel
def get_classified_k_velocity_u_and_f(fermi_energy, h00, h01):
import numpy as np
import guan
if np.array(h00).shape==():
dim = 1
else:
dim = np.array(h00).shape[0]
k_of_channel, velocity_of_channel, eigenvalue, eigenvector = guan.get_k_and_velocity_of_channel(fermi_energy, h00, h01)
ind_right_active = 0; ind_right_evanescent = 0; ind_left_active = 0; ind_left_evanescent = 0
k_right = np.zeros(dim, dtype=complex); k_left = np.zeros(dim, dtype=complex)
velocity_right = np.zeros(dim, dtype=complex); velocity_left = np.zeros(dim, dtype=complex)
lambda_right = np.zeros(dim, dtype=complex); lambda_left = np.zeros(dim, dtype=complex)
u_right = np.zeros((dim, dim), dtype=complex); u_left = np.zeros((dim, dim), dtype=complex)
for dim0 in range(2*dim):
if_active = guan.if_active_channel(k_of_channel[dim0])
if guan.if_active_channel(k_of_channel[dim0]) == 1:
direction = np.sign(velocity_of_channel[dim0])
else:
direction = np.sign(np.imag(k_of_channel[dim0]))
if direction == 1:
if if_active == 1: # right-moving active channel
k_right[ind_right_active] = k_of_channel[dim0]
velocity_right[ind_right_active] = velocity_of_channel[dim0]
lambda_right[ind_right_active] = eigenvalue[dim0]
u_right[:, ind_right_active] = eigenvector[:, dim0]
ind_right_active += 1
else: # right-moving evanescent channel
k_right[dim-1-ind_right_evanescent] = k_of_channel[dim0]
velocity_right[dim-1-ind_right_evanescent] = velocity_of_channel[dim0]
lambda_right[dim-1-ind_right_evanescent] = eigenvalue[dim0]
u_right[:, dim-1-ind_right_evanescent] = eigenvector[:, dim0]
ind_right_evanescent += 1
else:
if if_active == 1: # left-moving active channel
k_left[ind_left_active] = k_of_channel[dim0]
velocity_left[ind_left_active] = velocity_of_channel[dim0]
lambda_left[ind_left_active] = eigenvalue[dim0]
u_left[:, ind_left_active] = eigenvector[:, dim0]
ind_left_active += 1
else: # left-moving evanescent channel
k_left[dim-1-ind_left_evanescent] = k_of_channel[dim0]
velocity_left[dim-1-ind_left_evanescent] = velocity_of_channel[dim0]
lambda_left[dim-1-ind_left_evanescent] = eigenvalue[dim0]
u_left[:, dim-1-ind_left_evanescent] = eigenvector[:, dim0]
ind_left_evanescent += 1
lambda_matrix_right = np.diag(lambda_right)
lambda_matrix_left = np.diag(lambda_left)
f_right = np.dot(np.dot(u_right, lambda_matrix_right), np.linalg.inv(u_right))
f_left = np.dot(np.dot(u_left, lambda_matrix_left), np.linalg.inv(u_left))
return k_right, k_left, velocity_right, velocity_left, f_right, f_left, u_right, u_left, ind_right_active
Geometry
calculate_scattering_matrixcalculate_scattering_matrix(fermi_energy, h00, h01, length=100)
计算散射矩阵
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
length | 100 |
调用了:guan.get_classified_k_velocity_u_and_f, guan.green_function, guan.green_function_nn_n, guan.green_function_ii_n, guan.green_function_in_n, guan.green_function_ni_n, guan.if_active_channel
def calculate_scattering_matrix(fermi_energy, h00, h01, length=100):
import numpy as np
import math
import copy
import guan
h01 = np.array(h01)
if np.array(h00).shape==():
dim = 1
else:
dim = np.array(h00).shape[0]
k_right, k_left, velocity_right, velocity_left, f_right, f_left, u_right, u_left, ind_right_active = guan.get_classified_k_velocity_u_and_f(fermi_energy, h00, h01)
right_self_energy = np.dot(h01, f_right)
left_self_energy = np.dot(h01.transpose().conj(), np.linalg.inv(f_left))
for i0 in range(length):
if i0 == 0:
green_nn_n = guan.green_function(fermi_energy, h00, broadening=0, self_energy=left_self_energy)
green_00_n = copy.deepcopy(green_nn_n)
green_0n_n = copy.deepcopy(green_nn_n)
green_n0_n = copy.deepcopy(green_nn_n)
elif i0 != length-1:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n, broadening=0)
else:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n, broadening=0, self_energy=right_self_energy)
green_00_n = guan.green_function_ii_n(green_00_n, green_0n_n, h01, green_nn_n, green_n0_n)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
green_n0_n = guan.green_function_ni_n(green_nn_n, h01, green_n0_n)
temp = np.dot(h01.transpose().conj(), np.linalg.inv(f_right)-np.linalg.inv(f_left))
transmission_matrix = np.dot(np.dot(np.linalg.inv(u_right), np.dot(green_n0_n, temp)), u_right)
reflection_matrix = np.dot(np.dot(np.linalg.inv(u_left), np.dot(green_00_n, temp)-np.identity(dim)), u_right)
for dim0 in range(dim):
for dim1 in range(dim):
if_active = guan.if_active_channel(k_right[dim0])*guan.if_active_channel(k_right[dim1])
if if_active == 1:
transmission_matrix[dim0, dim1] = math.sqrt(np.abs(velocity_right[dim0]/velocity_right[dim1])) * transmission_matrix[dim0, dim1]
reflection_matrix[dim0, dim1] = math.sqrt(np.abs(velocity_left[dim0]/velocity_right[dim1]))*reflection_matrix[dim0, dim1]
else:
transmission_matrix[dim0, dim1] = 0
reflection_matrix[dim0, dim1] = 0
sum_of_tran_refl_array = np.sum(np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active])), axis=0)+np.sum(np.square(np.abs(reflection_matrix[0:ind_right_active, 0:ind_right_active])), axis=0)
for sum_of_tran_refl in sum_of_tran_refl_array:
if sum_of_tran_refl > 1.001:
print('Error Alert: scattering matrix is not normalized!')
return transmission_matrix, reflection_matrix, k_right, k_left, velocity_right, velocity_left, ind_right_active
Geometry
information_of_scattering_matrixinformation_of_scattering_matrix(transmission_matrix, reflection_matrix, k_right, k_left, velocity_right, velocity_left, ind_right_active)
从散射矩阵中,获取散射矩阵的信息
| 参数 | 类型 | 默认值 |
|---|---|---|
transmission_matrix | 必填 | |
reflection_matrix | 必填 | |
k_right | 必填 | |
k_left | 必填 | |
velocity_right | 必填 | |
velocity_left | 必填 | |
ind_right_active | 必填 |
def information_of_scattering_matrix(transmission_matrix, reflection_matrix, k_right, k_left, velocity_right, velocity_left, ind_right_active):
import numpy as np
if np.array(transmission_matrix).shape==():
dim = 1
else:
dim = np.array(transmission_matrix).shape[0]
number_of_active_channels = ind_right_active
number_of_evanescent_channels = dim-ind_right_active
k_of_right_moving_active_channels = np.real(k_right[0:ind_right_active])
k_of_left_moving_active_channels = np.real(k_left[0:ind_right_active])
velocity_of_right_moving_active_channels = np.real(velocity_right[0:ind_right_active])
velocity_of_left_moving_active_channels = np.real(velocity_left[0:ind_right_active])
transmission_matrix_for_active_channels = np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active]))
reflection_matrix_for_active_channels = np.square(np.abs(reflection_matrix[0:ind_right_active, 0:ind_right_active]))
total_transmission_of_channels = np.sum(np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active])), axis=0)
total_conductance = np.sum(np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active])))
total_reflection_of_channels = np.sum(np.square(np.abs(reflection_matrix[0:ind_right_active, 0:ind_right_active])), axis=0)
sum_of_transmission_and_reflection_of_channels = np.sum(np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active])), axis=0) + np.sum(np.square(np.abs(reflection_matrix[0:ind_right_active, 0:ind_right_active])), axis=0)
return number_of_active_channels, number_of_evanescent_channels, k_of_right_moving_active_channels, k_of_left_moving_active_channels, velocity_of_right_moving_active_channels, velocity_of_left_moving_active_channels, transmission_matrix_for_active_channels, reflection_matrix_for_active_channels, total_transmission_of_channels, total_conductance, total_reflection_of_channels, sum_of_transmission_and_reflection_of_channels
Geometry
calculate_scattering_matrix_and_get_informationcalculate_scattering_matrix_and_get_information(fermi_energy, h00, h01, length=100)
已知h00和h01,计算散射矩阵并获得散射矩阵的信息
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
length | 100 |
调用了:guan.calculate_scattering_matrix, guan.information_of_scattering_matrix
def calculate_scattering_matrix_and_get_information(fermi_energy, h00, h01, length=100):
import guan
transmission_matrix, reflection_matrix, k_right, k_left, velocity_right, velocity_left, ind_right_active = guan.calculate_scattering_matrix(fermi_energy, h00, h01, length=length)
number_of_active_channels, number_of_evanescent_channels, k_of_right_moving_active_channels, k_of_left_moving_active_channels, velocity_of_right_moving_active_channels, velocity_of_left_moving_active_channels, transmission_matrix_for_active_channels, reflection_matrix_for_active_channels, total_transmission_of_channels, total_conductance, total_reflection_of_channels, sum_of_transmission_and_reflection_of_channels = guan.information_of_scattering_matrix(transmission_matrix, reflection_matrix, k_right, k_left, velocity_right, velocity_left, ind_right_active)
return number_of_active_channels, number_of_evanescent_channels, k_of_right_moving_active_channels, k_of_left_moving_active_channels, velocity_of_right_moving_active_channels, velocity_of_left_moving_active_channels, transmission_matrix_for_active_channels, reflection_matrix_for_active_channels, total_transmission_of_channels, total_conductance, total_reflection_of_channels, sum_of_transmission_and_reflection_of_channels
Geometry
print_or_write_scattering_matrix_with_information_of_scattering_matrixprint_or_write_scattering_matrix_with_information_of_scattering_matrix(number_of_active_channels, number_of_evanescent_channels, k_of_right_moving_active_channels, k_of_left_moving_active_channels, velocity_of_right_moving_active_channels, velocity_of_left_moving_active_channels, transmission_matrix_for_active_channels, reflection_matrix_for_active_channels, total_transmission_of_channels, total_conductance, total_reflection_of_channels, sum_of_transmission_and_reflection_of_channels, print_show=1, write_file=0, filename='a', file_format='.txt')
从散射矩阵中打印出散射矩阵的信息
| 参数 | 类型 | 默认值 |
|---|---|---|
number_of_active_channels | 必填 | |
number_of_evanescent_channels | 必填 | |
k_of_right_moving_active_channels | 必填 | |
k_of_left_moving_active_channels | 必填 | |
velocity_of_right_moving_active_channels | 必填 | |
velocity_of_left_moving_active_channels | 必填 | |
transmission_matrix_for_active_channels | 必填 | |
reflection_matrix_for_active_channels | 必填 | |
total_transmission_of_channels | 必填 | |
total_conductance | 必填 | |
total_reflection_of_channels | 必填 | |
sum_of_transmission_and_reflection_of_channels | 必填 | |
print_show | 1 | |
write_file | 0 | |
filename | 'a' | |
file_format | '.txt' |
def print_or_write_scattering_matrix_with_information_of_scattering_matrix(number_of_active_channels, number_of_evanescent_channels, k_of_right_moving_active_channels, k_of_left_moving_active_channels, velocity_of_right_moving_active_channels, velocity_of_left_moving_active_channels, transmission_matrix_for_active_channels, reflection_matrix_for_active_channels, total_transmission_of_channels, total_conductance, total_reflection_of_channels, sum_of_transmission_and_reflection_of_channels, print_show=1, write_file=0, filename='a', file_format='.txt'):
if print_show == 1:
print('\nActive channel (left or right) = ', number_of_active_channels)
print('Evanescent channel (left or right) = ', number_of_evanescent_channels, '\n')
print('K of right-moving active channels:\n', k_of_right_moving_active_channels)
print('K of left-moving active channels:\n', k_of_left_moving_active_channels, '\n')
print('Velocity of right-moving active channels:\n', velocity_of_right_moving_active_channels)
print('Velocity of left-moving active channels:\n', velocity_of_left_moving_active_channels, '\n')
print('Transmission matrix:\n', transmission_matrix_for_active_channels)
print('Reflection matrix:\n', reflection_matrix_for_active_channels, '\n')
print('Total transmission of channels:\n', total_transmission_of_channels)
print('Total conductance = ', total_conductance, '\n')
print('Total reflection of channels:\n', total_reflection_of_channels)
print('Sum of transmission and reflection of channels:\n', sum_of_transmission_and_reflection_of_channels, '\n')
if write_file == 1:
with open(filename+file_format, 'w') as f:
f.write('Active channel (left or right) = ' + str(number_of_active_channels) + '\n')
f.write('Evanescent channel (left or right) = ' + str(number_of_evanescent_channels) + '\n\n')
f.write('Channel K Velocity\n')
for ind0 in range(number_of_active_channels):
f.write(' '+str(ind0 + 1) + ' | '+str(k_of_right_moving_active_channels[ind0])+' ' + str(velocity_of_right_moving_active_channels[ind0])+'\n')
f.write('\n')
for ind0 in range(number_of_active_channels):
f.write(' -' + str(ind0 + 1) + ' | ' + str(k_of_left_moving_active_channels[ind0]) + ' ' + str(velocity_of_left_moving_active_channels[ind0]) + '\n')
f.write('\nScattering matrix:\n ')
for ind0 in range(number_of_active_channels):
f.write(str(ind0+1)+' ')
f.write('\n')
for ind1 in range(number_of_active_channels):
f.write(' '+str(ind1+1)+' ')
for ind2 in range(number_of_active_channels):
f.write('%f' % transmission_matrix_for_active_channels[ind1, ind2]+' ')
f.write('\n')
f.write('\n')
for ind1 in range(number_of_active_channels):
f.write(' -'+str(ind1+1)+' ')
for ind2 in range(number_of_active_channels):
f.write('%f' % reflection_matrix_for_active_channels[ind1, ind2]+' ')
f.write('\n')
f.write('\n')
f.write('Total transmission of channels:\n'+str(total_transmission_of_channels)+'\n')
f.write('Total conductance = '+str(total_conductance)+'\n')
Geometry
print_or_write_scattering_matrixprint_or_write_scattering_matrix(fermi_energy, h00, h01, length=100, print_show=1, write_file=0, filename='a', file_format='.txt')
已知h00和h01,计算散射矩阵并打印出散射矩阵的信息
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
length | 100 | |
print_show | 1 | |
write_file | 0 | |
filename | 'a' | |
file_format | '.txt' |
调用了:guan.calculate_scattering_matrix, guan.information_of_scattering_matrix, guan.print_or_write_scattering_matrix_with_information_of_scattering_matrix
def print_or_write_scattering_matrix(fermi_energy, h00, h01, length=100, print_show=1, write_file=0, filename='a', file_format='.txt'):
import guan
transmission_matrix, reflection_matrix, k_right, k_left, velocity_right, velocity_left, ind_right_active = guan.calculate_scattering_matrix(fermi_energy, h00, h01, length=length)
number_of_active_channels, number_of_evanescent_channels, k_of_right_moving_active_channels, k_of_left_moving_active_channels, velocity_of_right_moving_active_channels, velocity_of_left_moving_active_channels, transmission_matrix_for_active_channels, reflection_matrix_for_active_channels, total_transmission_of_channels, total_conductance, total_reflection_of_channels, sum_of_transmission_and_reflection_of_channels = guan.information_of_scattering_matrix(transmission_matrix, reflection_matrix, k_right, k_left, velocity_right, velocity_left, ind_right_active)
guan.print_or_write_scattering_matrix_with_information_of_scattering_matrix(number_of_active_channels, number_of_evanescent_channels, k_of_right_moving_active_channels, k_of_left_moving_active_channels, velocity_of_right_moving_active_channels, velocity_of_left_moving_active_channels, transmission_matrix_for_active_channels, reflection_matrix_for_active_channels, total_transmission_of_channels, total_conductance, total_reflection_of_channels, sum_of_transmission_and_reflection_of_channels, print_show=print_show, write_file=write_file, filename=filename, file_format=file_format)
Geometry
calculate_scattering_matrix_with_disordercalculate_scattering_matrix_with_disorder(fermi_energy, h00, h01, length=100, disorder_intensity=2.0, disorder_concentration=1.0)
在无序下,计算散射矩阵
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
length | 100 | |
disorder_intensity | 2.0 | |
disorder_concentration | 1.0 |
调用了:guan.get_classified_k_velocity_u_and_f, guan.green_function, guan.green_function_nn_n, guan.green_function_ii_n, guan.green_function_in_n, guan.green_function_ni_n, guan.if_active_channel
def calculate_scattering_matrix_with_disorder(fermi_energy, h00, h01, length=100, disorder_intensity=2.0, disorder_concentration=1.0):
import numpy as np
import math
import copy
import guan
h01 = np.array(h01)
if np.array(h00).shape==():
dim = 1
else:
dim = np.array(h00).shape[0]
k_right, k_left, velocity_right, velocity_left, f_right, f_left, u_right, u_left, ind_right_active = guan.get_classified_k_velocity_u_and_f(fermi_energy, h00, h01)
right_self_energy = np.dot(h01, f_right)
left_self_energy = np.dot(h01.transpose().conj(), np.linalg.inv(f_left))
for i0 in range(length):
disorder = np.zeros((dim, dim))
for dim0 in range(dim):
if np.random.uniform(0, 1)<=disorder_concentration:
disorder[dim0, dim0] = np.random.uniform(-disorder_intensity, disorder_intensity)
if i0 == 0:
green_nn_n = guan.green_function(fermi_energy, h00, broadening=0, self_energy=left_self_energy)
green_00_n = copy.deepcopy(green_nn_n)
green_0n_n = copy.deepcopy(green_nn_n)
green_n0_n = copy.deepcopy(green_nn_n)
elif i0 != length-1:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00+disorder, h01, green_nn_n, broadening=0)
else:
green_nn_n = guan.green_function_nn_n(fermi_energy, h00, h01, green_nn_n, broadening=0, self_energy=right_self_energy)
green_00_n = guan.green_function_ii_n(green_00_n, green_0n_n, h01, green_nn_n, green_n0_n)
green_0n_n = guan.green_function_in_n(green_0n_n, h01, green_nn_n)
green_n0_n = guan.green_function_ni_n(green_nn_n, h01, green_n0_n)
temp = np.dot(h01.transpose().conj(), np.linalg.inv(f_right)-np.linalg.inv(f_left))
transmission_matrix = np.dot(np.dot(np.linalg.inv(u_right), np.dot(green_n0_n, temp)), u_right)
reflection_matrix = np.dot(np.dot(np.linalg.inv(u_left), np.dot(green_00_n, temp)-np.identity(dim)), u_right)
for dim0 in range(dim):
for dim1 in range(dim):
if_active = guan.if_active_channel(k_right[dim0])*guan.if_active_channel(k_right[dim1])
if if_active == 1:
transmission_matrix[dim0, dim1] = math.sqrt(np.abs(velocity_right[dim0]/velocity_right[dim1])) * transmission_matrix[dim0, dim1]
reflection_matrix[dim0, dim1] = math.sqrt(np.abs(velocity_left[dim0]/velocity_right[dim1]))*reflection_matrix[dim0, dim1]
else:
transmission_matrix[dim0, dim1] = 0
reflection_matrix[dim0, dim1] = 0
sum_of_tran_refl_array = np.sum(np.square(np.abs(transmission_matrix[0:ind_right_active, 0:ind_right_active])), axis=0)+np.sum(np.square(np.abs(reflection_matrix[0:ind_right_active, 0:ind_right_active])), axis=0)
for sum_of_tran_refl in sum_of_tran_refl_array:
if sum_of_tran_refl > 1.001:
print('Error Alert: scattering matrix is not normalized!')
return transmission_matrix, reflection_matrix, k_right, k_left, velocity_right, velocity_left, ind_right_active
Geometry
calculate_scattering_matrix_with_disorder_and_get_averaged_informationcalculate_scattering_matrix_with_disorder_and_get_averaged_information(fermi_energy, h00, h01, length=100, disorder_intensity=2.0, disorder_concentration=1.0, calculation_times=1)
在无序下,计算散射矩阵,并获取散射矩阵多次计算的平均信息
| 参数 | 类型 | 默认值 |
|---|---|---|
fermi_energy | 必填 | |
h00 | 必填 | |
h01 | 必填 | |
length | 100 | |
disorder_intensity | 2.0 | |
disorder_concentration | 1.0 | |
calculation_times | 1 |
调用了:guan.calculate_scattering_matrix_with_disorder, guan.information_of_scattering_matrix
def calculate_scattering_matrix_with_disorder_and_get_averaged_information(fermi_energy, h00, h01, length=100, disorder_intensity=2.0, disorder_concentration=1.0, calculation_times=1):
import guan
transmission_matrix_for_active_channels_averaged = 0
reflection_matrix_for_active_channels_averaged = 0
for i0 in range(calculation_times):
transmission_matrix, reflection_matrix, k_right, k_left, velocity_right, velocity_left, ind_right_active = guan.calculate_scattering_matrix_with_disorder(fermi_energy, h00, h01, length, disorder_intensity, disorder_concentration)
number_of_active_channels, number_of_evanescent_channels, k_of_right_moving_active_channels, k_of_left_moving_active_channels, velocity_of_right_moving_active_channels, velocity_of_left_moving_active_channels, transmission_matrix_for_active_channels, reflection_matrix_for_active_channels, total_transmission_of_channels, total_conductance, total_reflection_of_channels, sum_of_transmission_and_reflection_of_channels = guan.information_of_scattering_matrix(transmission_matrix, reflection_matrix, k_right, k_left, velocity_right, velocity_left, ind_right_active)
transmission_matrix_for_active_channels_averaged += transmission_matrix_for_active_channels
reflection_matrix_for_active_channels_averaged += reflection_matrix_for_active_channels
transmission_matrix_for_active_channels_averaged = transmission_matrix_for_active_channels_averaged/calculation_times
reflection_matrix_for_active_channels_averaged = reflection_matrix_for_active_channels_averaged/calculation_times
return transmission_matrix_for_active_channels_averaged, reflection_matrix_for_active_channels_averaged
calculate_chern_number_for_square_lattice_with_efficient_methodcalculate_chern_number_for_square_lattice_with_efficient_method(hamiltonian_function, precision=100, print_show=0)
通过高效法计算方格子的陈数
| 参数 | 类型 | 默认值 |
|---|---|---|
hamiltonian_function | 必填 | |
precision | 100 | |
print_show | 0 |
调用了:guan.calculate_eigenvector
def calculate_chern_number_for_square_lattice_with_efficient_method(hamiltonian_function, precision=100, print_show=0):
import numpy as np
import math
import cmath
import guan
if np.array(hamiltonian_function(0, 0)).shape==():
dim = 1
else:
dim = np.array(hamiltonian_function(0, 0)).shape[0]
delta = 2*math.pi/precision
chern_number = np.zeros(dim, dtype=complex)
for kx in np.arange(-math.pi, math.pi, delta):
if print_show == 1:
print(kx)
for ky in np.arange(-math.pi, math.pi, delta):
H = hamiltonian_function(kx, ky)
vector = guan.calculate_eigenvector(H)
H_delta_kx = hamiltonian_function(kx+delta, ky)
vector_delta_kx = guan.calculate_eigenvector(H_delta_kx)
H_delta_ky = hamiltonian_function(kx, ky+delta)
vector_delta_ky = guan.calculate_eigenvector(H_delta_ky)
H_delta_kx_ky = hamiltonian_function(kx+delta, ky+delta)
vector_delta_kx_ky = guan.calculate_eigenvector(H_delta_kx_ky)
for i in range(dim):
vector_i = vector[:, i]
vector_delta_kx_i = vector_delta_kx[:, i]
vector_delta_ky_i = vector_delta_ky[:, i]
vector_delta_kx_ky_i = vector_delta_kx_ky[:, i]
Ux = np.dot(np.conj(vector_i), vector_delta_kx_i)/abs(np.dot(np.conj(vector_i), vector_delta_kx_i))
Uy = np.dot(np.conj(vector_i), vector_delta_ky_i)/abs(np.dot(np.conj(vector_i), vector_delta_ky_i))
Ux_y = np.dot(np.conj(vector_delta_ky_i), vector_delta_kx_ky_i)/abs(np.dot(np.conj(vector_delta_ky_i), vector_delta_kx_ky_i))
Uy_x = np.dot(np.conj(vector_delta_kx_i), vector_delta_kx_ky_i)/abs(np.dot(np.conj(vector_delta_kx_i), vector_delta_kx_ky_i))
F = cmath.log(Ux*Uy_x*(1/Ux_y)*(1/Uy))
chern_number[i] = chern_number[i] + F
chern_number = chern_number/(2*math.pi*1j)
return chern_number
calculate_chern_number_for_square_lattice_with_efficient_method_for_degenerate_casecalculate_chern_number_for_square_lattice_with_efficient_method_for_degenerate_case(hamiltonian_function, index_of_bands=[0, 1], precision=100, print_show=0)
通过高效法计算方格子的陈数(可计算简并的情况)
| 参数 | 类型 | 默认值 |
|---|---|---|
hamiltonian_function | 必填 | |
index_of_bands | [0, 1] | |
precision | 100 | |
print_show | 0 |
def calculate_chern_number_for_square_lattice_with_efficient_method_for_degenerate_case(hamiltonian_function, index_of_bands=[0, 1], precision=100, print_show=0):
import numpy as np
import math
import cmath
delta = 2*math.pi/precision
chern_number = 0
for kx in np.arange(-math.pi, math.pi, delta):
if print_show == 1:
print(kx)
for ky in np.arange(-math.pi, math.pi, delta):
H = hamiltonian_function(kx, ky)
eigenvalue, vector = np.linalg.eigh(H)
H_delta_kx = hamiltonian_function(kx+delta, ky)
eigenvalue, vector_delta_kx = np.linalg.eigh(H_delta_kx)
H_delta_ky = hamiltonian_function(kx, ky+delta)
eigenvalue, vector_delta_ky = np.linalg.eigh(H_delta_ky)
H_delta_kx_ky = hamiltonian_function(kx+delta, ky+delta)
eigenvalue, vector_delta_kx_ky = np.linalg.eigh(H_delta_kx_ky)
dim = len(index_of_bands)
det_value = 1
# first dot product
dot_matrix = np.zeros((dim , dim), dtype=complex)
i0 = 0
for dim1 in index_of_bands:
j0 = 0
for dim2 in index_of_bands:
dot_matrix[i0, j0] = np.dot(np.conj(vector[:, dim1]), vector_delta_kx[:, dim2])
j0 += 1
i0 += 1
dot_matrix = np.linalg.det(dot_matrix)/abs(np.linalg.det(dot_matrix))
det_value = det_value*dot_matrix
# second dot product
dot_matrix = np.zeros((dim , dim), dtype=complex)
i0 = 0
for dim1 in index_of_bands:
j0 = 0
for dim2 in index_of_bands:
dot_matrix[i0, j0] = np.dot(np.conj(vector_delta_kx[:, dim1]), vector_delta_kx_ky[:, dim2])
j0 += 1
i0 += 1
dot_matrix = np.linalg.det(dot_matrix)/abs(np.linalg.det(dot_matrix))
det_value = det_value*dot_matrix
# third dot product
dot_matrix = np.zeros((dim , dim), dtype=complex)
i0 = 0
for dim1 in index_of_bands:
j0 = 0
for dim2 in index_of_bands:
dot_matrix[i0, j0] = np.dot(np.conj(vector_delta_kx_ky[:, dim1]), vector_delta_ky[:, dim2])
j0 += 1
i0 += 1
dot_matrix = np.linalg.det(dot_matrix)/abs(np.linalg.det(dot_matrix))
det_value = det_value*dot_matrix
# four dot product
dot_matrix = np.zeros((dim , dim), dtype=complex)
i0 = 0
for dim1 in index_of_bands:
j0 = 0
for dim2 in index_of_bands:
dot_matrix[i0, j0] = np.dot(np.conj(vector_delta_ky[:, dim1]), vector[:, dim2])
j0 += 1
i0 += 1
dot_matrix = np.linalg.det(dot_matrix)/abs(np.linalg.det(dot_matrix))
det_value= det_value*dot_matrix
chern_number += cmath.log(det_value)
chern_number = chern_number/(2*math.pi*1j)
return chern_number
calculate_chern_number_for_square_lattice_with_wilson_loopcalculate_chern_number_for_square_lattice_with_wilson_loop(hamiltonian_function, precision_of_plaquettes=20, precision_of_wilson_loop=5, print_show=0)
通过Wilson loop方法计算方格子的陈数
| 参数 | 类型 | 默认值 |
|---|---|---|
hamiltonian_function | 必填 | |
precision_of_plaquettes | 20 | |
precision_of_wilson_loop | 5 | |
print_show | 0 |
def calculate_chern_number_for_square_lattice_with_wilson_loop(hamiltonian_function, precision_of_plaquettes=20, precision_of_wilson_loop=5, print_show=0):
import numpy as np
import math
delta = 2*math.pi/precision_of_plaquettes
chern_number = 0
for kx in np.arange(-math.pi, math.pi, delta):
if print_show == 1:
print(kx)
for ky in np.arange(-math.pi, math.pi, delta):
vector_array = []
# line_1
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx+delta/precision_of_wilson_loop*i0, ky)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
# line_2
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx+delta, ky+delta/precision_of_wilson_loop*i0)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
# line_3
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx+delta-delta/precision_of_wilson_loop*i0, ky+delta)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
# line_4
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx, ky+delta-delta/precision_of_wilson_loop*i0)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
wilson_loop = 1
for i0 in range(len(vector_array)-1):
wilson_loop = wilson_loop*np.dot(vector_array[i0].transpose().conj(), vector_array[i0+1])
wilson_loop = wilson_loop*np.dot(vector_array[len(vector_array)-1].transpose().conj(), vector_array[0])
arg = np.log(np.diagonal(wilson_loop))/1j
chern_number = chern_number + arg
chern_number = chern_number/(2*math.pi)
return chern_number
calculate_chern_number_for_square_lattice_with_wilson_loop_for_degenerate_casecalculate_chern_number_for_square_lattice_with_wilson_loop_for_degenerate_case(hamiltonian_function, index_of_bands=[0, 1], precision_of_plaquettes=20, precision_of_wilson_loop=5, print_show=0)
通过Wilson loop方法计算方格子的陈数(可计算简并的情况)
| 参数 | 类型 | 默认值 |
|---|---|---|
hamiltonian_function | 必填 | |
index_of_bands | [0, 1] | |
precision_of_plaquettes | 20 | |
precision_of_wilson_loop | 5 | |
print_show | 0 |
def calculate_chern_number_for_square_lattice_with_wilson_loop_for_degenerate_case(hamiltonian_function, index_of_bands=[0, 1], precision_of_plaquettes=20, precision_of_wilson_loop=5, print_show=0):
import numpy as np
import math
delta = 2*math.pi/precision_of_plaquettes
chern_number = 0
for kx in np.arange(-math.pi, math.pi, delta):
if print_show == 1:
print(kx)
for ky in np.arange(-math.pi, math.pi, delta):
vector_array = []
# line_1
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx+delta/precision_of_wilson_loop*i0, ky)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
# line_2
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx+delta, ky+delta/precision_of_wilson_loop*i0)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
# line_3
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx+delta-delta/precision_of_wilson_loop*i0, ky+delta)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
# line_4
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx, ky+delta-delta/precision_of_wilson_loop*i0)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
wilson_loop = 1
dim = len(index_of_bands)
for i0 in range(len(vector_array)-1):
dot_matrix = np.zeros((dim , dim), dtype=complex)
i01 = 0
for dim1 in index_of_bands:
i02 = 0
for dim2 in index_of_bands:
dot_matrix[i01, i02] = np.dot(vector_array[i0][:, dim1].transpose().conj(), vector_array[i0+1][:, dim2])
i02 += 1
i01 += 1
det_value = np.linalg.det(dot_matrix)
wilson_loop = wilson_loop*det_value
dot_matrix_plus = np.zeros((dim , dim), dtype=complex)
i01 = 0
for dim1 in index_of_bands:
i02 = 0
for dim2 in index_of_bands:
dot_matrix_plus[i01, i02] = np.dot(vector_array[len(vector_array)-1][:, dim1].transpose().conj(), vector_array[0][:, dim2])
i02 += 1
i01 += 1
det_value = np.linalg.det(dot_matrix_plus)
wilson_loop = wilson_loop*det_value
arg = np.log(wilson_loop)/1j
chern_number = chern_number + arg
chern_number = chern_number/(2*math.pi)
return chern_number
calculate_berry_curvature_with_efficient_methodcalculate_berry_curvature_with_efficient_method(hamiltonian_function, k_min='default', k_max='default', precision=100, print_show=0)
通过高效法计算贝利曲率
| 参数 | 类型 | 默认值 |
|---|---|---|
hamiltonian_function | 必填 | |
k_min | 'default' | |
k_max | 'default' | |
precision | 100 | |
print_show | 0 |
调用了:guan.calculate_eigenvector
def calculate_berry_curvature_with_efficient_method(hamiltonian_function, k_min='default', k_max='default', precision=100, print_show=0):
import numpy as np
import cmath
import guan
import math
if k_min == 'default':
k_min = -math.pi
if k_max == 'default':
k_max=math.pi
if np.array(hamiltonian_function(0, 0)).shape==():
dim = 1
else:
dim = np.array(hamiltonian_function(0, 0)).shape[0]
delta = (k_max-k_min)/precision
k_array = np.arange(k_min, k_max, delta)
berry_curvature_array = np.zeros((k_array.shape[0], k_array.shape[0], dim), dtype=complex)
i0 = 0
for kx in k_array:
if print_show == 1:
print(kx)
j0 = 0
for ky in k_array:
H = hamiltonian_function(kx, ky)
vector = guan.calculate_eigenvector(H)
H_delta_kx = hamiltonian_function(kx+delta, ky)
vector_delta_kx = guan.calculate_eigenvector(H_delta_kx)
H_delta_ky = hamiltonian_function(kx, ky+delta)
vector_delta_ky = guan.calculate_eigenvector(H_delta_ky)
H_delta_kx_ky = hamiltonian_function(kx+delta, ky+delta)
vector_delta_kx_ky = guan.calculate_eigenvector(H_delta_kx_ky)
for i in range(dim):
vector_i = vector[:, i]
vector_delta_kx_i = vector_delta_kx[:, i]
vector_delta_ky_i = vector_delta_ky[:, i]
vector_delta_kx_ky_i = vector_delta_kx_ky[:, i]
Ux = np.dot(np.conj(vector_i), vector_delta_kx_i)/abs(np.dot(np.conj(vector_i), vector_delta_kx_i))
Uy = np.dot(np.conj(vector_i), vector_delta_ky_i)/abs(np.dot(np.conj(vector_i), vector_delta_ky_i))
Ux_y = np.dot(np.conj(vector_delta_ky_i), vector_delta_kx_ky_i)/abs(np.dot(np.conj(vector_delta_ky_i), vector_delta_kx_ky_i))
Uy_x = np.dot(np.conj(vector_delta_kx_i), vector_delta_kx_ky_i)/abs(np.dot(np.conj(vector_delta_kx_i), vector_delta_kx_ky_i))
berry_curvature = cmath.log(Ux*Uy_x*(1/Ux_y)*(1/Uy))/delta/delta*1j
berry_curvature_array[j0, i0, i] = berry_curvature
j0 += 1
i0 += 1
return k_array, berry_curvature_array
calculate_berry_curvature_with_efficient_method_for_degenerate_casecalculate_berry_curvature_with_efficient_method_for_degenerate_case(hamiltonian_function, index_of_bands=[0, 1], k_min='default', k_max='default', precision=100, print_show=0)
通过高效法计算贝利曲率(可计算简并的情况)
| 参数 | 类型 | 默认值 |
|---|---|---|
hamiltonian_function | 必填 | |
index_of_bands | [0, 1] | |
k_min | 'default' | |
k_max | 'default' | |
precision | 100 | |
print_show | 0 |
def calculate_berry_curvature_with_efficient_method_for_degenerate_case(hamiltonian_function, index_of_bands=[0, 1], k_min='default', k_max='default', precision=100, print_show=0):
import numpy as np
import cmath
import math
if k_min == 'default':
k_min = -math.pi
if k_max == 'default':
k_max=math.pi
delta = (k_max-k_min)/precision
k_array = np.arange(k_min, k_max, delta)
berry_curvature_array = np.zeros((k_array.shape[0], k_array.shape[0]), dtype=complex)
i00 = 0
for kx in np.arange(k_min, k_max, delta):
if print_show == 1:
print(kx)
j00 = 0
for ky in np.arange(k_min, k_max, delta):
H = hamiltonian_function(kx, ky)
eigenvalue, vector = np.linalg.eigh(H)
H_delta_kx = hamiltonian_function(kx+delta, ky)
eigenvalue, vector_delta_kx = np.linalg.eigh(H_delta_kx)
H_delta_ky = hamiltonian_function(kx, ky+delta)
eigenvalue, vector_delta_ky = np.linalg.eigh(H_delta_ky)
H_delta_kx_ky = hamiltonian_function(kx+delta, ky+delta)
eigenvalue, vector_delta_kx_ky = np.linalg.eigh(H_delta_kx_ky)
dim = len(index_of_bands)
det_value = 1
# first dot product
dot_matrix = np.zeros((dim , dim), dtype=complex)
i0 = 0
for dim1 in index_of_bands:
j0 = 0
for dim2 in index_of_bands:
dot_matrix[i0, j0] = np.dot(np.conj(vector[:, dim1]), vector_delta_kx[:, dim2])
j0 += 1
i0 += 1
dot_matrix = np.linalg.det(dot_matrix)/abs(np.linalg.det(dot_matrix))
det_value = det_value*dot_matrix
# second dot product
dot_matrix = np.zeros((dim , dim), dtype=complex)
i0 = 0
for dim1 in index_of_bands:
j0 = 0
for dim2 in index_of_bands:
dot_matrix[i0, j0] = np.dot(np.conj(vector_delta_kx[:, dim1]), vector_delta_kx_ky[:, dim2])
j0 += 1
i0 += 1
dot_matrix = np.linalg.det(dot_matrix)/abs(np.linalg.det(dot_matrix))
det_value = det_value*dot_matrix
# third dot product
dot_matrix = np.zeros((dim , dim), dtype=complex)
i0 = 0
for dim1 in index_of_bands:
j0 = 0
for dim2 in index_of_bands:
dot_matrix[i0, j0] = np.dot(np.conj(vector_delta_kx_ky[:, dim1]), vector_delta_ky[:, dim2])
j0 += 1
i0 += 1
dot_matrix = np.linalg.det(dot_matrix)/abs(np.linalg.det(dot_matrix))
det_value = det_value*dot_matrix
# four dot product
dot_matrix = np.zeros((dim , dim), dtype=complex)
i0 = 0
for dim1 in index_of_bands:
j0 = 0
for dim2 in index_of_bands:
dot_matrix[i0, j0] = np.dot(np.conj(vector_delta_ky[:, dim1]), vector[:, dim2])
j0 += 1
i0 += 1
dot_matrix = np.linalg.det(dot_matrix)/abs(np.linalg.det(dot_matrix))
det_value= det_value*dot_matrix
berry_curvature = cmath.log(det_value)/delta/delta*1j
berry_curvature_array[j00, i00] = berry_curvature
j00 += 1
i00 += 1
return k_array, berry_curvature_array
calculate_berry_curvature_with_wilson_loopcalculate_berry_curvature_with_wilson_loop(hamiltonian_function, k_min='default', k_max='default', precision_of_plaquettes=20, precision_of_wilson_loop=5, print_show=0)
通过Wilson loop方法计算贝里曲率
| 参数 | 类型 | 默认值 |
|---|---|---|
hamiltonian_function | 必填 | |
k_min | 'default' | |
k_max | 'default' | |
precision_of_plaquettes | 20 | |
precision_of_wilson_loop | 5 | |
print_show | 0 |
def calculate_berry_curvature_with_wilson_loop(hamiltonian_function, k_min='default', k_max='default', precision_of_plaquettes=20, precision_of_wilson_loop=5, print_show=0):
import numpy as np
import math
if k_min == 'default':
k_min = -math.pi
if k_max == 'default':
k_max=math.pi
if np.array(hamiltonian_function(0, 0)).shape==():
dim = 1
else:
dim = np.array(hamiltonian_function(0, 0)).shape[0]
delta = (k_max-k_min)/precision_of_plaquettes
k_array = np.arange(k_min, k_max, delta)
berry_curvature_array = np.zeros((k_array.shape[0], k_array.shape[0], dim), dtype=complex)
i00 = 0
for kx in k_array:
if print_show == 1:
print(kx)
j00 = 0
for ky in k_array:
vector_array = []
# line_1
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx+delta/precision_of_wilson_loop*i0, ky)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
# line_2
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx+delta, ky+delta/precision_of_wilson_loop*i0)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
# line_3
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx+delta-delta/precision_of_wilson_loop*i0, ky+delta)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
# line_4
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx, ky+delta-delta/precision_of_wilson_loop*i0)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
wilson_loop = 1
for i0 in range(len(vector_array)-1):
wilson_loop = wilson_loop*np.dot(vector_array[i0].transpose().conj(), vector_array[i0+1])
wilson_loop = wilson_loop*np.dot(vector_array[len(vector_array)-1].transpose().conj(), vector_array[0])
berry_curvature = np.log(np.diagonal(wilson_loop))/delta/delta*1j
berry_curvature_array[j00, i00, :]=berry_curvature
j00 += 1
i00 += 1
return k_array, berry_curvature_array
calculate_berry_curvature_with_wilson_loop_for_degenerate_casecalculate_berry_curvature_with_wilson_loop_for_degenerate_case(hamiltonian_function, index_of_bands=[0, 1], k_min='default', k_max='default', precision_of_plaquettes=20, precision_of_wilson_loop=5, print_show=0)
通过Wilson loop方法计算贝里曲率(可计算简并的情况)
| 参数 | 类型 | 默认值 |
|---|---|---|
hamiltonian_function | 必填 | |
index_of_bands | [0, 1] | |
k_min | 'default' | |
k_max | 'default' | |
precision_of_plaquettes | 20 | |
precision_of_wilson_loop | 5 | |
print_show | 0 |
def calculate_berry_curvature_with_wilson_loop_for_degenerate_case(hamiltonian_function, index_of_bands=[0, 1], k_min='default', k_max='default', precision_of_plaquettes=20, precision_of_wilson_loop=5, print_show=0):
import numpy as np
import math
if k_min == 'default':
k_min = -math.pi
if k_max == 'default':
k_max=math.pi
delta = (k_max-k_min)/precision_of_plaquettes
k_array = np.arange(k_min, k_max, delta)
berry_curvature_array = np.zeros((k_array.shape[0], k_array.shape[0]), dtype=complex)
i000 = 0
for kx in k_array:
if print_show == 1:
print(kx)
j000 = 0
for ky in k_array:
vector_array = []
# line_1
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx+delta/precision_of_wilson_loop*i0, ky)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
# line_2
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx+delta, ky+delta/precision_of_wilson_loop*i0)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
# line_3
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx+delta-delta/precision_of_wilson_loop*i0, ky+delta)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
# line_4
for i0 in range(precision_of_wilson_loop):
H_delta = hamiltonian_function(kx, ky+delta-delta/precision_of_wilson_loop*i0)
eigenvalue, eigenvector = np.linalg.eig(H_delta)
vector_delta = eigenvector[:, np.argsort(np.real(eigenvalue))]
vector_array.append(vector_delta)
wilson_loop = 1
dim = len(index_of_bands)
for i0 in range(len(vector_array)-1):
dot_matrix = np.zeros((dim , dim), dtype=complex)
i01 = 0
for dim1 in index_of_bands:
i02 = 0
for dim2 in index_of_bands:
dot_matrix[i01, i02] = np.dot(vector_array[i0][:, dim1].transpose().conj(), vector_array[i0+1][:, dim2])
i02 += 1
i01 += 1
det_value = np.linalg.det(dot_matrix)
wilson_loop = wilson_loop*det_value
dot_matrix_plus = np.zeros((dim , dim), dtype=complex)
i01 = 0
for dim1 in index_of_bands:
i02 = 0
for dim2 in index_of_bands:
dot_matrix_plus[i01, i02] = np.dot(vector_array[len(vector_array)-1][:, dim1].transpose().conj(), vector_array[0][:, dim2])
i02 += 1
i01 += 1
det_value = np.linalg.det(dot_matrix_plus)
wilson_loop = wilson_loop*det_value
berry_curvature = np.log(wilson_loop)/delta/delta*1j
berry_curvature_array[j000, i000]=berry_curvature
j000 += 1
i000 += 1
return k_array, berry_curvature_array
calculate_chern_number_for_honeycomb_latticecalculate_chern_number_for_honeycomb_lattice(hamiltonian_function, a=1, precision=300, print_show=0)
计算蜂窝格子的陈数(高效法)
| 参数 | 类型 | 默认值 |
|---|---|---|
hamiltonian_function | 必填 | |
a | 1 | |
precision | 300 | |
print_show | 0 |
调用了:guan.calculate_eigenvector
def calculate_chern_number_for_honeycomb_lattice(hamiltonian_function, a=1, precision=300, print_show=0):
import numpy as np
import math
import cmath
import guan
if np.array(hamiltonian_function(0, 0)).shape==():
dim = 1
else:
dim = np.array(hamiltonian_function(0, 0)).shape[0]
chern_number = np.zeros(dim, dtype=complex)
L1 = 4*math.sqrt(3)*math.pi/9/a
L2 = 2*math.sqrt(3)*math.pi/9/a
L3 = 2*math.pi/3/a
delta1 = 2*L1/precision
delta3 = 2*L3/precision
for kx in np.arange(-L1, L1, delta1):
if print_show == 1:
print(kx)
for ky in np.arange(-L3, L3, delta3):
if (-L2<=kx<=L2) or (kx>L2 and -(L1-kx)*math.tan(math.pi/3)<=ky<=(L1-kx)*math.tan(math.pi/3)) or (kx<-L2 and -(kx-(-L1))*math.tan(math.pi/3)<=ky<=(kx-(-L1))*math.tan(math.pi/3)):
H = hamiltonian_function(kx, ky)
vector = guan.calculate_eigenvector(H)
H_delta_kx = hamiltonian_function(kx+delta1, ky)
vector_delta_kx = guan.calculate_eigenvector(H_delta_kx)
H_delta_ky = hamiltonian_function(kx, ky+delta3)
vector_delta_ky = guan.calculate_eigenvector(H_delta_ky)
H_delta_kx_ky = hamiltonian_function(kx+delta1, ky+delta3)
vector_delta_kx_ky = guan.calculate_eigenvector(H_delta_kx_ky)
for i in range(dim):
vector_i = vector[:, i]
vector_delta_kx_i = vector_delta_kx[:, i]
vector_delta_ky_i = vector_delta_ky[:, i]
vector_delta_kx_ky_i = vector_delta_kx_ky[:, i]
Ux = np.dot(np.conj(vector_i), vector_delta_kx_i)/abs(np.dot(np.conj(vector_i), vector_delta_kx_i))
Uy = np.dot(np.conj(vector_i), vector_delta_ky_i)/abs(np.dot(np.conj(vector_i), vector_delta_ky_i))
Ux_y = np.dot(np.conj(vector_delta_ky_i), vector_delta_kx_ky_i)/abs(np.dot(np.conj(vector_delta_ky_i), vector_delta_kx_ky_i))
Uy_x = np.dot(np.conj(vector_delta_kx_i), vector_delta_kx_ky_i)/abs(np.dot(np.conj(vector_delta_kx_i), vector_delta_kx_ky_i))
F = cmath.log(Ux*Uy_x*(1/Ux_y)*(1/Uy))
chern_number[i] = chern_number[i] + F
chern_number = chern_number/(2*math.pi*1j)
return chern_number
calculate_wilson_loopcalculate_wilson_loop(hamiltonian_function, k_min='default', k_max='default', precision=100, print_show=0)
计算Wilson loop
| 参数 | 类型 | 默认值 |
|---|---|---|
hamiltonian_function | 必填 | |
k_min | 'default' | |
k_max | 'default' | |
precision | 100 | |
print_show | 0 |
调用了:guan.calculate_eigenvector
def calculate_wilson_loop(hamiltonian_function, k_min='default', k_max='default', precision=100, print_show=0):
import numpy as np
import guan
import math
if k_min == 'default':
k_min = -math.pi
if k_max == 'default':
k_max=math.pi
k_array = np.linspace(k_min, k_max, precision)
dim = np.array(hamiltonian_function(0)).shape[0]
wilson_loop_array = np.ones(dim, dtype=complex)
for i in range(dim):
if print_show == 1:
print(i)
eigenvector_array = []
for k in k_array:
eigenvector = guan.calculate_eigenvector(hamiltonian_function(k))
if k != k_max:
eigenvector_array.append(eigenvector[:, i])
else:
eigenvector_array.append(eigenvector_array[0])
for i0 in range(precision-1):
F = np.dot(eigenvector_array[i0+1].transpose().conj(), eigenvector_array[i0])
wilson_loop_array[i] = np.dot(F, wilson_loop_array[i])
return wilson_loop_array
convolutional_neural_network_with_two_convolutional_layers_and_two_fully_connected_layersconvolutional_neural_network_with_two_convolutional_layers_and_two_fully_connected_layers(in_channels=1, out_channels_1=10, out_channels_2=10, kernel_size_1=3, kernel_size_2=3, stride_1=1, stride_2=1, padding_1=0, padding_2=0, pooling=1, pooling_kernel_size=2, pooling_stride=2, input_size=1, hidden_size_1=10, hidden_size_2=10, output_size=1)
卷积神经网络模型(包含两个卷积层和两个全连接层)(模型的类定义成全局的)
| 参数 | 类型 | 默认值 |
|---|---|---|
in_channels | 1 | |
out_channels_1 | 10 | |
out_channels_2 | 10 | |
kernel_size_1 | 3 | |
kernel_size_2 | 3 | |
stride_1 | 1 | |
stride_2 | 1 | |
padding_1 | 0 | |
padding_2 | 0 | |
pooling | 1 | |
pooling_kernel_size | 2 | |
pooling_stride | 2 | |
input_size | 1 | |
hidden_size_1 | 10 | |
hidden_size_2 | 10 | |
output_size | 1 |
def convolutional_neural_network_with_two_convolutional_layers_and_two_fully_connected_layers(in_channels=1, out_channels_1=10, out_channels_2=10, kernel_size_1=3, kernel_size_2=3, stride_1=1, stride_2=1, padding_1=0, padding_2=0, pooling=1, pooling_kernel_size=2, pooling_stride=2, input_size=1, hidden_size_1=10, hidden_size_2=10, output_size=1):
import torch
global model_class_of_convolutional_neural_network_with_two_convolutional_layers_and_two_fully_connected_layers
class model_class_of_convolutional_neural_network_with_two_convolutional_layers_and_two_fully_connected_layers(torch.nn.Module):
def __init__(self, in_channels, out_channels_1, out_channels_2, kernel_size_1, kernel_size_2, stride_1, stride_2, padding_1, padding_2, pooling, pooling_kernel_size, pooling_stride, input_size, hidden_size_1, hidden_size_2, output_size):
super().__init__()
self.convolutional_layer_1 = torch.nn.Conv2d(in_channels=in_channels, out_channels=out_channels_1, kernel_size=kernel_size_1, stride=stride_1, padding=padding_1)
self.convolutional_layer_2 = torch.nn.Conv2d(in_channels=out_channels_1, out_channels=out_channels_2, kernel_size=kernel_size_2, stride=stride_2, padding=padding_2)
self.pooling_layer = torch.nn.MaxPool2d(kernel_size=pooling_kernel_size, stride=pooling_stride)
self.hidden_layer_1 = torch.nn.Linear(input_size, hidden_size_1)
self.hidden_layer_2 = torch.nn.Linear(hidden_size_1, hidden_size_2)
self.output_layer = torch.nn.Linear(hidden_size_2, output_size)
self.pooling = pooling
def forward(self, x):
if self.pooling == 1:
channel_output_1 = torch.nn.functional.relu(self.pooling_layer(self.convolutional_layer_1(x)))
channel_output_2 = torch.nn.functional.relu(self.pooling_layer(self.convolutional_layer_2(channel_output_1)))
else:
channel_output_1 = torch.nn.functional.relu(self.convolutional_layer_1(x))
channel_output_2 = torch.nn.functional.relu(self.convolutional_layer_2(channel_output_1))
channel_output_2 = torch.flatten(channel_output_2, 1)
hidden_output_1 = torch.nn.functional.relu(self.hidden_layer_1(channel_output_2))
hidden_output_2 = torch.nn.functional.relu(self.hidden_layer_2(hidden_output_1))
output = self.output_layer(hidden_output_2)
return output
model = model_class_of_convolutional_neural_network_with_two_convolutional_layers_and_two_fully_connected_layers(in_channels, out_channels_1, out_channels_2, kernel_size_1, kernel_size_2, stride_1, stride_2, padding_1, padding_2, pooling, pooling_kernel_size, pooling_stride, input_size, hidden_size_1, hidden_size_2, output_size)
return model
get_break_signal_from_loss_arrayget_break_signal_from_loss_array(loss_array, patience=100, min_delta=0.001)
从损失函数的变化情况中获取是否停止训练的信号
| 参数 | 类型 | 默认值 |
|---|---|---|
loss_array | 必填 | |
patience | 100 | |
min_delta | 0.001 |
def get_break_signal_from_loss_array(loss_array, patience=100, min_delta=0.001):
break_signal = 0
counter = 0
num = len(loss_array)
for i0 in range(num):
if i0 != 0:
if abs(loss_array[i0]-loss_array[i0-1])<min_delta:
counter += 1
if counter >= patience:
break_signal = 1
return break_signal
train_modeltrain_model(model, x_data, y_data, optimizer='Adam', learning_rate=0.001, criterion='MSELoss', num_epochs=1000, print_show=1, early_stop=0, patience=100, min_delta=0.001)
使用优化器训练模型
| 参数 | 类型 | 默认值 |
|---|---|---|
model | 必填 | |
x_data | 必填 | |
y_data | 必填 | |
optimizer | 'Adam' | |
learning_rate | 0.001 | |
criterion | 'MSELoss' | |
num_epochs | 1000 | |
print_show | 1 | |
early_stop | 0 | |
patience | 100 | |
min_delta | 0.001 |
调用了:guan.get_break_signal_from_loss_array
def train_model(model, x_data, y_data, optimizer='Adam', learning_rate=0.001, criterion='MSELoss', num_epochs=1000, print_show=1, early_stop=0, patience=100, min_delta=0.001):
import torch
if optimizer == 'Adam':
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
elif optimizer == 'SGD':
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
if criterion == 'MSELoss':
criterion = torch.nn.MSELoss()
elif criterion == 'CrossEntropyLoss':
criterion = torch.nn.CrossEntropyLoss()
loss_array = []
for epoch in range(num_epochs):
output = model.forward(x_data)
loss = criterion(output, y_data)
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss_array.append(loss.item())
if print_show == 1:
if (epoch + 1) % 100 == 0:
print(epoch, loss.item())
if early_stop == 1:
import guan
break_signal = guan.get_break_signal_from_loss_array(loss_array, patience=patience, min_delta=min_delta)
if break_signal:
break
return model, loss_array
batch_train_modelbatch_train_model(model, train_loader, optimizer='Adam', learning_rate=0.001, criterion='MSELoss', num_epochs=1000, print_show=1, more_loss_data=0, early_stop=0, patience=100, min_delta=0.001)
使用优化器批量训练模型
| 参数 | 类型 | 默认值 |
|---|---|---|
model | 必填 | |
train_loader | 必填 | |
optimizer | 'Adam' | |
learning_rate | 0.001 | |
criterion | 'MSELoss' | |
num_epochs | 1000 | |
print_show | 1 | |
more_loss_data | 0 | |
early_stop | 0 | |
patience | 100 | |
min_delta | 0.001 |
调用了:guan.get_break_signal_from_loss_array
def batch_train_model(model, train_loader, optimizer='Adam', learning_rate=0.001, criterion='MSELoss', num_epochs=1000, print_show=1, more_loss_data=0, early_stop=0, patience=100, min_delta=0.001):
import torch
if optimizer == 'Adam':
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
elif optimizer == 'SGD':
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
if criterion == 'MSELoss':
criterion = torch.nn.MSELoss()
elif criterion == 'CrossEntropyLoss':
criterion = torch.nn.CrossEntropyLoss()
loss_array = []
losses = []
for epoch in range(num_epochs):
for batch_x, batch_y in train_loader:
output = model.forward(batch_x)
loss = criterion(output, batch_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
losses.append(loss.item())
loss_array.append(loss.item())
if print_show == 1:
if (epoch + 1) % 100 == 0:
print(epoch, loss.item())
if early_stop == 1:
import guan
break_signal = guan.get_break_signal_from_loss_array(loss_array, patience=patience, min_delta=min_delta)
if break_signal:
break
if more_loss_data == 0:
return model, loss_array
else:
return model, losses
save_model_parameterssave_model_parameters(model, filename='./model_parameters.pth')
保存模型参数到文件
| 参数 | 类型 | 默认值 |
|---|---|---|
model | 必填 | |
filename | './model_parameters.pth' |
def save_model_parameters(model, filename='./model_parameters.pth'):
import torch
torch.save(model.state_dict(), filename)
save_modelsave_model(model, filename='./model.pth')
保存完整模型到文件(保存时需要模型的类可访问)
| 参数 | 类型 | 默认值 |
|---|---|---|
model | 必填 | |
filename | './model.pth' |
def save_model(model, filename='./model.pth'):
import torch
torch.save(model, filename)
save_model_with_torch_jit_scriptsave_model_with_torch_jit_script(model, filename='model_scripted_with_torch_jit.pth')
使用TorchScript形式保存模型到文件(TorchScript允许模型在不依赖Python解释器的情况下运行,适合在生产环境中部署)
| 参数 | 类型 | 默认值 |
|---|---|---|
model | 必填 | |
filename | 'model_scripted_with_torch_jit.pth' |
def save_model_with_torch_jit_script(model, filename='model_scripted_with_torch_jit.pth'):
import torch
scripted_model = torch.jit.script(model)
scripted_model.save(filename)
save_model_with_all_informationsave_model_with_all_information(model, model_class, model_instantiation, note='', filename='./model_with_all_information.pth')
以字典的形式保存模型的所有信息到文件(保存时需要模型的类可访问,此外还要输入模型的实例化函数。需要注意的是:该方法要求类和实例化函数都是独立可直接运行的模块)
| 参数 | 类型 | 默认值 |
|---|---|---|
model | 必填 | |
model_class | 必填 | |
model_instantiation | 必填 | |
note | '' | |
filename | './model_with_all_information.pth' |
调用了:guan.get_source
def save_model_with_all_information(model, model_class, model_instantiation, note='', filename='./model_with_all_information.pth'):
import torch
import guan
model_class_source = guan.get_source(name=model_class)
model_class_source = 'import torch\n'+model_class_source
model_instantiation_source = guan.get_source(name=model_instantiation)
checkpoint = {'model_state_dict': model.state_dict(),
'model_class_name': model_class.__name__,
'model_class_source': model_class_source,
'model_instantiation_name':model_instantiation.__name__,
'model_instantiation_source': model_instantiation_source,
'note': note,}
torch.save(checkpoint, filename)
load_model_parametersload_model_parameters(model, filename='./model_parameters.pth')
加载模型参数(需要输入模型,加载后,原输入的模型参数也会改变)
| 参数 | 类型 | 默认值 |
|---|---|---|
model | 必填 | |
filename | './model_parameters.pth' |
def load_model_parameters(model, filename='./model_parameters.pth'):
import torch
model.load_state_dict(torch.load(filename))
return model
load_modelload_model(filename='./model.pth')
加载完整模型(不需要输入模型,但加载时需要原定义的模型的类可访问)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | './model.pth' |
def load_model(filename='./model.pth'):
import torch
model = torch.load(filename)
return model
load_model_with_torch_jit_scriptload_model_with_torch_jit_script(filename='model_scripted_with_torch_jit.pth')
加载TorchScript形式的模型
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 'model_scripted_with_torch_jit.pth' |
def load_model_with_torch_jit_script(filename='model_scripted_with_torch_jit.pth'):
import torch
scripted_model = torch.jit.load(filename)
return scripted_model
load_model_with_all_informationload_model_with_all_information(filename='./model_with_all_information.pth', note_print=0)
加载包含所有信息的模型(包含了模型的类和实例化函数等,返回的是模型对象。需要注意的是:该方法要求类和实例化函数都是独立可直接运行的模块)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | './model_with_all_information.pth' | |
note_print | 0 |
def load_model_with_all_information(filename='./model_with_all_information.pth', note_print=0):
import torch
checkpoint = torch.load(filename)
model_class_source = checkpoint['model_class_source']
exec(model_class_source, globals())
# model_class_name = checkpoint['model_class_name']
# model_class = globals()[model_class_name]
model_instantiation_source = checkpoint['model_instantiation_source']
exec(model_instantiation_source, globals())
model_instantiation_name = checkpoint['model_instantiation_name']
model_instantiation = globals()[model_instantiation_name]
model = model_instantiation()
model.load_state_dict(checkpoint['model_state_dict'])
if note_print==1:
note = checkpoint['note']
print(note)
return model
load_train_dataload_train_data(x_train, y_train, batch_size=32)
加载训练数据,用于批量加载训练
| 参数 | 类型 | 默认值 |
|---|---|---|
x_train | 必填 | |
y_train | 必填 | |
batch_size | 32 |
def load_train_data(x_train, y_train, batch_size=32):
from torch.utils.data import DataLoader, TensorDataset
train_dataset = TensorDataset(x_train, y_train)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
return train_loader
load_input_data_and_output_data_as_torch_tensors_with_pickleload_input_data_and_output_data_as_torch_tensors_with_pickle(index_range=[1, 2, 3], directory='./', input_filename='input_index=', output_filename='output_index=', type=None)
从pickle文件(多个小文件)中读取输入数据和输出数据,用于训练或预测
| 参数 | 类型 | 默认值 |
|---|---|---|
index_range | [1, 2, 3] | |
directory | './' | |
input_filename | 'input_index=' | |
output_filename | 'output_index=' | |
type | None |
调用了:guan.load_data
def load_input_data_and_output_data_as_torch_tensors_with_pickle(index_range=[1, 2, 3], directory='./', input_filename='input_index=', output_filename='output_index=', type=None):
import guan
import numpy as np
import torch
input_data = []
for index in index_range:
input = guan.load_data(filename=directory+input_filename+str(index))
input_data.append(input)
output_data = []
for index in index_range:
output = guan.load_data(filename=directory+output_filename+str(index))
output_data.append(output)
if type == None:
input_data = np.array(input_data)
output_data= np.array(output_data)
else:
input_data = np.array(input_data).astype(type)
output_data= np.array(output_data).astype(type)
input_data = torch.from_numpy(input_data)
output_data = torch.from_numpy(output_data)
return input_data, output_data
load_input_data_and_output_data_as_torch_tensors_with_pickle_from_array_fileload_input_data_and_output_data_as_torch_tensors_with_pickle_from_array_file(input_filename='input_file', output_filename='output_file', type=None)
从pickle文件(一个数组文件)中读取输入数据和输出数据,用于训练或预测
| 参数 | 类型 | 默认值 |
|---|---|---|
input_filename | 'input_file' | |
output_filename | 'output_file' | |
type | None |
调用了:guan.load_data
def load_input_data_and_output_data_as_torch_tensors_with_pickle_from_array_file(input_filename='input_file', output_filename='output_file', type=None):
import guan
import numpy as np
import torch
input_data = guan.load_data(filename=input_filename)
output_data = guan.load_data(filename=output_filename)
if type == None:
input_data = np.array(input_data)
output_data= np.array(output_data)
else:
input_data = np.array(input_data).astype(type)
output_data= np.array(output_data).astype(type)
input_data = torch.from_numpy(input_data)
output_data = torch.from_numpy(output_data)
return input_data, output_data
pca_of_datapca_of_data(data, n_components=None, standard=1)
数据的主成分分析PCA
| 参数 | 类型 | 默认值 |
|---|---|---|
data | 必填 | |
n_components | None | |
standard | 1 |
def pca_of_data(data, n_components=None, standard=1):
from sklearn.decomposition import PCA
if standard==1:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)
else:
data_scaled = data
if n_components==None:
pca = PCA()
else:
pca = PCA(n_components=n_components)
data_transformed = pca.fit_transform(data_scaled)
explained_variance_ratio = pca.explained_variance_ratio_
return data_transformed, explained_variance_ratio
calculate_R2_with_definitioncalculate_R2_with_definition(y_true_array, y_pred_array)
通过定义计算R^2(基于实际值和预测值,数值有可能小于0)
| 参数 | 类型 | 默认值 |
|---|---|---|
y_true_array | 必填 | |
y_pred_array | 必填 |
def calculate_R2_with_definition(y_true_array, y_pred_array):
import numpy as np
y_mean = np.mean(y_true_array)
SS_tot = np.sum((y_true_array - y_mean) ** 2)
SS_res = np.sum((y_true_array - y_pred_array) ** 2)
R2 = 1 - (SS_res / SS_tot)
return R2
calculate_R2_with_sklearncalculate_R2_with_sklearn(y_true_array, y_pred_array)
通过sklearn计算R^2,和上面定义的计算结果一致
| 参数 | 类型 | 默认值 |
|---|---|---|
y_true_array | 必填 | |
y_pred_array | 必填 |
def calculate_R2_with_sklearn(y_true_array, y_pred_array):
from sklearn.metrics import r2_score
R2 = r2_score(y_true_array, y_pred_array)
return R2
calculate_R2_after_linear_regression_with_scipycalculate_R2_after_linear_regression_with_scipy(y_true_array, y_pred_array)
通过scipy计算线性回归后的R^2(基于线性回归模型,范围在0和1之间)
| 参数 | 类型 | 默认值 |
|---|---|---|
y_true_array | 必填 | |
y_pred_array | 必填 |
def calculate_R2_after_linear_regression_with_scipy(y_true_array, y_pred_array):
from scipy import stats
slope, intercept, r_value, p_value, std_err = stats.linregress(y_true_array, y_pred_array)
R2 = r_value**2
return R2
dump_datadump_data(data, filename='a', file_format='.pkl')
使用pickle将变量保存到文件(支持几乎所有对象类型)
| 参数 | 类型 | 默认值 |
|---|---|---|
data | 必填 | |
filename | 'a' | |
file_format | '.pkl' |
def dump_data(data, filename='a', file_format='.pkl'):
import pickle
with open(filename+file_format, 'wb') as f:
pickle.dump(data, f)
load_dataload_data(filename, file_format='.pkl')
使用pickle从文件中恢复数据到变量(支持几乎所有对象类型)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 必填 | |
file_format | '.pkl' |
def load_data(filename, file_format='.pkl'):
import pickle
with open(filename+file_format, 'rb') as f:
data = pickle.load(f)
return data
save_npy_datasave_npy_data(data, filename='a')
使用NumPy保存数组变量到npy文件(二进制文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
data | 必填 | |
filename | 'a' |
def save_npy_data(data, filename='a'):
import numpy as np
np.save(filename+'.npy', data)
load_npy_dataload_npy_data(filename)
使用NumPy从npy文件恢复数据到数组变量(二进制文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 必填 |
def load_npy_data(filename):
import numpy as np
data = np.load(filename+'.npy')
return data
save_txt_datasave_txt_data(data, filename='a')
使用NumPy保存数组变量到TXT文件(文本文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
data | 必填 | |
filename | 'a' |
def save_txt_data(data, filename='a'):
import numpy as np
np.savetxt(filename+'.txt', data)
load_txt_dataload_txt_data(filename)
使用NumPy从TXT文件恢复数据到数组变量(文本文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 必填 |
def load_txt_data(filename):
import numpy as np
data = np.loadtxt(filename+'.txt')
return data
read_one_dimensional_dataread_one_dimensional_data(filename='a', file_format='.txt')
读取文件中的一维数据(一行一组x和y)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 'a' | |
file_format | '.txt' |
def read_one_dimensional_data(filename='a', file_format='.txt'):
import numpy as np
f = open(filename+file_format, 'r', encoding='UTF-8')
text = f.read()
f.close()
row_list = np.array(text.split('\n'))
dim_column = np.array(row_list[0].split()).shape[0]
x_array = np.array([])
y_array = np.array([])
for row in row_list:
column = np.array(row.split())
if column.shape[0] != 0:
x_array = np.append(x_array, [float(column[0])], axis=0)
y_row = np.zeros(dim_column-1)
for dim0 in range(dim_column-1):
y_row[dim0] = float(column[dim0+1])
if np.array(y_array).shape[0] == 0:
y_array = [y_row]
else:
y_array = np.append(y_array, [y_row], axis=0)
return x_array, y_array
read_one_dimensional_complex_dataread_one_dimensional_complex_data(filename='a', file_format='.txt')
读取文件中的一维数据(一行一组x和y)(支持复数形式)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 'a' | |
file_format | '.txt' |
def read_one_dimensional_complex_data(filename='a', file_format='.txt'):
import numpy as np
f = open(filename+file_format, 'r', encoding='UTF-8')
text = f.read()
f.close()
row_list = np.array(text.split('\n'))
dim_column = np.array(row_list[0].split()).shape[0]
x_array = np.array([])
y_array = np.array([])
for row in row_list:
column = np.array(row.split())
if column.shape[0] != 0:
x_array = np.append(x_array, [complex(column[0])], axis=0)
y_row = np.zeros(dim_column-1, dtype=complex)
for dim0 in range(dim_column-1):
y_row[dim0] = complex(column[dim0+1])
if np.array(y_array).shape[0] == 0:
y_array = [y_row]
else:
y_array = np.append(y_array, [y_row], axis=0)
return x_array, y_array
read_xyz_dataread_xyz_data(filename='a', file_format='.txt')
读取文件中的XYZ数据(一行一组x, y, z)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 'a' | |
file_format | '.txt' |
def read_xyz_data(filename='a', file_format='.txt'):
import numpy as np
f = open(filename+file_format, 'r', encoding='UTF-8')
text = f.read()
f.close()
row_list = np.array(text.split('\n'))
x_array = np.array([])
y_array = np.array([])
z_array = np.array([])
for row in row_list:
column = np.array(row.split())
if column.shape[0] != 0:
x_array = np.append(x_array, [float(column[0])], axis=0)
y_array = np.append(y_array, [float(column[1])], axis=0)
z_array = np.append(z_array, [float(column[2])], axis=0)
return x_array, y_array, z_array
read_two_dimensional_dataread_two_dimensional_data(filename='a', file_format='.txt')
读取文件中的二维数据(第一行和第一列分别为横纵坐标)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 'a' | |
file_format | '.txt' |
def read_two_dimensional_data(filename='a', file_format='.txt'):
import numpy as np
f = open(filename+file_format, 'r', encoding='UTF-8')
text = f.read()
f.close()
row_list = np.array(text.split('\n'))
dim_column = np.array(row_list[0].split()).shape[0]
x_array = np.array([])
y_array = np.array([])
matrix = np.array([])
for i0 in range(row_list.shape[0]):
column = np.array(row_list[i0].split())
if i0 == 0:
x_str = column[1::]
x_array = np.zeros(x_str.shape[0])
for i00 in range(x_str.shape[0]):
x_array[i00] = float(x_str[i00])
elif column.shape[0] != 0:
y_array = np.append(y_array, [float(column[0])], axis=0)
matrix_row = np.zeros(dim_column-1)
for dim0 in range(dim_column-1):
matrix_row[dim0] = float(column[dim0+1])
if np.array(matrix).shape[0] == 0:
matrix = [matrix_row]
else:
matrix = np.append(matrix, [matrix_row], axis=0)
return x_array, y_array, matrix
read_two_dimensional_complex_dataread_two_dimensional_complex_data(filename='a', file_format='.txt')
读取文件中的二维数据(第一行和第一列分别为横纵坐标)(支持复数形式)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 'a' | |
file_format | '.txt' |
def read_two_dimensional_complex_data(filename='a', file_format='.txt'):
import numpy as np
f = open(filename+file_format, 'r', encoding='UTF-8')
text = f.read()
f.close()
row_list = np.array(text.split('\n'))
dim_column = np.array(row_list[0].split()).shape[0]
x_array = np.array([])
y_array = np.array([])
matrix = np.array([])
for i0 in range(row_list.shape[0]):
column = np.array(row_list[i0].split())
if i0 == 0:
x_str = column[1::]
x_array = np.zeros(x_str.shape[0], dtype=complex)
for i00 in range(x_str.shape[0]):
x_array[i00] = complex(x_str[i00])
elif column.shape[0] != 0:
y_array = np.append(y_array, [complex(column[0])], axis=0)
matrix_row = np.zeros(dim_column-1, dtype=complex)
for dim0 in range(dim_column-1):
matrix_row[dim0] = complex(column[dim0+1])
if np.array(matrix).shape[0] == 0:
matrix = [matrix_row]
else:
matrix = np.append(matrix, [matrix_row], axis=0)
return x_array, y_array, matrix
read_two_dimensional_data_without_xy_arrayread_two_dimensional_data_without_xy_array(filename='a', file_format='.txt')
读取文件中的二维数据(不包括横纵坐标)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 'a' | |
file_format | '.txt' |
def read_two_dimensional_data_without_xy_array(filename='a', file_format='.txt'):
import numpy as np
matrix = np.loadtxt(filename+file_format)
return matrix
write_one_dimensional_datawrite_one_dimensional_data(x_array, y_array, filename='a', file_format='.txt')
在文件中写入一维数据(一行一组x和y)
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
filename | 'a' | |
file_format | '.txt' |
调用了:guan.write_one_dimensional_data_without_opening_file
def write_one_dimensional_data(x_array, y_array, filename='a', file_format='.txt'):
import guan
with open(filename+file_format, 'w', encoding='UTF-8') as f:
guan.write_one_dimensional_data_without_opening_file(x_array, y_array, f)
write_one_dimensional_data_without_opening_filewrite_one_dimensional_data_without_opening_file(x_array, y_array, f)
在文件中写入一维数据(一行一组x和y)(需要输入已打开的文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
f | 必填 |
def write_one_dimensional_data_without_opening_file(x_array, y_array, f):
import numpy as np
x_array = np.array(x_array)
y_array = np.array(y_array)
i0 = 0
for x0 in x_array:
f.write(str(x0)+' ')
if len(y_array.shape) == 1:
f.write(str(y_array[i0])+'\n')
elif len(y_array.shape) == 2:
for j0 in range(y_array.shape[1]):
f.write(str(y_array[i0, j0])+' ')
f.write('\n')
i0 += 1
write_xyz_datawrite_xyz_data(x_array, y_array, z_array, filename='a', file_format='.txt')
在文件中写入XYZ数据(一行一组x, y, z)
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
z_array | 必填 | |
filename | 'a' | |
file_format | '.txt' |
def write_xyz_data(x_array, y_array, z_array, filename='a', file_format='.txt'):
import guan
with open(filename+file_format, 'w', encoding='UTF-8') as f:
write_xyz_data_without_opening_file(x_array, y_array, z_array, f)
write_xyz_data_without_opening_filewrite_xyz_data_without_opening_file(x_array, y_array, z_array, f)
在文件中写入XYZ数据(一行一组x, y, z)(需要输入已打开的文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
z_array | 必填 | |
f | 必填 |
def write_xyz_data_without_opening_file(x_array, y_array, z_array, f):
import numpy as np
x_array = np.array(x_array)
y_array = np.array(y_array)
z_array = np.array(z_array)
i0 = 0
for x0 in x_array:
f.write(str(x0)+' ')
f.write(str(y_array[i0])+' ')
f.write(str(z_array[i0])+'\n')
i0 += 1
write_two_dimensional_datawrite_two_dimensional_data(x_array, y_array, matrix, filename='a', file_format='.txt')
在文件中写入二维数据(第一行和第一列分别为横纵坐标)
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
matrix | 必填 | |
filename | 'a' | |
file_format | '.txt' |
调用了:guan.write_two_dimensional_data_without_opening_file
def write_two_dimensional_data(x_array, y_array, matrix, filename='a', file_format='.txt'):
import guan
with open(filename+file_format, 'w', encoding='UTF-8') as f:
guan.write_two_dimensional_data_without_opening_file(x_array, y_array, matrix, f)
write_two_dimensional_data_without_opening_filewrite_two_dimensional_data_without_opening_file(x_array, y_array, matrix, f)
在文件中写入二维数据(第一行和第一列分别为横纵坐标)(需要输入已打开的文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
matrix | 必填 | |
f | 必填 |
def write_two_dimensional_data_without_opening_file(x_array, y_array, matrix, f):
import numpy as np
x_array = np.array(x_array)
y_array = np.array(y_array)
matrix = np.array(matrix)
f.write('0 ')
for x0 in x_array:
f.write(str(x0)+' ')
f.write('\n')
i0 = 0
for y0 in y_array:
f.write(str(y0))
j0 = 0
for x0 in x_array:
f.write(' '+str(matrix[i0, j0])+' ')
j0 += 1
f.write('\n')
i0 += 1
write_two_dimensional_data_without_xy_arraywrite_two_dimensional_data_without_xy_array(matrix, filename='a', file_format='.txt')
在文件中写入二维数据(不包括横纵坐标)
| 参数 | 类型 | 默认值 |
|---|---|---|
matrix | 必填 | |
filename | 'a' | |
file_format | '.txt' |
调用了:guan.write_two_dimensional_data_without_xy_array_and_without_opening_file
def write_two_dimensional_data_without_xy_array(matrix, filename='a', file_format='.txt'):
import guan
with open(filename+file_format, 'w', encoding='UTF-8') as f:
guan.write_two_dimensional_data_without_xy_array_and_without_opening_file(matrix, f)
write_two_dimensional_data_without_xy_array_and_without_opening_filewrite_two_dimensional_data_without_xy_array_and_without_opening_file(matrix, f)
在文件中写入二维数据(不包括横纵坐标)(需要输入已打开的文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
matrix | 必填 | |
f | 必填 |
def write_two_dimensional_data_without_xy_array_and_without_opening_file(matrix, f):
for row in matrix:
for element in row:
f.write(str(element)+' ')
f.write('\n')
make_sh_file_for_qsubmake_sh_file_for_qsub(sh_filename='a', command_line='python a.py', cpu_num=1, task_name='task', cd_dir=0, pbs_q=0, queue_name='bigmem', specific_node=0, node_name='node50.cluster')
创建一个sh文件用于提交任务(PBS)
| 参数 | 类型 | 默认值 |
|---|---|---|
sh_filename | 'a' | |
command_line | 'python a.py' | |
cpu_num | 1 | |
task_name | 'task' | |
cd_dir | 0 | |
pbs_q | 0 | |
queue_name | 'bigmem' | |
specific_node | 0 | |
node_name | 'node50.cluster' |
def make_sh_file_for_qsub(sh_filename='a', command_line='python a.py', cpu_num=1, task_name='task', cd_dir=0, pbs_q=0, queue_name='bigmem', specific_node=0, node_name='node50.cluster'):
sh_content = \
'#!/bin/sh\n' \
+f'#PBS -N {task_name}\n'
if pbs_q==1:
sh_content += f'#PBS -q {queue_name}\n'
if specific_node==0:
sh_content += f'#PBS -l nodes=1:ppn={cpu_num}\n'
else:
sh_content += f'#PBS -l nodes={node_name}:ppn={cpu_num}\n'
if cd_dir==1:
sh_content += 'cd $PBS_O_WORKDIR\n'
sh_content += command_line
with open(sh_filename+'.sh', 'w') as f:
f.write(sh_content)
make_sh_file_for_sbatchmake_sh_file_for_sbatch(sh_filename='a', command_line='python a.py', cpu_num=1, task_name='task', cd_dir=0, sbatch_partition=0, partition_name='cpu48')
创建一个sh文件用于提交任务(Slurm)
| 参数 | 类型 | 默认值 |
|---|---|---|
sh_filename | 'a' | |
command_line | 'python a.py' | |
cpu_num | 1 | |
task_name | 'task' | |
cd_dir | 0 | |
sbatch_partition | 0 | |
partition_name | 'cpu48' |
def make_sh_file_for_sbatch(sh_filename='a', command_line='python a.py', cpu_num=1, task_name='task', cd_dir=0, sbatch_partition=0, partition_name='cpu48'):
sh_content = \
'#!/bin/sh\n' \
+f'#SBATCH --job-name={task_name}\n'
if sbatch_partition==1:
sh_content += f'#SBATCH --partition={partition_name}\n'
sh_content += f'#SBATCH --cpus-per-task={cpu_num}\n'
if cd_dir==1:
sh_content += 'cd $PBS_O_WORKDIR\n'
sh_content += command_line
with open(sh_filename+'.sh', 'w') as f:
f.write(sh_content)
make_sh_file_for_bsubmake_sh_file_for_bsub(sh_filename='a', command_line='python a.py', cpu_num=1, task_name='task', cd_dir=0, bsub_q=0, queue_name='score')
创建一个sh文件用于提交任务(LSF)
| 参数 | 类型 | 默认值 |
|---|---|---|
sh_filename | 'a' | |
command_line | 'python a.py' | |
cpu_num | 1 | |
task_name | 'task' | |
cd_dir | 0 | |
bsub_q | 0 | |
queue_name | 'score' |
def make_sh_file_for_bsub(sh_filename='a', command_line='python a.py', cpu_num=1, task_name='task', cd_dir=0, bsub_q=0, queue_name='score'):
sh_content = \
'#!/bin/sh\n' \
+f'#BSUB -J {task_name}\n'
if bsub_q==1:
sh_content += f'#BSUB -q {queue_name}\n'
sh_content += f'#BSUB -n {cpu_num}\n'
if cd_dir==1:
sh_content += 'cd $PBS_O_WORKDIR\n'
sh_content += command_line
with open(sh_filename+'.sh', 'w') as f:
f.write(sh_content)
qsub_taskqsub_task(filename='a', file_format='.sh')
qsub 提交任务(PBS)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 'a' | |
file_format | '.sh' |
def qsub_task(filename='a', file_format='.sh'):
import os
os.system('qsub '+filename+file_format)
sbatch_tasksbatch_task(filename='a', file_format='.sh')
sbatch 提交任务(Slurm)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 'a' | |
file_format | '.sh' |
def sbatch_task(filename='a', file_format='.sh'):
import os
os.system('sbatch '+filename+file_format)
bsub_taskbsub_task(filename='a', file_format='.sh')
bsub 提交任务(LSF)
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 'a' | |
file_format | '.sh' |
def bsub_task(filename='a', file_format='.sh'):
import os
os.system('bsub < '+filename+file_format)
copy_py_sh_file_and_qsub_taskcopy_py_sh_file_and_qsub_task(parameter_array, py_filename='a', old_str_in_py='parameter = 0', new_str_in_py='parameter = ', sh_filename='a', task_name='task')
复制.py和.sh文件,然后提交任务,实现半手动并行(PBS)
| 参数 | 类型 | 默认值 |
|---|---|---|
parameter_array | 必填 | |
py_filename | 'a' | |
old_str_in_py | 'parameter = 0' | |
new_str_in_py | 'parameter = ' | |
sh_filename | 'a' | |
task_name | 'task' |
def copy_py_sh_file_and_qsub_task(parameter_array, py_filename='a', old_str_in_py='parameter = 0', new_str_in_py='parameter = ', sh_filename='a', task_name='task'):
import os
parameter_str_array = []
for i0 in parameter_array:
parameter_str_array.append(str(i0))
index = 0
for parameter_str in parameter_str_array:
index += 1
# copy python file
old_file = py_filename+'.py'
new_file = py_filename+'_'+str(index)+'.py'
os.system('cp '+old_file+' '+new_file)
with open(new_file, 'r') as f:
content = f.read()
old_str = old_str_in_py
new_str = new_str_in_py+parameter_str
content = content.replace(old_str, new_str)
with open(py_filename+'_'+str(index)+'.py', 'w') as f:
f.write(content)
# copy sh file
old_file = sh_filename+'.sh'
new_file = sh_filename+'_'+str(index)+'.sh'
os.system('cp '+old_file+' '+new_file)
with open(new_file, 'r') as f:
content = f.read()
old_str = 'python '+py_filename+'.py'
new_str = 'python '+py_filename+'_'+str(index)+'.py'
content = content.replace(old_str, new_str)
old_str = '#PBS -N '+task_name
new_str = '#PBS -N '+task_name+'_'+str(index)
content = content.replace(old_str, new_str)
with open(sh_filename+'_'+str(index)+'.sh', 'w') as f:
f.write(content)
# qsub task
os.system('qsub '+new_file)
copy_py_sh_file_and_sbatch_taskcopy_py_sh_file_and_sbatch_task(parameter_array, py_filename='a', old_str_in_py='parameter = 0', new_str_in_py='parameter = ', sh_filename='a', task_name='task')
复制.py和.sh文件,然后提交任务,实现半手动并行(Slurm)
| 参数 | 类型 | 默认值 |
|---|---|---|
parameter_array | 必填 | |
py_filename | 'a' | |
old_str_in_py | 'parameter = 0' | |
new_str_in_py | 'parameter = ' | |
sh_filename | 'a' | |
task_name | 'task' |
def copy_py_sh_file_and_sbatch_task(parameter_array, py_filename='a', old_str_in_py='parameter = 0', new_str_in_py='parameter = ', sh_filename='a', task_name='task'):
import os
parameter_str_array = []
for i0 in parameter_array:
parameter_str_array.append(str(i0))
index = 0
for parameter_str in parameter_str_array:
index += 1
# copy python file
old_file = py_filename+'.py'
new_file = py_filename+'_'+str(index)+'.py'
os.system('cp '+old_file+' '+new_file)
with open(new_file, 'r') as f:
content = f.read()
old_str = old_str_in_py
new_str = new_str_in_py+parameter_str
content = content.replace(old_str, new_str)
with open(py_filename+'_'+str(index)+'.py', 'w') as f:
f.write(content)
# copy sh file
old_file = sh_filename+'.sh'
new_file = sh_filename+'_'+str(index)+'.sh'
os.system('cp '+old_file+' '+new_file)
with open(new_file, 'r') as f:
content = f.read()
old_str = 'python '+py_filename+'.py'
new_str = 'python '+py_filename+'_'+str(index)+'.py'
content = content.replace(old_str, new_str)
old_str = '#SBATCH --job-name='+task_name
new_str = '#SBATCH --job-name='+task_name+'_'+str(index)
content = content.replace(old_str, new_str)
with open(sh_filename+'_'+str(index)+'.sh', 'w') as f:
f.write(content)
# sbatch task
os.system('sbatch '+new_file)
copy_py_sh_file_and_bsub_taskcopy_py_sh_file_and_bsub_task(parameter_array, py_filename='a', old_str_in_py='parameter = 0', new_str_in_py='parameter = ', sh_filename='a', task_name='task')
复制.py和.sh文件,然后提交任务,实现半手动并行(LSF)
| 参数 | 类型 | 默认值 |
|---|---|---|
parameter_array | 必填 | |
py_filename | 'a' | |
old_str_in_py | 'parameter = 0' | |
new_str_in_py | 'parameter = ' | |
sh_filename | 'a' | |
task_name | 'task' |
def copy_py_sh_file_and_bsub_task(parameter_array, py_filename='a', old_str_in_py='parameter = 0', new_str_in_py='parameter = ', sh_filename='a', task_name='task'):
import os
parameter_str_array = []
for i0 in parameter_array:
parameter_str_array.append(str(i0))
index = 0
for parameter_str in parameter_str_array:
index += 1
# copy python file
old_file = py_filename+'.py'
new_file = py_filename+'_'+str(index)+'.py'
os.system('cp '+old_file+' '+new_file)
with open(new_file, 'r') as f:
content = f.read()
old_str = old_str_in_py
new_str = new_str_in_py+parameter_str
content = content.replace(old_str, new_str)
with open(py_filename+'_'+str(index)+'.py', 'w') as f:
f.write(content)
# copy sh file
old_file = sh_filename+'.sh'
new_file = sh_filename+'_'+str(index)+'.sh'
os.system('cp '+old_file+' '+new_file)
with open(new_file, 'r') as f:
content = f.read()
old_str = 'python '+py_filename+'.py'
new_str = 'python '+py_filename+'_'+str(index)+'.py'
content = content.replace(old_str, new_str)
old_str = '#BSUB -J '+task_name
new_str = '#BSUB -J '+task_name+'_'+str(index)
content = content.replace(old_str, new_str)
with open(sh_filename+'_'+str(index)+'.sh', 'w') as f:
f.write(content)
# bsub task
os.system('bsub < '+new_file)
write_matrix_in_markdown_formatwrite_matrix_in_markdown_format(matrix, filename='a')
把矩阵写入.md文件(Markdown表格形式)
| 参数 | 类型 | 默认值 |
|---|---|---|
matrix | 必填 | |
filename | 'a' |
def write_matrix_in_markdown_format(matrix, filename='a'):
import numpy as np
matrix = np.array(matrix)
dim_0 = matrix.shape[0]
dim_1 = matrix.shape[1]
with open(filename+'.md', 'w', encoding='UTF-8') as f:
f.write(f'| Row\Column ')
for i1 in range(dim_1):
f.write(f'| column {i1+1} ')
f.write('|\n')
for i1 in range(dim_1+1):
f.write('| :---: ')
f.write('|\n')
for i0 in range(dim_0):
f.write(f'| row {i0+1} ')
for i1 in range(dim_1):
f.write(f'| {matrix[i0, i1]} ')
f.write('|\n')
write_matrix_in_latex_formatwrite_matrix_in_latex_format(matrix, filename='a', format='bmatrix')
把矩阵写入.md文件(Latex形式)
| 参数 | 类型 | 默认值 |
|---|---|---|
matrix | 必填 | |
filename | 'a' | |
format | 'bmatrix' |
def write_matrix_in_latex_format(matrix, filename='a', format='bmatrix'):
import numpy as np
matrix = np.array(matrix)
dim_0 = matrix.shape[0]
dim_1 = matrix.shape[1]
with open(filename+'.md', 'w', encoding='UTF-8') as f:
f.write(f'$$\\begin{{{format}}}\n')
for i0 in range(dim_0):
for i1 in range(dim_1):
if i1 != dim_1-1:
f.write(f'{matrix[i0, i1]} & ')
else:
f.write(f'{matrix[i0, i1]} \\\\\n')
f.write(f'\\end{{{format}}}$$')
make_directorymake_directory(directory='./test')
如果不存在文件夹,则新建文件夹
| 参数 | 类型 | 默认值 |
|---|---|---|
directory | './test' |
def make_directory(directory='./test'):
import os
if not os.path.exists(directory):
os.makedirs(directory)
make_filemake_file(file_path='./a.txt')
如果不存在文件,则新建空文件
| 参数 | 类型 | 默认值 |
|---|---|---|
file_path | './a.txt' |
def make_file(file_path='./a.txt'):
import os
if not os.path.exists(file_path):
with open(file_path, 'w', encoding='UTF-8') as f:
pass
open_fileopen_file(filename='a', file_format='.txt', mode='add')
打开文件用于写入,默认为新增内容
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 'a' | |
file_format | '.txt' | |
mode | 'add' |
def open_file(filename='a', file_format='.txt', mode='add'):
if mode == 'add':
f = open(filename+file_format, 'a', encoding='UTF-8')
elif mode == 'overwrite':
f = open(filename+file_format, 'w', encoding='UTF-8')
return f
print_to_fileprint_to_file(*args, filename='print_result', file_format='.txt', print_on=True)
打印到TXT文件(补充内容)
| 参数 | 类型 | 默认值 |
|---|---|---|
*args | 必填 | |
filename | 'print_result' | |
file_format | '.txt' | |
print_on | True |
def print_to_file(*args, filename='print_result', file_format='.txt', print_on=True):
if print_on==True:
for arg in args:
print(arg, end=' ')
print()
f = open(filename+file_format, 'a', encoding='UTF-8')
for arg in args:
f.write(str(arg)+' ')
f.write('\n')
f.close()
write_text_filewrite_text_file(content, filename='a', file_format='.txt')
写入到文本文件(覆盖内容)
| 参数 | 类型 | 默认值 |
|---|---|---|
content | 必填 | |
filename | 'a' | |
file_format | '.txt' |
def write_text_file(content, filename='a', file_format='.txt'):
with open(filename+file_format, 'w', encoding='UTF-8') as f:
f.write(content)
read_text_fileread_text_file(file_path='./a.txt', make_file=None)
读取文本文件内容(如果文件不存在,返回空字符串)
| 参数 | 类型 | 默认值 |
|---|---|---|
file_path | './a.txt' | |
make_file | None |
def read_text_file(file_path='./a.txt', make_file=None):
import os
if not os.path.exists(file_path):
if make_file != None:
with open(file_path, 'w', encoding='UTF-8') as f:
pass
return ''
else:
with open(file_path, 'r', encoding='UTF-8') as f:
content = f.read()
return content
get_all_directories_in_current_directoryget_all_directories_in_current_directory(current_directory='./')
获取当前文件夹中的所有子文件夹名
| 参数 | 类型 | 默认值 |
|---|---|---|
current_directory | './' |
def get_all_directories_in_current_directory(current_directory='./'):
import os
all_items = os.listdir(current_directory)
directories = [item for item in all_items if os.path.isdir(os.path.join(current_directory, item))]
return directories
get_all_filenames_in_directoryget_all_filenames_in_directory(directory='./', file_format=None, show_root_path=0, sort=1, include_subdirectory=1)
获取目录中的所有文件名
| 参数 | 类型 | 默认值 |
|---|---|---|
directory | './' | |
file_format | None | |
show_root_path | 0 | |
sort | 1 | |
include_subdirectory | 1 |
def get_all_filenames_in_directory(directory='./', file_format=None, show_root_path=0, sort=1, include_subdirectory=1):
import os
file_list = []
for root, dirs, files in os.walk(directory):
for i0 in range(len(files)):
if file_format == None:
if show_root_path == 0:
file_list.append(files[i0])
else:
file_list.append(root+'/'+files[i0])
else:
if file_format in files[i0]:
if show_root_path == 0:
file_list.append(files[i0])
else:
file_list.append(root+'/'+files[i0])
if include_subdirectory != 1:
break
if sort == 1:
file_list = sorted(file_list)
return file_list
read_text_files_in_directoryread_text_files_in_directory(directory='./', file_format='.md')
获取文件夹中某种文本类型的文件以及读取所有内容
| 参数 | 类型 | 默认值 |
|---|---|---|
directory | './' | |
file_format | '.md' |
def read_text_files_in_directory(directory='./', file_format='.md'):
import os
file_list = []
for root, dirs, files in os.walk(directory):
for i0 in range(len(files)):
if file_format in files[i0]:
file_list.append(root+'/'+files[i0])
content_array = []
for file in file_list:
with open(file, 'r', encoding='UTF-8') as f:
content_array.append(f.read())
return file_list, content_array
find_words_in_multiple_filesfind_words_in_multiple_files(words, directory='./', file_format='.md')
在多个文本文件中查找关键词
| 参数 | 类型 | 默认值 |
|---|---|---|
words | 必填 | |
directory | './' | |
file_format | '.md' |
调用了:guan.read_text_files_in_directory
def find_words_in_multiple_files(words, directory='./', file_format='.md'):
import guan
file_list, content_array = guan.read_text_files_in_directory(directory=directory, file_format=file_format)
num_files = len(file_list)
file_list_with_words = []
for i0 in range(num_files):
if words in content_array[i0]:
file_list_with_words.append(file_list[i0])
return file_list_with_words
copy_filecopy_file(old_file='./a.txt', new_file='./b.txt')
复制一份文件
| 参数 | 类型 | 默认值 |
|---|---|---|
old_file | './a.txt' | |
new_file | './b.txt' |
def copy_file(old_file='./a.txt', new_file='./b.txt'):
import shutil
shutil.copy(old_file, new_file)
open_file_and_replace_stropen_file_and_replace_str(file_path='./a.txt', old_str='', new_str='')
打开文件,替代某字符串
| 参数 | 类型 | 默认值 |
|---|---|---|
file_path | './a.txt' | |
old_str | '' | |
new_str | '' |
调用了:guan.read_text_file, guan.open_file
def open_file_and_replace_str(file_path='./a.txt', old_str='', new_str=''):
import guan
content = guan.read_text_file(file_path=file_path)
content = content.replace(old_str, new_str)
f = guan.open_file(filename=file_path, file_format='', mode='overwrite')
f.write(content)
f.close()
copy_file_and_replace_strcopy_file_and_replace_str(old_file='./a.txt', new_file='./b.txt', old_str='', new_str='')
复制一份文件,然后再替代某字符串
| 参数 | 类型 | 默认值 |
|---|---|---|
old_file | './a.txt' | |
new_file | './b.txt' | |
old_str | '' | |
new_str | '' |
调用了:guan.copy_file, guan.read_text_file, guan.open_file
def copy_file_and_replace_str(old_file='./a.txt', new_file='./b.txt', old_str='', new_str=''):
import guan
guan.copy_file(old_file=old_file, new_file=new_file)
content = guan.read_text_file(file_path=new_file)
content = content.replace(old_str, new_str)
f = guan.open_file(filename=new_file, file_format='', mode='overwrite')
f.write(content)
f.close()
change_directory_by_replacementchange_directory_by_replacement(current_key_word='code', new_key_word='data')
改变当前的目录位置
| 参数 | 类型 | 默认值 |
|---|---|---|
current_key_word | 'code' | |
new_key_word | 'data' |
def change_directory_by_replacement(current_key_word='code', new_key_word='data'):
import os
code_path = os.getcwd()
data_path = code_path.replace('\\', '/')
data_path = data_path.replace(current_key_word, new_key_word)
if os.path.exists(data_path) == False:
os.makedirs(data_path)
os.chdir(data_path)
find_repeated_file_with_same_filenamefind_repeated_file_with_same_filename(directory='./', ignored_directory_with_words=[], ignored_file_with_words=[], num=1000)
查找文件名相同的文件
| 参数 | 类型 | 默认值 |
|---|---|---|
directory | './' | |
ignored_directory_with_words | [] | |
ignored_file_with_words | [] | |
num | 1000 |
def find_repeated_file_with_same_filename(directory='./', ignored_directory_with_words=[], ignored_file_with_words=[], num=1000):
import os
from collections import Counter
file_list = []
for root, dirs, files in os.walk(directory):
for i0 in range(len(files)):
file_list.append(files[i0])
for word in ignored_directory_with_words:
if word in root:
file_list.remove(files[i0])
for word in ignored_file_with_words:
if word in files[i0]:
try:
file_list.remove(files[i0])
except:
pass
count_file = Counter(file_list).most_common(num)
repeated_file = []
for item in count_file:
if item[1]>1:
repeated_file.append(item)
return repeated_file
count_file_in_sub_directorycount_file_in_sub_directory(directory='./', sort=0, reverse=1, print_show=1, smaller_than_num=None)
统计各个子文件夹中的文件数量
| 参数 | 类型 | 默认值 |
|---|---|---|
directory | './' | |
sort | 0 | |
reverse | 1 | |
print_show | 1 | |
smaller_than_num | None |
def count_file_in_sub_directory(directory='./', sort=0, reverse=1, print_show=1, smaller_than_num=None):
import os
import numpy as np
dirs_list = []
for root, dirs, files in os.walk(directory):
if dirs != []:
for i0 in range(len(dirs)):
dirs_list.append(root+'/'+dirs[i0])
count_file_array = []
for sub_dir in dirs_list:
file_list = []
for root, dirs, files in os.walk(sub_dir):
for i0 in range(len(files)):
file_list.append(files[i0])
count_file = len(file_list)
count_file_array.append(count_file)
if sort == 0:
if print_show == 1:
if smaller_than_num == None:
print(sub_dir)
print(count_file)
print()
else:
if count_file<smaller_than_num:
print(sub_dir)
print(count_file)
print()
if sort == 0:
sub_directory = dirs_list
num_in_sub_directory = count_file_array
if sort == 1:
sub_directory = []
num_in_sub_directory = []
if reverse == 1:
index_array = np.argsort(count_file_array)[::-1]
else:
index_array = np.argsort(count_file_array)
for i0 in index_array:
sub_directory.append(dirs_list[i0])
num_in_sub_directory.append(count_file_array[i0])
if print_show == 1:
if smaller_than_num == None:
print(dirs_list[i0])
print(count_file_array[i0])
print()
else:
if count_file_array[i0]<smaller_than_num:
print(dirs_list[i0])
print(count_file_array[i0])
print()
return sub_directory, num_in_sub_directory
creat_necessary_filecreat_necessary_file(directory, filename='readme', file_format='.md', content='', overwrite=None, ignored_directory_with_words=[])
在多个子文件夹中产生必要的文件,例如 readme.md
| 参数 | 类型 | 默认值 |
|---|---|---|
directory | 必填 | |
filename | 'readme' | |
file_format | '.md' | |
content | '' | |
overwrite | None | |
ignored_directory_with_words | [] |
def creat_necessary_file(directory, filename='readme', file_format='.md', content='', overwrite=None, ignored_directory_with_words=[]):
import os
directory_with_file = []
ignored_directory = []
for root, dirs, files in os.walk(directory):
for i0 in range(len(files)):
if root not in directory_with_file:
directory_with_file.append(root)
if files[i0] == filename+file_format:
if root not in ignored_directory:
ignored_directory.append(root)
if overwrite == None:
for root in ignored_directory:
directory_with_file.remove(root)
ignored_directory_more =[]
for root in directory_with_file:
for word in ignored_directory_with_words:
if word in root:
if root not in ignored_directory_more:
ignored_directory_more.append(root)
for root in ignored_directory_more:
directory_with_file.remove(root)
for root in directory_with_file:
os.chdir(root)
f = open(filename+file_format, 'w', encoding="utf-8")
f.write(content)
f.close()
delete_file_with_specific_namedelete_file_with_specific_name(directory, filename='readme', file_format='.md')
删除特定文件名的文件(谨慎使用)
| 参数 | 类型 | 默认值 |
|---|---|---|
directory | 必填 | |
filename | 'readme' | |
file_format | '.md' |
def delete_file_with_specific_name(directory, filename='readme', file_format='.md'):
import os
for root, dirs, files in os.walk(directory):
for i0 in range(len(files)):
if files[i0] == filename+file_format:
os.remove(root+'/'+files[i0])
move_all_files_to_root_directorymove_all_files_to_root_directory(directory)
将所有文件移到根目录(谨慎使用)
| 参数 | 类型 | 默认值 |
|---|---|---|
directory | 必填 |
def move_all_files_to_root_directory(directory):
import os
import shutil
for root, dirs, files in os.walk(directory):
for i0 in range(len(files)):
shutil.move(root+'/'+files[i0], directory+'/'+files[i0])
for i0 in range(100):
for root, dirs, files in os.walk(directory):
try:
os.rmdir(root)
except:
pass
import_plt_and_start_fig_aximport_plt_and_start_fig_ax(adjust_bottom=0.2, adjust_left=0.2, labelsize=20, fontfamily='Times New Roman')
导入plt, fig, ax
| 参数 | 类型 | 默认值 |
|---|---|---|
adjust_bottom | 0.2 | |
adjust_left | 0.2 | |
labelsize | 20 | |
fontfamily | 'Times New Roman' |
def import_plt_and_start_fig_ax(adjust_bottom=0.2, adjust_left=0.2, labelsize=20, fontfamily='Times New Roman'):
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=adjust_bottom, left=adjust_left)
ax.grid()
ax.tick_params(labelsize=labelsize)
if fontfamily=='Times New Roman':
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
return plt, fig, ax
import_plt_and_start_fig_ax_without_axisimport_plt_and_start_fig_ax_without_axis()
导入plt, fig, ax(不显示坐标)
def import_plt_and_start_fig_ax_without_axis():
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.subplots_adjust(left=0, bottom=0, right=1, top=1)
plt.axis('off')
return plt, fig, ax
savefig_with_all_formatssavefig_with_all_formats(plt, filename, more_dpi=1, tiff=0)
保存图片为所有常见的格式
| 参数 | 类型 | 默认值 |
|---|---|---|
plt | 必填 | |
filename | 必填 | |
more_dpi | 1 | |
tiff | 0 |
def savefig_with_all_formats(plt, filename, more_dpi=1, tiff=0):
plt.savefig(filename+'.eps')
plt.savefig(filename+'.svg')
plt.savefig(filename+'.pdf')
plt.savefig(filename+'.jpg')
plt.savefig(filename+'.png')
if tiff:
plt.savefig(filename+'.tiff')
if more_dpi:
try:
plt.savefig(filename+'_dpi=300.jpg', dpi=300)
plt.savefig(filename+'_dpi=600.jpg', dpi=600)
plt.savefig(filename+'_dpi=1000.jpg', dpi=1000)
plt.savefig(filename+'_dpi=300.png', dpi=300)
plt.savefig(filename+'_dpi=600.png', dpi=600)
plt.savefig(filename+'_dpi=1000.png', dpi=1000)
if tiff:
plt.savefig(filename+'_dpi=300.tiff', dpi=300)
plt.savefig(filename+'_dpi=600.tiff', dpi=600)
plt.savefig(filename+'_dpi=1000.tiff', dpi=1000)
except:
pass
plot_without_starting_fig_axplot_without_starting_fig_ax(plt, fig, ax, x_array, y_array, xlabel='x', ylabel='y', title='', fontsize=20, style='', y_min=None, y_max=None, linewidth=None, markersize=None, color=None, fontfamily='Times New Roman')
基于plt, fig, ax画图
| 参数 | 类型 | 默认值 |
|---|---|---|
plt | 必填 | |
fig | 必填 | |
ax | 必填 | |
x_array | 必填 | |
y_array | 必填 | |
xlabel | 'x' | |
ylabel | 'y' | |
title | '' | |
fontsize | 20 | |
style | '' | |
y_min | None | |
y_max | None | |
linewidth | None | |
markersize | None | |
color | None | |
fontfamily | 'Times New Roman' |
def plot_without_starting_fig_ax(plt, fig, ax, x_array, y_array, xlabel='x', ylabel='y', title='', fontsize=20, style='', y_min=None, y_max=None, linewidth=None, markersize=None, color=None, fontfamily='Times New Roman'):
if color==None:
ax.plot(x_array, y_array, style, linewidth=linewidth, markersize=markersize)
else:
ax.plot(x_array, y_array, style, linewidth=linewidth, markersize=markersize, color=color)
if fontfamily=='Times New Roman':
ax.set_title(title, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=fontsize, fontfamily='Times New Roman')
else:
ax.set_title(title, fontsize=fontsize)
ax.set_xlabel(xlabel, fontsize=fontsize)
ax.set_ylabel(ylabel, fontsize=fontsize)
if y_min!=None or y_max!=None:
if y_min==None:
y_min=min(y_array)
if y_max==None:
y_max=max(y_array)
ax.set_ylim(y_min, y_max)
plotplot(x_array, y_array, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=20, show=1, save=0, filename='a', file_format='.jpg', dpi=300, style='', y_min=None, y_max=None, linewidth=None, markersize=None, adjust_bottom=0.2, adjust_left=0.2, fontfamily='Times New Roman')
画图
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
xlabel | 'x' | |
ylabel | 'y' | |
title | '' | |
fontsize | 20 | |
labelsize | 20 | |
show | 1 | |
save | 0 | |
filename | 'a' | |
file_format | '.jpg' | |
dpi | 300 | |
style | '' | |
y_min | None | |
y_max | None | |
linewidth | None | |
markersize | None | |
adjust_bottom | 0.2 | |
adjust_left | 0.2 | |
fontfamily | 'Times New Roman' |
调用了:guan.import_plt_and_start_fig_ax
def plot(x_array, y_array, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=20, show=1, save=0, filename='a', file_format='.jpg', dpi=300, style='', y_min=None, y_max=None, linewidth=None, markersize=None, adjust_bottom=0.2, adjust_left=0.2, fontfamily='Times New Roman'):
import guan
plt, fig, ax = guan.import_plt_and_start_fig_ax(adjust_bottom=adjust_bottom, adjust_left=adjust_left, labelsize=labelsize, fontfamily=fontfamily)
ax.plot(x_array, y_array, style, linewidth=linewidth, markersize=markersize)
if fontfamily=='Times New Roman':
ax.set_title(title, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=fontsize, fontfamily='Times New Roman')
else:
ax.set_title(title, fontsize=fontsize)
ax.set_xlabel(xlabel, fontsize=fontsize)
ax.set_ylabel(ylabel, fontsize=fontsize)
if y_min!=None or y_max!=None:
if y_min==None:
y_min=min(y_array)
if y_max==None:
y_max=max(y_array)
ax.set_ylim(y_min, y_max)
if save == 1:
plt.savefig(filename+file_format, dpi=dpi)
if show == 1:
plt.show()
plt.close('all')
plot_two_arrayplot_two_array(x_array, y1_array, y2_array, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=20, show=1, save=0, filename='a', file_format='.jpg', dpi=300, style_1='', style_2='', y_min=None, y_max=None, linewidth_1=None, linewidth_2=None, markersize_1=None, markersize_2=None, adjust_bottom=0.2, adjust_left=0.2, fontfamily='Times New Roman')
一组横坐标数据,两组纵坐标数据画图
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y1_array | 必填 | |
y2_array | 必填 | |
xlabel | 'x' | |
ylabel | 'y' | |
title | '' | |
fontsize | 20 | |
labelsize | 20 | |
show | 1 | |
save | 0 | |
filename | 'a' | |
file_format | '.jpg' | |
dpi | 300 | |
style_1 | '' | |
style_2 | '' | |
y_min | None | |
y_max | None | |
linewidth_1 | None | |
linewidth_2 | None | |
markersize_1 | None | |
markersize_2 | None | |
adjust_bottom | 0.2 | |
adjust_left | 0.2 | |
fontfamily | 'Times New Roman' |
调用了:guan.import_plt_and_start_fig_ax
def plot_two_array(x_array, y1_array, y2_array, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=20, show=1, save=0, filename='a', file_format='.jpg', dpi=300, style_1='', style_2='', y_min=None, y_max=None, linewidth_1=None, linewidth_2=None, markersize_1=None, markersize_2=None, adjust_bottom=0.2, adjust_left=0.2, fontfamily='Times New Roman'):
import guan
plt, fig, ax = guan.import_plt_and_start_fig_ax(adjust_bottom=adjust_bottom, adjust_left=adjust_left, labelsize=labelsize, fontfamily=fontfamily)
ax.plot(x_array, y1_array, style_1, linewidth=linewidth_1, markersize=markersize_1)
ax.plot(x_array, y2_array, style_2, linewidth=linewidth_2, markersize=markersize_2)
if fontfamily=='Times New Roman':
ax.set_title(title, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=fontsize, fontfamily='Times New Roman')
else:
ax.set_title(title, fontsize=fontsize)
ax.set_xlabel(xlabel, fontsize=fontsize)
ax.set_ylabel(ylabel, fontsize=fontsize)
if y_min!=None or y_max!=None:
if y_min==None:
y1_min=min(y1_array)
y2_min=min(y2_array)
y_min=min([y1_min, y2_min])
if y_max==None:
y1_max=max(y1_array)
y2_max=max(y2_array)
y_max=max([y1_max, y2_max])
ax.set_ylim(y_min, y_max)
if save == 1:
plt.savefig(filename+file_format, dpi=dpi)
if show == 1:
plt.show()
plt.close('all')
plot_two_array_with_two_horizontal_arrayplot_two_array_with_two_horizontal_array(x1_array, x2_array, y1_array, y2_array, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=20, show=1, save=0, filename='a', file_format='.jpg', dpi=300, style_1='', style_2='', y_min=None, y_max=None, linewidth_1=None, linewidth_2=None, markersize_1=None, markersize_2=None, adjust_bottom=0.2, adjust_left=0.2, fontfamily='Times New Roman')
两组横坐标数据,两组纵坐标数据画图
| 参数 | 类型 | 默认值 |
|---|---|---|
x1_array | 必填 | |
x2_array | 必填 | |
y1_array | 必填 | |
y2_array | 必填 | |
xlabel | 'x' | |
ylabel | 'y' | |
title | '' | |
fontsize | 20 | |
labelsize | 20 | |
show | 1 | |
save | 0 | |
filename | 'a' | |
file_format | '.jpg' | |
dpi | 300 | |
style_1 | '' | |
style_2 | '' | |
y_min | None | |
y_max | None | |
linewidth_1 | None | |
linewidth_2 | None | |
markersize_1 | None | |
markersize_2 | None | |
adjust_bottom | 0.2 | |
adjust_left | 0.2 | |
fontfamily | 'Times New Roman' |
调用了:guan.import_plt_and_start_fig_ax
def plot_two_array_with_two_horizontal_array(x1_array, x2_array, y1_array, y2_array, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=20, show=1, save=0, filename='a', file_format='.jpg', dpi=300, style_1='', style_2='', y_min=None, y_max=None, linewidth_1=None, linewidth_2=None, markersize_1=None, markersize_2=None, adjust_bottom=0.2, adjust_left=0.2, fontfamily='Times New Roman'):
import guan
plt, fig, ax = guan.import_plt_and_start_fig_ax(adjust_bottom=adjust_bottom, adjust_left=adjust_left, labelsize=labelsize, fontfamily=fontfamily)
ax.plot(x1_array, y1_array, style_1, linewidth=linewidth_1, markersize=markersize_1)
ax.plot(x2_array, y2_array, style_2, linewidth=linewidth_2, markersize=markersize_2)
if fontfamily=='Times New Roman':
ax.set_title(title, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=fontsize, fontfamily='Times New Roman')
else:
ax.set_title(title, fontsize=fontsize)
ax.set_xlabel(xlabel, fontsize=fontsize)
ax.set_ylabel(ylabel, fontsize=fontsize)
if y_min!=None or y_max!=None:
if y_min==None:
y1_min=min(y1_array)
y2_min=min(y2_array)
y_min=min([y1_min, y2_min])
if y_max==None:
y1_max=max(y1_array)
y2_max=max(y2_array)
y_max=max([y1_max, y2_max])
ax.set_ylim(y_min, y_max)
if save == 1:
plt.savefig(filename+file_format, dpi=dpi)
if show == 1:
plt.show()
plt.close('all')
plot_three_arrayplot_three_array(x_array, y1_array, y2_array, y3_array, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=20, show=1, save=0, filename='a', file_format='.jpg', dpi=300, style_1='', style_2='', style_3='', y_min=None, y_max=None, linewidth_1=None, linewidth_2=None, linewidth_3=None, markersize_1=None, markersize_2=None, markersize_3=None, adjust_bottom=0.2, adjust_left=0.2, fontfamily='Times New Roman')
一组横坐标数据,三组纵坐标数据画图
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y1_array | 必填 | |
y2_array | 必填 | |
y3_array | 必填 | |
xlabel | 'x' | |
ylabel | 'y' | |
title | '' | |
fontsize | 20 | |
labelsize | 20 | |
show | 1 | |
save | 0 | |
filename | 'a' | |
file_format | '.jpg' | |
dpi | 300 | |
style_1 | '' | |
style_2 | '' | |
style_3 | '' | |
y_min | None | |
y_max | None | |
linewidth_1 | None | |
linewidth_2 | None | |
linewidth_3 | None | |
markersize_1 | None | |
markersize_2 | None | |
markersize_3 | None | |
adjust_bottom | 0.2 | |
adjust_left | 0.2 | |
fontfamily | 'Times New Roman' |
调用了:guan.import_plt_and_start_fig_ax
def plot_three_array(x_array, y1_array, y2_array, y3_array, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=20, show=1, save=0, filename='a', file_format='.jpg', dpi=300, style_1='', style_2='', style_3='', y_min=None, y_max=None, linewidth_1=None, linewidth_2=None, linewidth_3=None,markersize_1=None, markersize_2=None, markersize_3=None, adjust_bottom=0.2, adjust_left=0.2, fontfamily='Times New Roman'):
import guan
plt, fig, ax = guan.import_plt_and_start_fig_ax(adjust_bottom=adjust_bottom, adjust_left=adjust_left, labelsize=labelsize, fontfamily=fontfamily)
ax.plot(x_array, y1_array, style_1, linewidth=linewidth_1, markersize=markersize_1)
ax.plot(x_array, y2_array, style_2, linewidth=linewidth_2, markersize=markersize_2)
ax.plot(x_array, y3_array, style_3, linewidth=linewidth_3, markersize=markersize_3)
if fontfamily=='Times New Roman':
ax.set_title(title, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=fontsize, fontfamily='Times New Roman')
else:
ax.set_title(title, fontsize=fontsize)
ax.set_xlabel(xlabel, fontsize=fontsize)
ax.set_ylabel(ylabel, fontsize=fontsize)
if y_min!=None or y_max!=None:
if y_min==None:
y1_min=min(y1_array)
y2_min=min(y2_array)
y3_min=min(y3_array)
y_min=min([y1_min, y2_min, y3_min])
if y_max==None:
y1_max=max(y1_array)
y2_max=max(y2_array)
y3_max=max(y3_array)
y_max=max([y1_max, y2_max, y3_max])
ax.set_ylim(y_min, y_max)
if save == 1:
plt.savefig(filename+file_format, dpi=dpi)
if show == 1:
plt.show()
plt.close('all')
plot_three_array_with_three_horizontal_arrayplot_three_array_with_three_horizontal_array(x1_array, x2_array, x3_array, y1_array, y2_array, y3_array, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=20, show=1, save=0, filename='a', file_format='.jpg', dpi=300, style_1='', style_2='', style_3='', y_min=None, y_max=None, linewidth_1=None, linewidth_2=None, linewidth_3=None, markersize_1=None, markersize_2=None, markersize_3=None, adjust_bottom=0.2, adjust_left=0.2, fontfamily='Times New Roman')
三组横坐标数据,三组纵坐标数据画图
| 参数 | 类型 | 默认值 |
|---|---|---|
x1_array | 必填 | |
x2_array | 必填 | |
x3_array | 必填 | |
y1_array | 必填 | |
y2_array | 必填 | |
y3_array | 必填 | |
xlabel | 'x' | |
ylabel | 'y' | |
title | '' | |
fontsize | 20 | |
labelsize | 20 | |
show | 1 | |
save | 0 | |
filename | 'a' | |
file_format | '.jpg' | |
dpi | 300 | |
style_1 | '' | |
style_2 | '' | |
style_3 | '' | |
y_min | None | |
y_max | None | |
linewidth_1 | None | |
linewidth_2 | None | |
linewidth_3 | None | |
markersize_1 | None | |
markersize_2 | None | |
markersize_3 | None | |
adjust_bottom | 0.2 | |
adjust_left | 0.2 | |
fontfamily | 'Times New Roman' |
调用了:guan.import_plt_and_start_fig_ax
def plot_three_array_with_three_horizontal_array(x1_array, x2_array, x3_array, y1_array, y2_array, y3_array, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=20, show=1, save=0, filename='a', file_format='.jpg', dpi=300, style_1='', style_2='', style_3='', y_min=None, y_max=None, linewidth_1=None, linewidth_2=None, linewidth_3=None,markersize_1=None, markersize_2=None, markersize_3=None, adjust_bottom=0.2, adjust_left=0.2, fontfamily='Times New Roman'):
import guan
plt, fig, ax = guan.import_plt_and_start_fig_ax(adjust_bottom=adjust_bottom, adjust_left=adjust_left, labelsize=labelsize, fontfamily=fontfamily)
ax.plot(x1_array, y1_array, style_1, linewidth=linewidth_1, markersize=markersize_1)
ax.plot(x2_array, y2_array, style_2, linewidth=linewidth_2, markersize=markersize_2)
ax.plot(x3_array, y3_array, style_3, linewidth=linewidth_3, markersize=markersize_3)
if fontfamily=='Times New Roman':
ax.set_title(title, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=fontsize, fontfamily='Times New Roman')
else:
ax.set_title(title, fontsize=fontsize)
ax.set_xlabel(xlabel, fontsize=fontsize)
ax.set_ylabel(ylabel, fontsize=fontsize)
if y_min!=None or y_max!=None:
if y_min==None:
y1_min=min(y1_array)
y2_min=min(y2_array)
y3_min=min(y3_array)
y_min=min([y1_min, y2_min, y3_min])
if y_max==None:
y1_max=max(y1_array)
y2_max=max(y2_array)
y3_max=max(y3_array)
y_max=max([y1_max, y2_max, y3_max])
ax.set_ylim(y_min, y_max)
if save == 1:
plt.savefig(filename+file_format, dpi=dpi)
if show == 1:
plt.show()
plt.close('all')
plot_3d_surfaceplot_3d_surface(x_array, y_array, matrix, xlabel='x', ylabel='y', zlabel='z', title='', fontsize=20, labelsize=15, show=1, save=0, filename='a', file_format='.jpg', dpi=300, z_min=None, z_max=None, rcount=100, ccount=100, fontfamily='Times New Roman')
画三维图
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
matrix | 必填 | |
xlabel | 'x' | |
ylabel | 'y' | |
zlabel | 'z' | |
title | '' | |
fontsize | 20 | |
labelsize | 15 | |
show | 1 | |
save | 0 | |
filename | 'a' | |
file_format | '.jpg' | |
dpi | 300 | |
z_min | None | |
z_max | None | |
rcount | 100 | |
ccount | 100 | |
fontfamily | 'Times New Roman' |
def plot_3d_surface(x_array, y_array, matrix, xlabel='x', ylabel='y', zlabel='z', title='', fontsize=20, labelsize=15, show=1, save=0, filename='a', file_format='.jpg', dpi=300, z_min=None, z_max=None, rcount=100, ccount=100, fontfamily='Times New Roman'):
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator
matrix = np.array(matrix)
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
plt.subplots_adjust(bottom=0.1, right=0.65)
x_array, y_array = np.meshgrid(x_array, y_array)
if len(matrix.shape) == 2:
surf = ax.plot_surface(x_array, y_array, matrix, rcount=rcount, ccount=ccount, cmap=cm.coolwarm, linewidth=0, antialiased=False)
elif len(matrix.shape) == 3:
for i0 in range(matrix.shape[2]):
surf = ax.plot_surface(x_array, y_array, matrix[:,:,i0], rcount=rcount, ccount=ccount, cmap=cm.coolwarm, linewidth=0, antialiased=False)
if fontfamily=='Times New Roman':
ax.set_title(title, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_zlabel(zlabel, fontsize=fontsize, fontfamily='Times New Roman')
else:
ax.set_title(title, fontsize=fontsize)
ax.set_xlabel(xlabel, fontsize=fontsize)
ax.set_ylabel(ylabel, fontsize=fontsize)
ax.set_zlabel(zlabel, fontsize=fontsize)
ax.zaxis.set_major_locator(LinearLocator(5))
ax.zaxis.set_major_formatter('{x:.2f}')
if z_min!=None or z_max!=None:
if z_min==None:
z_min=matrix.min()
if z_max==None:
z_max=matrix.max()
ax.set_zlim(z_min, z_max)
ax.tick_params(labelsize=labelsize)
if fontfamily=='Times New Roman':
labels = ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()
[label.set_fontname('Times New Roman') for label in labels]
cax = plt.axes([0.8, 0.1, 0.05, 0.8])
cbar = fig.colorbar(surf, cax=cax)
cbar.ax.tick_params(labelsize=labelsize)
if fontfamily=='Times New Roman':
for l in cbar.ax.yaxis.get_ticklabels():
l.set_family('Times New Roman')
if save == 1:
plt.savefig(filename+file_format, dpi=dpi)
if show == 1:
plt.show()
plt.close('all')
plot_contourplot_contour(x_array, y_array, matrix, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=15, cmap='jet', levels=None, show=1, save=0, filename='a', file_format='.jpg', dpi=300, fontfamily='Times New Roman')
画Contour图
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
matrix | 必填 | |
xlabel | 'x' | |
ylabel | 'y' | |
title | '' | |
fontsize | 20 | |
labelsize | 15 | |
cmap | 'jet' | |
levels | None | |
show | 1 | |
save | 0 | |
filename | 'a' | |
file_format | '.jpg' | |
dpi | 300 | |
fontfamily | 'Times New Roman' |
def plot_contour(x_array, y_array, matrix, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=15, cmap='jet', levels=None, show=1, save=0, filename='a', file_format='.jpg', dpi=300, fontfamily='Times New Roman'):
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2, right=0.75, left=0.2)
x_array, y_array = np.meshgrid(x_array, y_array)
contour = ax.contourf(x_array,y_array,matrix,cmap=cmap, levels=levels)
if fontfamily=='Times New Roman':
ax.set_title(title, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=fontsize, fontfamily='Times New Roman')
else:
ax.set_title(title, fontsize=fontsize)
ax.set_xlabel(xlabel, fontsize=fontsize)
ax.set_ylabel(ylabel, fontsize=fontsize)
ax.tick_params(labelsize=labelsize)
if fontfamily=='Times New Roman':
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
cax = plt.axes([0.8, 0.2, 0.05, 0.68])
cbar = fig.colorbar(contour, cax=cax)
cbar.ax.tick_params(labelsize=labelsize)
if fontfamily=='Times New Roman':
for l in cbar.ax.yaxis.get_ticklabels():
l.set_family('Times New Roman')
if save == 1:
plt.savefig(filename+file_format, dpi=dpi)
if show == 1:
plt.show()
plt.close('all')
plot_pcolorplot_pcolor(x_array, y_array, matrix, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=15, cmap='jet', levels=None, show=1, save=0, filename='a', file_format='.jpg', dpi=300, fontfamily='Times New Roman')
画棋盘图/伪彩色图
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
matrix | 必填 | |
xlabel | 'x' | |
ylabel | 'y' | |
title | '' | |
fontsize | 20 | |
labelsize | 15 | |
cmap | 'jet' | |
levels | None | |
show | 1 | |
save | 0 | |
filename | 'a' | |
file_format | '.jpg' | |
dpi | 300 | |
fontfamily | 'Times New Roman' |
def plot_pcolor(x_array, y_array, matrix, xlabel='x', ylabel='y', title='', fontsize=20, labelsize=15, cmap='jet', levels=None, show=1, save=0, filename='a', file_format='.jpg', dpi=300, fontfamily='Times New Roman'):
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2, right=0.75, left=0.2)
x_array, y_array = np.meshgrid(x_array, y_array)
contour = ax.pcolor(x_array,y_array,matrix, cmap=cmap)
if fontfamily=='Times New Roman':
ax.set_title(title, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=fontsize, fontfamily='Times New Roman')
else:
ax.set_title(title, fontsize=fontsize)
ax.set_xlabel(xlabel, fontsize=fontsize)
ax.set_ylabel(ylabel, fontsize=fontsize)
ax.tick_params(labelsize=labelsize)
if fontfamily=='Times New Roman':
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
cax = plt.axes([0.8, 0.2, 0.05, 0.68])
cbar = fig.colorbar(contour, cax=cax)
cbar.ax.tick_params(labelsize=labelsize)
if fontfamily=='Times New Roman':
for l in cbar.ax.yaxis.get_ticklabels():
l.set_family('Times New Roman')
if save == 1:
plt.savefig(filename+file_format, dpi=dpi)
if show == 1:
plt.show()
plt.close('all')
draw_dots_and_lines_without_starting_fig_axdraw_dots_and_lines_without_starting_fig_ax(plt, fig, ax, coordinate_array, draw_dots=1, draw_lines=1, max_distance=1.0001, line_style='-k', linewidth=1, dot_style='ro', markersize=3)
基于plt, fig, ax,通过坐标画点和线
| 参数 | 类型 | 默认值 |
|---|---|---|
plt | 必填 | |
fig | 必填 | |
ax | 必填 | |
coordinate_array | 必填 | |
draw_dots | 1 | |
draw_lines | 1 | |
max_distance | 1.0001 | |
line_style | '-k' | |
linewidth | 1 | |
dot_style | 'ro' | |
markersize | 3 |
def draw_dots_and_lines_without_starting_fig_ax(plt, fig, ax, coordinate_array, draw_dots=1, draw_lines=1, max_distance=1.0001, line_style='-k', linewidth=1, dot_style='ro', markersize=3):
import numpy as np
coordinate_array = np.array(coordinate_array)
if draw_lines==1:
for i1 in range(coordinate_array.shape[0]):
for i2 in range(coordinate_array.shape[0]):
if i1<i2:
x1 = coordinate_array[i1, 0]
x2 = coordinate_array[i2, 0]
y1 = coordinate_array[i1, 1]
y2 = coordinate_array[i2, 1]
if abs(x1-x2)<=max_distance and abs(y1-y2)<=max_distance:
if np.sqrt((x1 - x2)**2+(y1 - y2)**2) <= max_distance:
ax.plot([x1, x2], [y1, y2], line_style, linewidth=linewidth)
if draw_dots==1:
ax.plot(coordinate_array[:, 0], coordinate_array[:, 1], dot_style, markersize=markersize)
draw_dots_and_linesdraw_dots_and_lines(coordinate_array, draw_dots=1, draw_lines=1, max_distance=1.0001, line_style='-k', linewidth=1, dot_style='ro', markersize=3, axis_off=1, show=1, save=0, filename='a', file_format='.eps', dpi=300)
通过坐标画点和线
| 参数 | 类型 | 默认值 |
|---|---|---|
coordinate_array | 必填 | |
draw_dots | 1 | |
draw_lines | 1 | |
max_distance | 1.0001 | |
line_style | '-k' | |
linewidth | 1 | |
dot_style | 'ro' | |
markersize | 3 | |
axis_off | 1 | |
show | 1 | |
save | 0 | |
filename | 'a' | |
file_format | '.eps' | |
dpi | 300 |
调用了:guan.draw_dots_and_lines_without_starting_fig_ax
def draw_dots_and_lines(coordinate_array, draw_dots=1, draw_lines=1, max_distance=1.0001, line_style='-k', linewidth=1, dot_style='ro', markersize=3, axis_off=1, show=1, save=0, filename='a', file_format='.eps', dpi=300):
import numpy as np
import matplotlib.pyplot as plt
import guan
coordinate_array = np.array(coordinate_array)
x_range = max(coordinate_array[:, 0])-min(coordinate_array[:, 0])
y_range = max(coordinate_array[:, 1])-min(coordinate_array[:, 1])
fig, ax = plt.subplots(figsize=(6*x_range/y_range,6))
ax.set_aspect('equal') # important code ensuring that the x and y axes have the same scale.
if axis_off==1:
plt.subplots_adjust(left=0, bottom=0, right=1, top=1)
plt.axis('off')
guan.draw_dots_and_lines_without_starting_fig_ax(plt, fig, ax, coordinate_array, draw_dots=draw_dots, draw_lines=draw_lines, max_distance=max_distance, line_style=line_style, linewidth=linewidth, dot_style=dot_style, markersize=markersize)
if show==1:
plt.show()
if save==1:
if file_format=='.eps':
plt.savefig(filename+file_format)
else:
plt.savefig(filename+file_format, dpi=dpi)
combine_two_imagescombine_two_images(image_path_array, figsize=(16, 8), show=0, save=1, filename='a', file_format='.jpg', dpi=300)
合并两个图片
| 参数 | 类型 | 默认值 |
|---|---|---|
image_path_array | 必填 | |
figsize | (16, 8) | |
show | 0 | |
save | 1 | |
filename | 'a' | |
file_format | '.jpg' | |
dpi | 300 |
def combine_two_images(image_path_array, figsize=(16,8), show=0, save=1, filename='a', file_format='.jpg', dpi=300):
import numpy as np
num = np.array(image_path_array).shape[0]
if num != 2:
print('Error: The number of images should be two!')
else:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
fig = plt.figure(figsize=figsize)
plt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=0, hspace=0)
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
image_1 = mpimg.imread(image_path_array[0])
image_2 = mpimg.imread(image_path_array[1])
ax1.imshow(image_1)
ax2.imshow(image_2)
ax1.axis('off')
ax2.axis('off')
if show == 1:
plt.show()
if save == 1:
plt.savefig(filename+file_format, dpi=dpi)
plt.close('all')
combine_three_imagescombine_three_images(image_path_array, figsize=(16, 5), show=0, save=1, filename='a', file_format='.jpg', dpi=300)
合并三个图片
| 参数 | 类型 | 默认值 |
|---|---|---|
image_path_array | 必填 | |
figsize | (16, 5) | |
show | 0 | |
save | 1 | |
filename | 'a' | |
file_format | '.jpg' | |
dpi | 300 |
def combine_three_images(image_path_array, figsize=(16,5), show=0, save=1, filename='a', file_format='.jpg', dpi=300):
import numpy as np
num = np.array(image_path_array).shape[0]
if num != 3:
print('Error: The number of images should be three!')
else:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
fig = plt.figure(figsize=figsize)
plt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=0, hspace=0)
ax1 = fig.add_subplot(131)
ax2 = fig.add_subplot(132)
ax3 = fig.add_subplot(133)
image_1 = mpimg.imread(image_path_array[0])
image_2 = mpimg.imread(image_path_array[1])
image_3 = mpimg.imread(image_path_array[2])
ax1.imshow(image_1)
ax2.imshow(image_2)
ax3.imshow(image_3)
ax1.axis('off')
ax2.axis('off')
ax3.axis('off')
if show == 1:
plt.show()
if save == 1:
plt.savefig(filename+file_format, dpi=dpi)
plt.close('all')
combine_four_imagescombine_four_images(image_path_array, figsize=(16, 16), show=0, save=1, filename='a', file_format='.jpg', dpi=300)
合并四个图片
| 参数 | 类型 | 默认值 |
|---|---|---|
image_path_array | 必填 | |
figsize | (16, 16) | |
show | 0 | |
save | 1 | |
filename | 'a' | |
file_format | '.jpg' | |
dpi | 300 |
def combine_four_images(image_path_array, figsize=(16,16), show=0, save=1, filename='a', file_format='.jpg', dpi=300):
import numpy as np
num = np.array(image_path_array).shape[0]
if num != 4:
print('Error: The number of images should be four!')
else:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
fig = plt.figure(figsize=figsize)
plt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=0, hspace=0)
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
image_1 = mpimg.imread(image_path_array[0])
image_2 = mpimg.imread(image_path_array[1])
image_3 = mpimg.imread(image_path_array[2])
image_4 = mpimg.imread(image_path_array[3])
ax1.imshow(image_1)
ax2.imshow(image_2)
ax3.imshow(image_3)
ax4.imshow(image_4)
ax1.axis('off')
ax2.axis('off')
ax3.axis('off')
ax4.axis('off')
if show == 1:
plt.show()
if save == 1:
plt.savefig(filename+file_format, dpi=dpi)
plt.close('all')
batch_reading_and_plottingbatch_reading_and_plotting(directory, xlabel='x', ylabel='y')
对某个目录中的txt文件批量读取和画图
| 参数 | 类型 | 默认值 |
|---|---|---|
directory | 必填 | |
xlabel | 'x' | |
ylabel | 'y' |
调用了:guan.read_one_dimensional_data, guan.plot
def batch_reading_and_plotting(directory, xlabel='x', ylabel='y'):
import re
import os
import guan
for root, dirs, files in os.walk(directory):
for file in files:
if re.search('^txt.', file[::-1]):
filename = file[:-4]
x_array, y_array = guan.read_one_dimensional_data(filename=filename)
guan.plot(x_array, y_array, xlabel=xlabel, ylabel=ylabel, title=filename, show=0, save=1, filename=filename)
make_gifmake_gif(image_path_array, filename='a', duration=0.1)
将图片制作GIF动画
| 参数 | 类型 | 默认值 |
|---|---|---|
image_path_array | 必填 | |
filename | 'a' | |
duration | 0.1 |
def make_gif(image_path_array, filename='a', duration=0.1):
import imageio
images = []
for image_path in image_path_array:
im = imageio.imread(image_path)
images.append(im)
imageio.mimsave(filename+'.gif', images, 'GIF', duration=duration)
color_matplotlibcolor_matplotlib()
选取Matplotlib颜色
def color_matplotlib():
color_array = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan']
return color_array
logging_with_day_and_timelogging_with_day_and_time(content='', filename='time_logging', file_format='.txt')
获取运行的日期和时间并写入文件
| 参数 | 类型 | 默认值 |
|---|---|---|
content | '' | |
filename | 'time_logging' | |
file_format | '.txt' |
def logging_with_day_and_time(content='', filename='time_logging', file_format='.txt'):
import datetime
datetime_today = str(datetime.date.today())
datetime_time = datetime.datetime.now().strftime('%H:%M:%S')
with open(filename+file_format, 'a', encoding="utf-8") as f2:
if content == '':
f2.write(datetime_today+' '+datetime_time+'\n')
else:
f2.write(datetime_today+' '+datetime_time+' '+str(content)+'\n')
record_time_and_print_running_timerecord_time_and_print_running_time(start_time=None)
获取当前位置的 Unix 时间戳,并打印某段程序的运行时间
| 参数 | 类型 | 默认值 |
|---|---|---|
start_time | None |
def record_time_and_print_running_time(start_time=None):
import time
current_time = time.time()
if start_time == None:
print("\n--- 开始计时(第一个记录点)---\n")
else:
print(f"\n--- 自上一个记录点已运行: {current_time - start_time:.2f} 秒 ---\n")
return current_time
timertimer(function_name, *args, **kwargs)
使用该函数运行某个函数并获取函数计算时间(秒)
| 参数 | 类型 | 默认值 |
|---|---|---|
function_name | 必填 | |
*args | 必填 | |
**kwargs | 必填 |
def timer(function_name, *args, **kwargs):
import time
start = time.time()
result = function_name(*args, **kwargs)
end = time.time()
print(f"Running time of {function_name.__name__}: {end - start} seconds")
return result
try_excepttry_except(function_name, *args, **kwargs)
使用该函数运行某个函数并实现 try-except-pass 结构
| 参数 | 类型 | 默认值 |
|---|---|---|
function_name | 必填 | |
*args | 必填 | |
**kwargs | 必填 |
def try_except(function_name, *args, **kwargs):
try:
return function_name(*args, **kwargs)
except:
pass
parallel_calculation_with_multiprocessing_Poolparallel_calculation_with_multiprocessing_Pool(func, args_list=[1, 2, 3], show_time=0)
使用 multiprocessing.Pool 实现自动分配任务并行
| 参数 | 类型 | 默认值 |
|---|---|---|
func | 必填 | |
args_list | [1, 2, 3] | |
show_time | 0 |
def parallel_calculation_with_multiprocessing_Pool(func, args_list=[1, 2, 3], show_time=0):
import multiprocessing
import time
start_time = time.time()
with multiprocessing.Pool() as pool:
result_array = pool.map(func, args_list)
end_time = time.time()
if show_time:
print(end_time - start_time)
return result_array
loop_calculation_with_one_parameterloop_calculation_with_one_parameter(function_name, parameter_array)
循环一个参数计算某个函数,并返回计算结果的数组
| 参数 | 类型 | 默认值 |
|---|---|---|
function_name | 必填 | |
parameter_array | 必填 |
def loop_calculation_with_one_parameter(function_name, parameter_array):
import numpy as np
result_array = []
for parameter in parameter_array:
result = function_name(parameter)
result_array.append(result)
result_array = np.array(result_array)
return result_array
loop_calculation_with_two_parametersloop_calculation_with_two_parameters(function_name, parameter_array_1, parameter_array_2)
循环两个参数计算某个函数,并返回计算结果的数组
| 参数 | 类型 | 默认值 |
|---|---|---|
function_name | 必填 | |
parameter_array_1 | 必填 | |
parameter_array_2 | 必填 |
def loop_calculation_with_two_parameters(function_name, parameter_array_1, parameter_array_2):
import numpy as np
result_array = np.zeros((len(parameter_array_2), len(parameter_array_1)))
i1 = 0
for parameter_1 in parameter_array_1:
i2 = 0
for parameter_2 in parameter_array_2:
result = function_name(parameter_1, parameter_2)
result_array[i2, i1] = result
i2 += 1
i1 += 1
return result_array
loop_calculation_with_three_parametersloop_calculation_with_three_parameters(function_name, parameter_array_1, parameter_array_2, parameter_array_3)
循环三个参数计算某个函数,并返回计算结果的数组
| 参数 | 类型 | 默认值 |
|---|---|---|
function_name | 必填 | |
parameter_array_1 | 必填 | |
parameter_array_2 | 必填 | |
parameter_array_3 | 必填 |
def loop_calculation_with_three_parameters(function_name, parameter_array_1, parameter_array_2, parameter_array_3):
import numpy as np
result_array = np.zeros((len(parameter_array_3), len(parameter_array_2), len(parameter_array_1)))
i1 = 0
for parameter_1 in parameter_array_1:
i2 = 0
for parameter_2 in parameter_array_2:
i3 = 0
for parameter_3 in parameter_array_3:
result = function_name(parameter_1, parameter_2, parameter_3)
result_array[i3, i2, i1] = result
i3 += 1
i2 += 1
i1 += 1
return result_array
word_diffword_diff(a, b, print_show=1)
文本对比
| 参数 | 类型 | 默认值 |
|---|---|---|
a | 必填 | |
b | 必填 | |
print_show | 1 |
def word_diff(a, b, print_show=1):
import difflib
import jieba
import logging
jieba.setLogLevel(logging.ERROR)
a_words = jieba.lcut(a)
b_words = jieba.lcut(b)
sm = difflib.SequenceMatcher(None, a_words, b_words, autojunk=False)
result = []
for tag, i1, i2, j1, j2 in sm.get_opcodes():
if tag == "equal":
result.extend(a_words[i1:i2])
elif tag == "delete":
result.append("\033[9;91m" + "".join(a_words[i1:i2]) + "\033[0m")
elif tag == "insert":
result.append("\033[92m" + "".join(b_words[j1:j2]) + "\033[0m")
elif tag == "replace":
result.append("\033[9;91m" + "".join(a_words[i1:i2]) + "\033[0m")
result.append(" ")
result.append("\033[92m" + "".join(b_words[j1:j2]) + "\033[0m")
diff_result = "".join(result)
if print_show:
print(diff_result)
return diff_result
word_diff_to_htmlword_diff_to_html(a, b, filename='diff_result', write_file=1)
文本对比(写入HTML文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
a | 必填 | |
b | 必填 | |
filename | 'diff_result' | |
write_file | 1 |
def word_diff_to_html(a, b, filename='diff_result', write_file=1):
import difflib
from html import escape
import jieba
import logging
jieba.setLogLevel(logging.ERROR)
a_words = jieba.lcut(a)
b_words = jieba.lcut(b)
sm = difflib.SequenceMatcher(None, a_words, b_words, autojunk=False)
html_parts = []
for tag, i1, i2, j1, j2 in sm.get_opcodes():
if tag == "equal":
html_parts.append("".join(map(escape, a_words[i1:i2])))
elif tag == "delete":
html_parts.append(f"<span style='background:#e74c3c;color:white;padding:1px 2px;border-radius:2px;text-decoration:line-through;'>"
+ "".join(map(escape, a_words[i1:i2]))
+ "</span>")
elif tag == "insert":
html_parts.append(f"<span style='background:#2ecc71;color:white;padding:1px 2px;border-radius:2px;'>"
+ "".join(map(escape, b_words[j1:j2]))
+ "</span>")
elif tag == "replace":
html_parts.append(f"<span style='background:#e74c3c;color:white;padding:1px 2px;border-radius:2px;text-decoration:line-through;'>"
+ "".join(map(escape, a_words[i1:i2]))
+ "</span>")
html_parts.append(" ")
html_parts.append(f"<span style='background:#2ecc71;color:white;padding:1px 2px;border-radius:2px;'>"
+ "".join(map(escape, b_words[j1:j2]))
+ "</span>")
diff_result = "".join(html_parts)
diff_result = diff_result.replace("\n", "<br>")
if write_file:
with open(filename+'.html', 'w', encoding='UTF-8') as f:
f.write(diff_result)
return diff_result
print_arrayprint_array(array, line_break=0)
打印数组
| 参数 | 类型 | 默认值 |
|---|---|---|
array | 必填 | |
line_break | 0 |
def print_array(array, line_break=0):
if line_break == 0:
for i0 in array:
print(i0)
else:
for i0 in array:
print(i0)
print()
print_array_with_indexprint_array_with_index(array, show_index=1, index_type=0)
以显示编号的样式,打印数组
| 参数 | 类型 | 默认值 |
|---|---|---|
array | 必填 | |
show_index | 1 | |
index_type | 0 |
def print_array_with_index(array, show_index=1, index_type=0):
if show_index==0:
for i0 in array:
print(i0)
else:
if index_type==0:
index = 0
for i0 in array:
print(index, i0)
index += 1
else:
index = 0
for i0 in array:
index += 1
print(index, i0)
dimension_of_arraydimension_of_array(array)
获取矩阵的维度(考虑单一数值的矩阵维度为1)
| 参数 | 类型 | 默认值 |
|---|---|---|
array | 必填 |
def dimension_of_array(array):
import numpy as np
array = np.array(array)
if array.shape==():
dim = 1
else:
dim = array.shape[0]
return dim
is_hermitianis_hermitian(matrix)
检查矩阵是否为厄米矩阵(相对误差为1e-5)
| 参数 | 类型 | 默认值 |
|---|---|---|
matrix | 必填 |
def is_hermitian(matrix):
import numpy as np
matrix = np.array(matrix)
if matrix.shape[0] != matrix.shape[1]:
return False
return np.allclose(matrix, np.conj(matrix.T))
close_to_integerclose_to_integer(value, abs_tol=0.001)
判断一个数是否接近于整数
| 参数 | 类型 | 默认值 |
|---|---|---|
value | 必填 | |
abs_tol | 0.001 |
def close_to_integer(value, abs_tol=1e-3):
import math
result = math.isclose(value, round(value), abs_tol=abs_tol)
return result
remove_item_in_one_arrayremove_item_in_one_array(array, item)
从列表中删除某个匹配的元素
| 参数 | 类型 | 默认值 |
|---|---|---|
array | 必填 | |
item | 必填 |
def remove_item_in_one_array(array, item):
new_array = [x for x in array if x != item]
return new_array
sort_array_by_index_elementsort_array_by_index_element(original_array, index)
根据子数组的第index个元素对子数组进行排序(index从0开始)
| 参数 | 类型 | 默认值 |
|---|---|---|
original_array | 必填 | |
index | 必填 |
def sort_array_by_index_element(original_array, index):
sorted_array = sorted(original_array, key=lambda x: x[index])
return sorted_array
get_random_numberget_random_number(start=0, end=1)
随机获得一个整数,左闭右闭
| 参数 | 类型 | 默认值 |
|---|---|---|
start | 0 | |
end | 1 |
def get_random_number(start=0, end=1):
import random
rand_number = random.randint(start, end) # 左闭右闭 [start, end]
return rand_number
generate_random_int_number_for_a_specific_seedgenerate_random_int_number_for_a_specific_seed(seed=0, x_min=0, x_max=10)
选取一个种子生成固定的随机整数,左闭右开
| 参数 | 类型 | 默认值 |
|---|---|---|
seed | 0 | |
x_min | 0 | |
x_max | 10 |
def generate_random_int_number_for_a_specific_seed(seed=0, x_min=0, x_max=10):
import numpy as np
np.random.seed(seed)
rand_num = np.random.randint(x_min, x_max) # 左闭右开[x_min, x_max)
return rand_num
standard_deviationstandard_deviation(data_array)
使用Numpy库计算总体标准差
| 参数 | 类型 | 默认值 |
|---|---|---|
data_array | 必填 |
def standard_deviation(data_array):
import numpy as np
std_result = np.std(data_array)
return std_result
standard_deviation_with_formulastandard_deviation_with_formula(data_array)
使用公式计算总体标准差
| 参数 | 类型 | 默认值 |
|---|---|---|
data_array | 必填 |
def standard_deviation_with_formula(data_array):
import numpy as np
averaged_data = sum(data_array)/len(data_array)
averaged_squared_data = sum(np.array(data_array)**2)/len(data_array)
std_result = np.sqrt(averaged_squared_data-averaged_data**2)
return std_result
calculate_pearson_correlationcalculate_pearson_correlation(x_array, y_array)
使用公式计算皮尔逊相关系数
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 |
def calculate_pearson_correlation(x_array, y_array):
import numpy as np
mean_x = np.mean(x_array)
mean_y = np.mean(y_array)
numerator = np.sum((x_array - mean_x) * (y_array - mean_y))
sum_sq_x = np.sum((x_array - mean_x) ** 2)
sum_sq_y = np.sum((y_array - mean_y) ** 2)
denominator = np.sqrt(sum_sq_x * sum_sq_y)
correlation = numerator / denominator
return correlation
calculate_pearson_correlation_with_scipycalculate_pearson_correlation_with_scipy(x_array, y_array)
使用 scipy 计算皮尔逊相关系数和 p 值
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 |
def calculate_pearson_correlation_with_scipy(x_array, y_array):
import scipy.stats
correlation, p_value = scipy.stats.pearsonr(x_array, y_array)
return correlation, p_value
calculate_correlation_matrix_for_multiple_arrayscalculate_correlation_matrix_for_multiple_arrays(multiple_arrays)
使用 scipy 计算多个数组的皮尔逊相关系数和 p 值的矩阵
| 参数 | 类型 | 默认值 |
|---|---|---|
multiple_arrays | 必填 |
def calculate_correlation_matrix_for_multiple_arrays(multiple_arrays):
import scipy.stats
import numpy as np
num_arrays = len(multiple_arrays)
correlation_matrix = np.zeros((num_arrays, num_arrays))
p_value_matrix = np.zeros((num_arrays, num_arrays))
row_idx = 0
for array_1 in multiple_arrays:
col_idx = 0
for array_2 in multiple_arrays:
correlation, p_value = scipy.stats.pearsonr(array_1, array_2)
correlation_matrix[row_idx, col_idx] = correlation
p_value_matrix[row_idx, col_idx] = p_value
col_idx += 1
row_idx += 1
return correlation_matrix, p_value_matrix
get_string_between_two_patternsget_string_between_two_patterns(original_string, start, end, include_start_and_end=0)
获取两个模式之间的字符串
| 参数 | 类型 | 默认值 |
|---|---|---|
original_string | 必填 | |
start | 必填 | |
end | 必填 | |
include_start_and_end | 0 |
def get_string_between_two_patterns(original_string, start, end, include_start_and_end=0):
import re
pattern = f'{start}(.*?){end}'
result = re.search(pattern, original_string)
if result:
if include_start_and_end == 0:
return result.group(1)
else:
return start+result.group(1)+end
else:
return ''
remove_substringsremove_substrings(original_string, start, end)
删除某个字符串中两个模式之间的内容,返回新字符串
| 参数 | 类型 | 默认值 |
|---|---|---|
original_string | 必填 | |
start | 必填 | |
end | 必填 |
def remove_substrings(original_string, start, end):
import re
escaped_start = re.escape(start)
escaped_end = re.escape(end)
pattern = f'{escaped_start}.*?{escaped_end}'
return re.sub(pattern, '', original_string, flags=re.DOTALL)
get_rotation_matrixget_rotation_matrix(angle_deg)
获取旋转矩阵(输入为角度)
| 参数 | 类型 | 默认值 |
|---|---|---|
angle_deg | 必填 |
def get_rotation_matrix(angle_deg):
import numpy as np
angle_rad = np.radians(angle_deg)
matrix = np.array([
[np.cos(angle_rad), -np.sin(angle_rad)],
[np.sin(angle_rad), np.cos(angle_rad)]
])
return matrix
rotate_pointrotate_point(x, y, angle_deg)
旋转某个点,返回新的点的坐标
| 参数 | 类型 | 默认值 |
|---|---|---|
x | 必填 | |
y | 必填 | |
angle_deg | 必填 |
def rotate_point(x, y, angle_deg):
import numpy as np
rotation_matrix = get_rotation_matrix(angle_deg)
x, y = np.dot(rotation_matrix, np.array([x, y]))
return x, y
convert_xyz_data_into_matrix_dataconvert_xyz_data_into_matrix_data(x_array, y_array, z_array)
将XYZ数据转成矩阵数据(说明:x_array/y_array的输入和输出不一样。要求z_array数据中y对应的数据为小循环,x对应的数据为大循环)
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
z_array | 必填 |
def convert_xyz_data_into_matrix_data(x_array, y_array, z_array):
import numpy as np
x_array_input = np.array(x_array)
y_array_input = np.array(y_array)
x_array = np.array(list(set(x_array_input)))
y_array = np.array(list(set(y_array_input)))
z_array = np.array(z_array)
len_x = len(x_array)
len_y = len(y_array)
matrix = np.zeros((len_x, len_y))
for ix in range(len_x):
for iy in range(len_y):
matrix[ix, iy] = z_array[ix*len_y+iy]
return x_array, y_array, matrix
convert_matrix_data_into_xyz_dataconvert_matrix_data_into_xyz_data(x_array, y_array, matrix)
将矩阵数据转成XYZ数据(说明:x_array/y_array的输入和输出不一样。生成的z_array数据中y对应的数据为小循环,x对应的数据为大循环)
| 参数 | 类型 | 默认值 |
|---|---|---|
x_array | 必填 | |
y_array | 必填 | |
matrix | 必填 |
def convert_matrix_data_into_xyz_data(x_array, y_array, matrix):
import numpy as np
x_array_input = np.array(x_array)
y_array_input = np.array(y_array)
matrix = np.array(matrix)
len_x = len(x_array_input)
len_y = len(y_array_input)
x_array = np.zeros((len_x*len_y))
y_array = np.zeros((len_x*len_y))
z_array = np.zeros((len_x*len_y))
for ix in range(len_x):
for iy in range(len_y):
x_array[ix*len_y+iy] = x_array_input[ix]
y_array[ix*len_y+iy] = y_array_input[iy]
z_array[ix*len_y+iy] = matrix[ix, iy]
return x_array, y_array, z_array
preprocess_for_parallel_calculationspreprocess_for_parallel_calculations(parameter_array_all, task_num=1, task_index=0)
并行计算前的预处理,把参数分成多份
| 参数 | 类型 | 默认值 |
|---|---|---|
parameter_array_all | 必填 | |
task_num | 1 | |
task_index | 0 |
def preprocess_for_parallel_calculations(parameter_array_all, task_num=1, task_index=0):
import numpy as np
num_all = np.array(parameter_array_all).shape[0]
if num_all%task_num == 0:
num_parameter = int(num_all/task_num)
parameter_array = parameter_array_all[task_index*num_parameter:(task_index+1)*num_parameter]
else:
num_parameter = int(num_all/(task_num-1))
if task_index != task_num-1:
parameter_array = parameter_array_all[task_index*num_parameter:(task_index+1)*num_parameter]
else:
parameter_array = parameter_array_all[task_index*num_parameter:num_all]
return parameter_array
run_programs_sequentiallyrun_programs_sequentially(program_files=['./a.py', './b.py'], execute='python ', show_time=0)
自动先后运行程序
| 参数 | 类型 | 默认值 |
|---|---|---|
program_files | ['./a.py', './b.py'] | |
execute | 'python ' | |
show_time | 0 |
def run_programs_sequentially(program_files=['./a.py', './b.py'], execute='python ', show_time=0):
import os
import time
if show_time == 1:
start = time.time()
i0 = 0
for program_file in program_files:
i0 += 1
if show_time == 1:
start_0 = time.time()
os.system(execute+program_file)
if show_time == 1:
end_0 = time.time()
print('Running time of program_'+str(i0)+' = '+str((end_0-start_0)/60)+' min')
if show_time == 1:
end = time.time()
print('Total running time = '+str((end-start)/60)+' min')
split_text_into_sentencessplit_text_into_sentences(text)
根据 “.” 和 “。” 符号进行分句
| 参数 | 类型 | 默认值 |
|---|---|---|
text | 必填 |
def split_text_into_sentences(text):
import re
pattern = r'(?<=[。])|(?<=\.)(?=\s|$)'
sentences = re.split(pattern, text)
sentence_array = [s.strip() for s in sentences if s.strip()]
return sentence_array
split_textsplit_text(text, width=100)
根据一定的字符长度来分割文本
| 参数 | 类型 | 默认值 |
|---|---|---|
text | 必填 | |
width | 100 |
def split_text(text, width=100):
split_text_list = [text[i:i+width] for i in range(0, len(text), width)]
return split_text_list
split_text_with_textwrapsplit_text_with_textwrap(text, width=100)
使用textwrap根据一定的字符长度来分割文本(会自动微小调节宽度,但存在换行符和空格丢失的问题)
| 参数 | 类型 | 默认值 |
|---|---|---|
text | 必填 | |
width | 100 |
def split_text_with_textwrap(text, width=100):
import textwrap
split_text_list = textwrap.wrap(text, width)
return split_text_list
divide_text_into_wordsdivide_text_into_words(text)
使用jieba软件包进行分词
| 参数 | 类型 | 默认值 |
|---|---|---|
text | 必填 |
def divide_text_into_words(text):
import jieba
words = jieba.lcut(text)
return words
check_Chinese_or_Englishcheck_Chinese_or_English(a)
判断某个字符是中文还是英文或其他
| 参数 | 类型 | 默认值 |
|---|---|---|
a | 必填 |
def check_Chinese_or_English(a):
if '\u4e00' <= a <= '\u9fff' :
word_type = 'Chinese'
elif '\x00' <= a <= '\xff':
word_type = 'English'
else:
word_type = 'Others'
return word_type
count_wordscount_words(text, include_space=0, show_words=0)
统计中英文文本的字数,默认不包括空格
| 参数 | 类型 | 默认值 |
|---|---|---|
text | 必填 | |
include_space | 0 | |
show_words | 0 |
调用了:guan.check_Chinese_or_English
def count_words(text, include_space=0, show_words=0):
import jieba
import guan
words = jieba.lcut(text)
new_words = []
if include_space == 0:
for word in words:
if word != ' ':
new_words.append(word)
else:
new_words = words
num_words = 0
new_words_2 = []
for word in new_words:
word_type = guan.check_Chinese_or_English(word[0])
if word_type == 'Chinese':
num_words += len(word)
for one_word in word:
new_words_2.append(one_word)
elif word_type == 'English' or 'Others':
num_words += 1
new_words_2.append(word)
if show_words == 1:
print(new_words_2)
return num_words
get_sourceget_source(name)
获取函数或类的源码(返回字符串)
| 参数 | 类型 | 默认值 |
|---|---|---|
name | 必填 |
def get_source(name):
import inspect
source = inspect.getsource(name)
return source
rgb_to_hexrgb_to_hex(rgb, pound=1)
将RGB转成HEX
| 参数 | 类型 | 默认值 |
|---|---|---|
rgb | 必填 | |
pound | 1 |
def rgb_to_hex(rgb, pound=1):
if pound==0:
return '%02x%02x%02x' % rgb
else:
return '#%02x%02x%02x' % rgb
hex_to_rgbhex_to_rgb(hex)
将HEX转成RGB
| 参数 | 类型 | 默认值 |
|---|---|---|
hex | 必填 |
def hex_to_rgb(hex):
hex = hex.lstrip('#')
length = len(hex)
return tuple(int(hex[i:i+length//3], 16) for i in range(0, length, length//3))
encryption_MD5encryption_MD5(password, salt='')
使用MD5进行散列加密
| 参数 | 类型 | 默认值 |
|---|---|---|
password | 必填 | |
salt | '' |
def encryption_MD5(password, salt=''):
import hashlib
password = salt+password
hashed_password = hashlib.md5(password.encode('utf-8')).hexdigest()
return hashed_password
encryption_SHA_256encryption_SHA_256(password, salt='')
使用SHA-256进行散列加密(常用且相对比较安全)
| 参数 | 类型 | 默认值 |
|---|---|---|
password | 必填 | |
salt | '' |
def encryption_SHA_256(password, salt=''):
import hashlib
password = salt+password
hashed_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
return hashed_password
encryption_bcryptencryption_bcrypt(password)
使用bcrypt生成盐并加密(常用且更加安全)
| 参数 | 类型 | 默认值 |
|---|---|---|
password | 必填 |
def encryption_bcrypt(password):
import bcrypt
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed_password
check_bcrypt_hashed_passwordcheck_bcrypt_hashed_password(password_input, hashed_password)
验证bcrypt加密的密码(这里的hashed_password已经包含了生成时使用的盐,bcrypt.checkpw会自动从hashed_password中提取盐,因此在验证时无需再单独传递盐)
| 参数 | 类型 | 默认值 |
|---|---|---|
password_input | 必填 | |
hashed_password | 必填 |
def check_bcrypt_hashed_password(password_input, hashed_password):
import bcrypt
return bcrypt.checkpw(password_input.encode('utf-8'), hashed_password)
openai_chatopenai_chat(prompt='你好', model='qwen-plus', temperature=0.7, system_message=None, history=[], print_show=1, load_env=1)
使用 OpenAI 框架对话(需要 API Key)
| 参数 | 类型 | 默认值 |
|---|---|---|
prompt | '你好' | |
model | 'qwen-plus' | |
temperature | 0.7 | |
system_message | None | |
history | [] | |
print_show | 1 | |
load_env | 1 |
def openai_chat(prompt="你好", model="qwen-plus", temperature=0.7, system_message=None, history=[], print_show=1, load_env=1):
import os
from openai import OpenAI
if load_env:
import dotenv
from pathlib import Path
import inspect
caller_frame = inspect.stack()[1]
caller_dir = Path(caller_frame.filename).parent
env_path = caller_dir / ".env"
if env_path.exists():
dotenv.load_dotenv(env_path)
client = OpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("DASHSCOPE_BASE_URL"),
)
if system_message == None:
messages = history+[{"role": "user", "content": prompt}]
else:
messages = [{"role": "system", "content": system_message}]+history+[{"role": "user", "content": prompt}]
completion = client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
stream=True,
extra_body={"enable_thinking": False},
)
response = ''
for chunk in completion:
response += chunk.choices[0].delta.content
if print_show:
print(chunk.choices[0].delta.content, end="", flush=True)
if print_show:
print()
history.append({"role": "user", "content": prompt})
history.append({"role": "assistant", "content": response})
return response, history
load_langchain_modelload_langchain_model(model='qwen-plus', temperature=0.7, load_env=1)
通过 LangChain 加载模型(需要 API Key)
| 参数 | 类型 | 默认值 |
|---|---|---|
model | 'qwen-plus' | |
temperature | 0.7 | |
load_env | 1 |
def load_langchain_model(model="qwen-plus", temperature=0.7, load_env=1):
from langchain_openai import ChatOpenAI
import os
if load_env:
import dotenv
from pathlib import Path
import inspect
caller_frame = inspect.stack()[1]
caller_dir = Path(caller_frame.filename).parent
env_path = caller_dir / ".env"
if env_path.exists():
dotenv.load_dotenv(env_path)
llm = ChatOpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("DASHSCOPE_BASE_URL"),
model=model,
temperature=temperature,
streaming=True,
)
return llm
langchain_chat_without_memorylangchain_chat_without_memory(prompt='你好', model='qwen-plus', temperature=0.7, system_message=None, print_show=1, load_env=1)
使用 LangChain 无记忆对话(需要 API Key)
| 参数 | 类型 | 默认值 |
|---|---|---|
prompt | '你好' | |
model | 'qwen-plus' | |
temperature | 0.7 | |
system_message | None | |
print_show | 1 | |
load_env | 1 |
def langchain_chat_without_memory(prompt="你好", model="qwen-plus", temperature=0.7, system_message=None, print_show=1, load_env=1):
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
import os
if load_env:
import dotenv
from pathlib import Path
import inspect
caller_frame = inspect.stack()[1]
caller_dir = Path(caller_frame.filename).parent
env_path = caller_dir / ".env"
if env_path.exists():
dotenv.load_dotenv(env_path)
llm = ChatOpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("DASHSCOPE_BASE_URL"),
model=model,
temperature=temperature,
streaming=True,
)
if system_message == None:
langchain_prompt = ChatPromptTemplate.from_messages([
("human", "{question}")
])
else:
langchain_prompt = ChatPromptTemplate.from_messages([
("system", system_message),
("human", "{question}")
])
chain = langchain_prompt | llm
response = ''
for chunk in chain.stream({"question": prompt}):
response += chunk.content
if print_show:
print(chunk.content, end="", flush=True)
if print_show:
print()
return response
langchain_chat_with_memorylangchain_chat_with_memory(prompt='你好', model='qwen-plus', temperature=0.7, system_message=None, session_id='default', print_show=1, load_env=1)
使用 LangChain 有记忆对话(记忆临时保存在函数的属性上,需要 API Key)
| 参数 | 类型 | 默认值 |
|---|---|---|
prompt | '你好' | |
model | 'qwen-plus' | |
temperature | 0.7 | |
system_message | None | |
session_id | 'default' | |
print_show | 1 | |
load_env | 1 |
def langchain_chat_with_memory(prompt="你好", model="qwen-plus", temperature=0.7, system_message=None, session_id="default", print_show=1, load_env=1):
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory
import os
if load_env:
import dotenv
from pathlib import Path
import inspect
caller_frame = inspect.stack()[1]
caller_dir = Path(caller_frame.filename).parent
env_path = caller_dir / ".env"
if env_path.exists():
dotenv.load_dotenv(env_path)
llm = ChatOpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("DASHSCOPE_BASE_URL"),
model=model,
temperature=temperature,
streaming=True,
)
if system_message == None:
langchain_prompt = ChatPromptTemplate.from_messages([
MessagesPlaceholder("history"),
("human", "{question}")
])
else:
langchain_prompt = ChatPromptTemplate.from_messages([
("system", system_message),
MessagesPlaceholder("history"),
("human", "{question}")
])
chain = langchain_prompt | llm
if not hasattr(langchain_chat_with_memory, "store"):
langchain_chat_with_memory.store = {}
def get_session_history(sid: str):
if sid not in langchain_chat_with_memory.store:
langchain_chat_with_memory.store[sid] = ChatMessageHistory()
return langchain_chat_with_memory.store[sid]
chatbot = RunnableWithMessageHistory(
chain,
lambda sid: get_session_history(sid),
input_messages_key="question",
history_messages_key="history",
)
response = ''
for chunk in chatbot.stream({"question": prompt}, config={"configurable": {"session_id": session_id}}):
response += chunk.content
if print_show:
print(chunk.content, end="", flush=True)
if print_show:
print()
return response
langchain_chat_with_toolslangchain_chat_with_tools(prompt='你好', model='qwen-plus', temperature=0.7, system_message=None, tools=None, print_show=1, load_env=1)
使用 LangChain 调用工具对话(需要 API Key)
| 参数 | 类型 | 默认值 |
|---|---|---|
prompt | '你好' | |
model | 'qwen-plus' | |
temperature | 0.7 | |
system_message | None | |
tools | None | |
print_show | 1 | |
load_env | 1 |
调用了:guan.langchain_chat_without_memory
def langchain_chat_with_tools(prompt="你好", model="qwen-plus", temperature=0.7, system_message=None, tools=None, print_show=1, load_env=1):
import guan
if tools==None:
response = guan.langchain_chat_without_memory(prompt=prompt, model=model, temperature=temperature, system_message=system_message, print_show=print_show, load_env=load_env)
else:
import os
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain.agents import create_openai_tools_agent, AgentExecutor
if load_env:
import dotenv
from pathlib import Path
import inspect
caller_frame = inspect.stack()[1]
caller_dir = Path(caller_frame.filename).parent
env_path = caller_dir / ".env"
if env_path.exists():
dotenv.load_dotenv(env_path)
llm = ChatOpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("DASHSCOPE_BASE_URL"),
model=model,
temperature=temperature,
streaming=False,
)
if system_message == None:
prompt_template = ChatPromptTemplate.from_messages([
("human", "{input_message}"),
("placeholder", "{agent_scratchpad}"),
])
else:
prompt_template = ChatPromptTemplate.from_messages([
("system", system_message),
("human", "{input_message}"),
("placeholder", "{agent_scratchpad}"),
])
agent = create_openai_tools_agent(llm, tools, prompt_template)
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=bool(print_show),
handle_parsing_errors=True,
)
response_result = agent_executor.invoke({"input_message": prompt})
response = response_result["output"]
if print_show:
print('\n'+response)
return response
langchain_chat_with_tools_and_memorylangchain_chat_with_tools_and_memory(prompt='你好', model='qwen-plus', temperature=0.7, system_message=None, tools=None, session_id='default', print_show=1, load_env=1)
使用 LangChain 调用工具有记忆对话(记忆临时保存在函数的属性上,需要 API Key)
| 参数 | 类型 | 默认值 |
|---|---|---|
prompt | '你好' | |
model | 'qwen-plus' | |
temperature | 0.7 | |
system_message | None | |
tools | None | |
session_id | 'default' | |
print_show | 1 | |
load_env | 1 |
调用了:guan.langchain_chat_with_memory
def langchain_chat_with_tools_and_memory(prompt="你好", model="qwen-plus", temperature=0.7, system_message=None, tools=None, session_id="default", print_show=1, load_env=1):
import guan
if tools==None:
response = guan.langchain_chat_with_memory(prompt=prompt, model=model, temperature=temperature, system_message=system_message, session_id=session_id, print_show=print_show, load_env=load_env)
else:
import os
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain.agents import create_openai_tools_agent, AgentExecutor
if load_env:
import dotenv
from pathlib import Path
import inspect
caller_frame = inspect.stack()[1]
caller_dir = Path(caller_frame.filename).parent
env_path = caller_dir / ".env"
if env_path.exists():
dotenv.load_dotenv(env_path)
llm = ChatOpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("DASHSCOPE_BASE_URL"),
model=model,
temperature=temperature,
streaming=False,
)
if system_message == None:
prompt_template = ChatPromptTemplate.from_messages([
MessagesPlaceholder("history"),
("human", "{input_message}"),
("placeholder", "{agent_scratchpad}"),
])
else:
prompt_template = ChatPromptTemplate.from_messages([
("system", system_message),
MessagesPlaceholder("history"),
("human", "{input_message}"),
("placeholder", "{agent_scratchpad}"),
])
if not hasattr(langchain_chat_with_tools_and_memory, "store"):
langchain_chat_with_tools_and_memory.store = {}
def get_session_history(sid: str):
if sid not in langchain_chat_with_tools_and_memory.store:
langchain_chat_with_tools_and_memory.store[sid] = ChatMessageHistory()
return langchain_chat_with_tools_and_memory.store[sid]
agent = create_openai_tools_agent(llm, tools, prompt_template)
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=bool(print_show),
handle_parsing_errors=True,
)
agent_with_chat_history = RunnableWithMessageHistory(
agent_executor,
get_session_history,
input_messages_key="input_message",
history_messages_key="history",
)
response_result = agent_with_chat_history.invoke({"input_message": prompt}, config={"configurable": {"session_id": session_id}})
response = response_result["output"]
if print_show:
print('\n'+response)
return response
ollama_chatollama_chat(prompt='你好/no_think', model='qwen3:0.6b', temperature=0.8, print_show=1)
使用 Ollama 本地模型对话(需要运行 Ollama 和下载对应的模型)
| 参数 | 类型 | 默认值 |
|---|---|---|
prompt | '你好/no_think' | |
model | 'qwen3:0.6b' | |
temperature | 0.8 | |
print_show | 1 |
def ollama_chat(prompt='你好/no_think', model="qwen3:0.6b", temperature=0.8, print_show=1):
import ollama
response_stream = ollama.chat(model=model, messages=[{"role": "user", "content": prompt}], stream=True, options={"temperature": temperature})
response = ''
start_thinking = 1
for part in response_stream:
response += part['message']['content']
if print_show == 1:
thinking = part['message'].get('thinking')
if thinking is not None:
if start_thinking == 1:
print('<think>')
start_thinking = 0
print(f"{thinking}", end='', flush=True)
else:
if start_thinking == 0:
print('</think>')
start_thinking = 1
print(part['message']['content'], end='', flush=True)
if print_show == 1:
print()
return response
load_modelscope_modelload_modelscope_model(model_name='D:/models/Qwen/Qwen3-0.6B')
ModelScope 加载本地模型和分词器(只加载一次,需要有模型文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
model_name | 'D:/models/Qwen/Qwen3-0.6B' |
def load_modelscope_model(model_name="D:/models/Qwen/Qwen3-0.6B"):
from modelscope import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
return model, tokenizer
modelscope_chatmodelscope_chat(model, tokenizer, prompt='你好 /no_think', history=[], temperature=0.7, top_p=0.8, print_show=1)
使用 ModelScope 本地模型聊天(需要有模型文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
model | 必填 | |
tokenizer | 必填 | |
prompt | '你好 /no_think' | |
history | [] | |
temperature | 0.7 | |
top_p | 0.8 | |
print_show | 1 |
def modelscope_chat(model, tokenizer, prompt='你好 /no_think', history=[], temperature=0.7, top_p=0.8, print_show=1):
from threading import Thread
from transformers import TextIteratorStreamer
messages = history + [{"role": "user", "content": prompt}]
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
inputs = tokenizer(text, return_tensors="pt")
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
generation_kwargs = dict(
**inputs,
streamer=streamer,
max_new_tokens=32768,
temperature=temperature,
top_p=top_p,
do_sample=True,
repetition_penalty=1.2
)
thread = Thread(target=model.generate, kwargs=generation_kwargs)
thread.start()
response = ""
for new_text in streamer:
if print_show:
print(new_text, end="", flush=True)
response += new_text
if print_show:
print()
history += [
{"role": "user", "content": prompt},
{"role": "assistant", "content": response}
]
return response, history
load_llama_modelload_llama_model(model_path='D:/models/Qwen/Qwen3-0.6B-GGUF/Qwen3-0.6B-Q8_0.gguf')
LLaMA 加载本地模型(只加载一次,需要有模型文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
model_path | 'D:/models/Qwen/Qwen3-0.6B-GGUF/Qwen3-0.6B-Q8_0.gguf' |
def load_llama_model(model_path="D:/models/Qwen/Qwen3-0.6B-GGUF/Qwen3-0.6B-Q8_0.gguf"):
from llama_cpp import Llama
llm = Llama(
model_path=model_path,
n_ctx=32768,
verbose=False,
chat_format="chatml",
logits_all=False
)
return llm
llama_chatllama_chat(llm, prompt='你好 /no_think', history=[], temperature=0.7, top_p=0.8, print_show=1)
使用 LLaMA 本地模型聊天(需要有模型文件)
| 参数 | 类型 | 默认值 |
|---|---|---|
llm | 必填 | |
prompt | '你好 /no_think' | |
history | [] | |
temperature | 0.7 | |
top_p | 0.8 | |
print_show | 1 |
def llama_chat(llm, prompt='你好 /no_think', history=[], temperature=0.7, top_p=0.8, print_show=1):
history += [{"role": "user", "content": prompt}]
llm_response = llm.create_chat_completion(
messages=history,
temperature=temperature,
top_p=top_p,
repeat_penalty=1.5,
stream=True,
)
response = ''
for chunk in llm_response:
delta = chunk['choices'][0]['delta']
if 'content' in delta:
token = delta['content']
response += token
if print_show:
print(token, end="", flush=True)
if print_show:
print()
history.append({"role": "assistant", "content": response})
return response, history
timer_decoratortimer_decorator(func)
函数的装饰器,用于获取计算时间(秒)
| 参数 | 类型 | 默认值 |
|---|---|---|
func | 必填 |
def timer_decorator(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Running time of {func.__name__}: {end - start} seconds")
return result
return wrapper
timer_decorator_minutestimer_decorator_minutes(func)
函数的装饰器,用于获取计算时间(分)
| 参数 | 类型 | 默认值 |
|---|---|---|
func | 必填 |
def timer_decorator_minutes(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Running time of {func.__name__}: {(end - start)/60} minutes")
return result
return wrapper
timer_decorator_hourstimer_decorator_hours(func)
函数的装饰器,用于获取计算时间(时)
| 参数 | 类型 | 默认值 |
|---|---|---|
func | 必填 |
def timer_decorator_hours(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Running time of {func.__name__}: {(end - start)/3600} hours")
return result
return wrapper
timer_decorator_with_parameterstimer_decorator_with_parameters(unit='second', print_show=1, write_file=0, filename='timer')
函数的装饰器,用于获取计算时间(秒,分,时),可将运行的时间写入文件
| 参数 | 类型 | 默认值 |
|---|---|---|
unit | 'second' | |
print_show | 1 | |
write_file | 0 | |
filename | 'timer' |
def timer_decorator_with_parameters(unit='second', print_show=1, write_file=0, filename='timer'):
def timer_decorator(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
if unit == 'second':
timer_text = f"Running time of {func.__name__}: {end - start} seconds"
elif unit == 'minute':
timer_text = f"Running time of {func.__name__}: {(end - start)/60} minutes"
elif unit == 'hour':
timer_text = f"Running time of {func.__name__}: {(end - start)/3600} hours"
else:
timer_text = f"Running time of {func.__name__}: {end - start} seconds"
if print_show == 1:
print(timer_text)
if write_file == 1:
with open(filename+'.txt', 'a') as f:
f.write(timer_text+'\n')
return result
return wrapper
return timer_decorator
try_decoratortry_decorator(func)
函数的装饰器,用于实现 try except 结构
| 参数 | 类型 | 默认值 |
|---|---|---|
func | 必填 |
def try_decorator(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
pass
return wrapper
原子类
自定义类和使用自定义类的函数 custom classes and functions using objects of custom classes
Atom.__init____init__(self, name='atom', index=0, x=0, y=0, z=0, energy=0)
| 参数 | 类型 | 默认值 |
|---|---|---|
self | 必填 | |
name | 'atom' | |
index | 0 | |
x | 0 | |
y | 0 | |
z | 0 | |
energy | 0 |
def __init__(self, name='atom', index=0, x=0, y=0, z=0, energy=0):
self.name = name
self.index = index
self.x = x
self.y = y
self.z = z
self.energy = energy
cpu_test_with_additioncpu_test_with_addition(print_show=1)
CPU性能测试(十亿次循环的浮点加法运算的时间,约30秒左右)
| 参数 | 类型 | 默认值 |
|---|---|---|
print_show | 1 |
def cpu_test_with_addition(print_show=1):
import time
result = 0.0
start_time = time.time()
for _ in range(int(1e9)):
result += 1e-9
end_time = time.time()
run_time = end_time - start_time
if print_show:
print(run_time)
return run_time
combine_two_pdf_filescombine_two_pdf_files(input_file_1='a.pdf', input_file_2='b.pdf', output_file='combined_file.pdf')
拼接两个PDF文件
| 参数 | 类型 | 默认值 |
|---|---|---|
input_file_1 | 'a.pdf' | |
input_file_2 | 'b.pdf' | |
output_file | 'combined_file.pdf' |
def combine_two_pdf_files(input_file_1='a.pdf', input_file_2='b.pdf', output_file='combined_file.pdf'):
import PyPDF2
output_pdf = PyPDF2.PdfWriter()
with open(input_file_1, 'rb') as file1:
pdf1 = PyPDF2.PdfReader(file1)
for page in range(len(pdf1.pages)):
output_pdf.add_page(pdf1.pages[page])
with open(input_file_2, 'rb') as file2:
pdf2 = PyPDF2.PdfReader(file2)
for page in range(len(pdf2.pages)):
output_pdf.add_page(pdf2.pages[page])
with open(output_file, 'wb') as combined_file:
output_pdf.write(combined_file)
pdf_to_text_with_pdfplumberpdf_to_text_with_pdfplumber(pdf_path)
使用pdfplumber将PDF文件转成文本
| 参数 | 类型 | 默认值 |
|---|---|---|
pdf_path | 必填 |
def pdf_to_text_with_pdfplumber(pdf_path):
import pdfplumber
with pdfplumber.open(pdf_path) as pdf:
all_text = []
for page in pdf.pages:
text = page.extract_text()
all_text.append(text)
content = "\n\n".join(all_text)
return content
pdf_to_text_with_pdfminer3kpdf_to_text_with_pdfminer3k(pdf_path)
使用pdfminer3k将PDF文件转成文本(仅仅支持旧版本的 pdfminer3k)
| 参数 | 类型 | 默认值 |
|---|---|---|
pdf_path | 必填 |
def pdf_to_text_with_pdfminer3k(pdf_path):
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTTextBox
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
import logging
logging.Logger.propagate = False
logging.getLogger().setLevel(logging.ERROR)
praser = PDFParser(open(pdf_path, 'rb'))
doc = PDFDocument()
praser.set_document(doc)
doc.set_parser(praser)
doc.initialize()
if not doc.is_extractable:
raise PDFTextExtractionNotAllowed
else:
rsrcmgr = PDFResourceManager()
laparams = LAParams()
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
content = ''
for page in doc.get_pages():
interpreter.process_page(page)
layout = device.get_result()
for x in layout:
if isinstance(x, LTTextBox):
content = content + x.get_text().strip()
return content
pdf_to_text_with_PyPDF2_for_all_pagespdf_to_text_with_PyPDF2_for_all_pages(pdf_path)
使用PyPDF2将PDF文件转成文本
| 参数 | 类型 | 默认值 |
|---|---|---|
pdf_path | 必填 |
调用了:guan.get_pdf_page_number, guan.pdf_to_txt_for_a_specific_page
def pdf_to_text_with_PyPDF2_for_all_pages(pdf_path):
import guan
num_pages = guan.get_pdf_page_number(pdf_path)
content = ''
for i0 in range(num_pages):
page_text = guan.pdf_to_txt_for_a_specific_page(pdf_path, page_num=i0+1)
content += page_text + '\n\n'
return content
get_pdf_page_numberget_pdf_page_number(pdf_path)
获取PDF文件页数
| 参数 | 类型 | 默认值 |
|---|---|---|
pdf_path | 必填 |
def get_pdf_page_number(pdf_path):
import PyPDF2
pdf_file = open(pdf_path, 'rb')
pdf_reader = PyPDF2.PdfReader(pdf_file)
num_pages = len(pdf_reader.pages)
return num_pages
pdf_to_txt_for_a_specific_pagepdf_to_txt_for_a_specific_page(pdf_path, page_num=1)
获取PDF文件指定页面的内容
| 参数 | 类型 | 默认值 |
|---|---|---|
pdf_path | 必填 | |
page_num | 1 |
def pdf_to_txt_for_a_specific_page(pdf_path, page_num=1):
import PyPDF2
pdf_file = open(pdf_path, 'rb')
pdf_reader = PyPDF2.PdfReader(pdf_file)
num_pages = len(pdf_reader.pages)
for page_num0 in range(num_pages):
if page_num0 == page_num-1:
page = pdf_reader.pages[page_num0]
page_text = page.extract_text()
pdf_file.close()
return page_text
get_links_from_pdfget_links_from_pdf(pdf_path, link_starting_form='')
获取PDF文献中的链接。例如: link_starting_form='https://doi.org'
| 参数 | 类型 | 默认值 |
|---|---|---|
pdf_path | 必填 | |
link_starting_form | '' |
def get_links_from_pdf(pdf_path, link_starting_form=''):
import PyPDF2
import re
reader = PyPDF2.PdfReader(pdf_path)
pages = len(reader.pages)
i0 = 0
links = []
for page in range(pages):
pageSliced = reader.pages[page]
pageObject = pageSliced.get_object()
if '/Annots' in pageObject.keys():
ann = pageObject['/Annots']
old = ''
for a in ann:
u = a.get_object()
if '/A' in u.keys():
if '/URI' in u['/A']:
if re.search(re.compile('^'+link_starting_form), u['/A']['/URI']):
if u['/A']['/URI'] != old:
links.append(u['/A']['/URI'])
i0 += 1
old = u['/A']['/URI']
return links
convert_file_encoding_for_one_directoryconvert_file_encoding_for_one_directory(source_directory, target_directory, file_formats=['.m'], src_encoding='utf-8', dst_encoding='gb18030')
将某个文件夹中的某个类型的文本文件全部修改为另外一个编码,其他文件不变
| 参数 | 类型 | 默认值 |
|---|---|---|
source_directory | 必填 | |
target_directory | 必填 | |
file_formats | ['.m'] | |
src_encoding | 'utf-8' | |
dst_encoding | 'gb18030' |
def convert_file_encoding_for_one_directory(source_directory, target_directory, file_formats=['.m'], src_encoding='utf-8', dst_encoding='gb18030'):
import os
import shutil
os.makedirs(target_directory, exist_ok=True)
for root, dirs, files in os.walk(source_directory):
rel_path = os.path.relpath(root, source_directory)
target_subdir = os.path.join(target_directory, rel_path) if rel_path != '.' else target_directory
os.makedirs(target_subdir, exist_ok=True)
for file in files:
src_file = os.path.join(root, file)
dst_file = os.path.join(target_subdir, file)
if any(file.lower().endswith(ext.lower()) for ext in file_formats):
try:
with open(src_file, 'r', encoding=src_encoding) as f:
content = f.read()
with open(dst_file, 'w', encoding=dst_encoding) as f:
f.write(content)
except Exception as e:
shutil.copy2(src_file, dst_file)
else:
shutil.copy2(src_file, dst_file)
get_dateget_date(bar=True)
获取当前日期字符串
| 参数 | 类型 | 默认值 |
|---|---|---|
bar | True |
def get_date(bar=True):
import datetime
datetime_date = str(datetime.date.today())
if bar==False:
datetime_date = datetime_date.replace('-', '')
return datetime_date
get_timeget_time(colon=True)
获取当前时间字符串
| 参数 | 类型 | 默认值 |
|---|---|---|
colon | True |
def get_time(colon=True):
import datetime
datetime_time = datetime.datetime.now().strftime('%H:%M:%S')
if colon==False:
datetime_time = datetime_time.replace(':', '')
return datetime_time
get_date_array_of_the_current_monthget_date_array_of_the_current_month(str_or_datetime='str')
获取本月的所有日期
| 参数 | 类型 | 默认值 |
|---|---|---|
str_or_datetime | 'str' |
def get_date_array_of_the_current_month(str_or_datetime='str'):
import datetime
today = datetime.date.today()
first_day_of_month = today.replace(day=1)
if first_day_of_month.month == 12:
next_month = first_day_of_month.replace(year=first_day_of_month.year + 1, month=1)
else:
next_month = first_day_of_month.replace(month=first_day_of_month.month + 1)
current_date = first_day_of_month
date_array = []
while current_date < next_month:
if str_or_datetime=='str':
date_array.append(str(current_date))
elif str_or_datetime=='datetime':
date_array.append(current_date)
current_date += datetime.timedelta(days=1)
return date_array
get_last_monthget_last_month()
获取上个月份
def get_last_month():
import datetime
today = datetime.date.today()
last_month = today.month - 1
if last_month == 0:
last_month = 12
year_of_last_month = today.year - 1
else:
year_of_last_month = today.year
return year_of_last_month, last_month
get_the_month_before_lastget_the_month_before_last()
获取上上个月份
def get_the_month_before_last():
import datetime
today = datetime.date.today()
the_month_before_last = today.month - 2
if the_month_before_last == 0:
the_month_before_last = 12
year_of_the_month_before_last = today.year - 1
else:
year_of_the_month_before_last = today.year
if the_month_before_last == -1:
the_month_before_last = 11
year_of_the_month_before_last = today.year - 1
else:
year_of_the_month_before_last = today.year
return year_of_the_month_before_last, the_month_before_last
get_date_array_of_the_last_monthget_date_array_of_the_last_month(str_or_datetime='str')
获取上个月的所有日期
| 参数 | 类型 | 默认值 |
|---|---|---|
str_or_datetime | 'str' |
def get_date_array_of_the_last_month(str_or_datetime='str'):
import datetime
import guan
today = datetime.date.today()
year_of_last_month, last_month = guan.get_last_month()
first_day_of_month = today.replace(year=year_of_last_month, month=last_month, day=1)
if first_day_of_month.month == 12:
next_month = first_day_of_month.replace(year=first_day_of_month.year + 1, month=1)
else:
next_month = first_day_of_month.replace(month=first_day_of_month.month + 1)
current_date = first_day_of_month
date_array = []
while current_date < next_month:
if str_or_datetime=='str':
date_array.append(str(current_date))
elif str_or_datetime=='datetime':
date_array.append(current_date)
current_date += datetime.timedelta(days=1)
return date_array
get_date_array_of_the_month_before_lastget_date_array_of_the_month_before_last(str_or_datetime='str')
获取上上个月的所有日期
| 参数 | 类型 | 默认值 |
|---|---|---|
str_or_datetime | 'str' |
调用了:guan.get_the_month_before_last
def get_date_array_of_the_month_before_last(str_or_datetime='str'):
import datetime
import guan
today = datetime.date.today()
year_of_last_last_month, last_last_month = guan.get_the_month_before_last()
first_day_of_month = today.replace(year=year_of_last_last_month, month=last_last_month, day=1)
if first_day_of_month.month == 12:
next_month = first_day_of_month.replace(year=first_day_of_month.year + 1, month=1)
else:
next_month = first_day_of_month.replace(month=first_day_of_month.month + 1)
current_date = first_day_of_month
date_array = []
while current_date < next_month:
if str_or_datetime=='str':
date_array.append(str(current_date))
elif str_or_datetime=='datetime':
date_array.append(current_date)
current_date += datetime.timedelta(days=1)
return date_array
fill_zero_data_for_new_datesfill_zero_data_for_new_dates(old_dates, new_dates, old_data_array)
根据新的日期,填充数组中缺少的数据为零
| 参数 | 类型 | 默认值 |
|---|---|---|
old_dates | 必填 | |
new_dates | 必填 | |
old_data_array | 必填 |
def fill_zero_data_for_new_dates(old_dates, new_dates, old_data_array):
new_data_array = []
for date in new_dates:
if str(date) not in old_dates:
new_data_array.append(0)
else:
index = old_dates.index(date)
new_data_array.append(old_data_array[index])
return new_data_array
get_memory_infoget_memory_info()
获取内存信息
def get_memory_info():
import psutil
memory_info = psutil.virtual_memory()
total_memory = memory_info.total/(1024**2)
used_memory = memory_info.used/(1024**2)
available_memory = memory_info.available/(1024**2)
used_memory_percent = memory_info.percent
return total_memory, used_memory, available_memory, used_memory_percent
get_cpu_usage_for_windowsget_cpu_usage_for_windows(interval=1.0)
获取CPU使用率(基于性能计数器,适用于Windows系统)
| 参数 | 类型 | 默认值 |
|---|---|---|
interval | 1.0 |
def get_cpu_usage_for_windows(interval=1.0):
import time
import ctypes
from ctypes import wintypes
class FILETIME(ctypes.Structure):
_fields_ = [
('dwLowDateTime', wintypes.DWORD),
('dwHighDateTime', wintypes.DWORD)
]
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
# 第一次采样
idle1 = FILETIME()
kernel1 = FILETIME()
user1 = FILETIME()
kernel32.GetSystemTimes(ctypes.byref(idle1), ctypes.byref(kernel1), ctypes.byref(user1))
time.sleep(interval)
# 第二次采样
idle2 = FILETIME()
kernel2 = FILETIME()
user2 = FILETIME()
kernel32.GetSystemTimes(ctypes.byref(idle2), ctypes.byref(kernel2), ctypes.byref(user2))
# 计算时间差
def filetime_to_int(ft):
return (ft.dwHighDateTime << 32) + ft.dwLowDateTime
idle = filetime_to_int(idle2) - filetime_to_int(idle1)
kernel = filetime_to_int(kernel2) - filetime_to_int(kernel1)
user = filetime_to_int(user2) - filetime_to_int(user1)
total = kernel + user
if total == 0:
return 0.0
return 100.0 * (total - idle) / total
get_cpu_usage_for_linuxget_cpu_usage_for_linux(interval=1.0)
获取CPU使用率(基于/proc/stat,适用于Linux系统)
| 参数 | 类型 | 默认值 |
|---|---|---|
interval | 1.0 |
def get_cpu_usage_for_linux(interval=1.0):
import time
def read_cpu_stats():
with open('/proc/stat') as f:
for line in f:
if line.startswith('cpu '):
parts = line.split()
return list(map(int, parts[1:]))
return None
stats1 = read_cpu_stats()
if not stats1:
return 0.0
time.sleep(interval)
stats2 = read_cpu_stats()
if not stats2:
return 0.0
idle1 = stats1[3] + stats1[4]
total1 = sum(stats1)
idle2 = stats2[3] + stats2[4]
total2 = sum(stats2)
total_delta = total2 - total1
idle_delta = idle2 - idle1
if total_delta == 0:
return 0.0
return 100.0 * (total_delta - idle_delta) / total_delta
get_cpu_usageget_cpu_usage(interval=1)
使用psutil获取CPU的平均使用率
| 参数 | 类型 | 默认值 |
|---|---|---|
interval | 1 |
def get_cpu_usage(interval=1):
import psutil
cpu_usage = psutil.cpu_percent(interval=interval)
return cpu_usage
get_cpu_usage_array_per_coreget_cpu_usage_array_per_core(interval=1)
使用psutil获取每个CPU核心的使用率,返回列表
| 参数 | 类型 | 默认值 |
|---|---|---|
interval | 1 |
def get_cpu_usage_array_per_core(interval=1):
import psutil
cpu_usage_array_per_core = psutil.cpu_percent(interval=interval, percpu=True)
return cpu_usage_array_per_core
get_cpu_max_usage_for_all_coresget_cpu_max_usage_for_all_cores(interval=1)
使用psutil获取使用率最高的CPU核心的使用率
| 参数 | 类型 | 默认值 |
|---|---|---|
interval | 1 |
调用了:guan.get_cpu_usage_array_per_core
def get_cpu_max_usage_for_all_cores(interval=1):
import guan
cpu_usage_array_per_core = guan.get_cpu_usage_array_per_core(interval=interval)
max_cpu_usage = max(cpu_usage_array_per_core)
return max_cpu_usage
get_cpu_averaged_usage_for_non_zero_coresget_cpu_averaged_usage_for_non_zero_cores(interval=1)
使用psutil获取非零使用率的CPU核心的平均使用率
| 参数 | 类型 | 默认值 |
|---|---|---|
interval | 1 |
调用了:guan.get_cpu_usage_array_per_core, guan.remove_item_in_one_array
def get_cpu_averaged_usage_for_non_zero_cores(interval=1):
import guan
cpu_usage_array_per_core = guan.get_cpu_usage_array_per_core(interval=interval)
cpu_usage_array_per_core_new = guan.remove_item_in_one_array(cpu_usage_array_per_core, 0.0)
averaged_cpu_usage = sum(cpu_usage_array_per_core_new)/len(cpu_usage_array_per_core_new)
return averaged_cpu_usage
get_cpu_information_for_timesget_cpu_information_for_times(interval=1, sleep_interval=0, times=60)
使用psutil在一定数量周期内得到CPU的使用率信息。默认为1秒钟收集一次,(interval+sleep_interval)*times 为收集的时间范围,范围默认为60秒,即1分钟后返回列表,总共得到60组数据。其中,数字第一列和第二列分别是平均值和最大值。
| 参数 | 类型 | 默认值 |
|---|---|---|
interval | 1 | |
sleep_interval | 0 | |
times | 60 |
调用了:guan.get_date, guan.get_time, guan.get_cpu_usage_array_per_core
def get_cpu_information_for_times(interval=1, sleep_interval=0, times=60):
import guan
import time
cpu_information_array = []
for _ in range(times):
cpu_information = []
datetime_date = guan.get_date()
datetime_time = guan.get_time()
cpu_information.append(datetime_date)
cpu_information.append(datetime_time)
cpu_usage_array_per_core = guan.get_cpu_usage_array_per_core(interval=interval)
cpu_information.append(sum(cpu_usage_array_per_core)/len(cpu_usage_array_per_core))
cpu_information.append(max(cpu_usage_array_per_core))
for cpu_usage in cpu_usage_array_per_core:
cpu_information.append(cpu_usage)
cpu_information_array.append(cpu_information)
time.sleep(sleep_interval)
return cpu_information_array
write_cpu_information_to_filewrite_cpu_information_to_file(filename='./cpu_usage', interval=1, sleep_interval=59, times=60)
使用psutil获取CPU的使用率,将得到的CPU的使用率信息写入文件。默认为1分钟收集一次,(interval+sleep_interval)*times 为收集的时间范围,范围默认为60分钟,即1小时写入文件一次,总共得到60组数据。其中,数字第一列和第二列分别是平均值和最大值。
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | './cpu_usage' | |
interval | 1 | |
sleep_interval | 59 | |
times | 60 |
调用了:guan.make_file, guan.open_file, guan.get_cpu_information_for_times
def write_cpu_information_to_file(filename='./cpu_usage', interval=1, sleep_interval=59, times=60):
import guan
guan.make_file(filename+'.txt')
while True:
f = guan.open_file(filename)
cpu_information_array = guan.get_cpu_information_for_times(interval=interval, sleep_interval=sleep_interval, times=times)
for cpu_information in cpu_information_array:
i0 = 0
for information in cpu_information:
if i0 < 2:
f.write(str(information)+' ')
else:
f.write(f'{information:.1f} ')
i0 += 1
f.write('\n')
f.close()
plot_cpu_informationplot_cpu_information(filename='./cpu_usage', recent_num=60, max_cpu=0)
使用psutil获取CPU的使用率,画CPU的使用率图。默认为画最近的60个数据,以及不画CPU核心的最大使用率。
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | './cpu_usage' | |
recent_num | 60 | |
max_cpu | 0 |
调用了:guan.import_plt_and_start_fig_ax, guan.plot_without_starting_fig_ax
def plot_cpu_information(filename='./cpu_usage', recent_num=60, max_cpu=0):
import guan
from datetime import datetime
with open(filename+".txt", "r") as file:
lines = file.readlines()
lines = lines[::-1]
timestamps_array = []
averaged_cpu_usage_array = []
max_cpu_usage_array = []
i0 = 0
for line in lines:
i0 += 1
if i0 >= recent_num:
break
cpu_information = line.strip()
information = cpu_information.split()
time_str = information[0]+' '+information[1]
time_format = "%Y-%m-%d %H:%M:%S"
timestamps_array.append(datetime.strptime(time_str, time_format))
averaged_cpu_usage_array.append(float(information[2]))
max_cpu_usage_array.append(float(information[3]))
plt, fig, ax = guan.import_plt_and_start_fig_ax(adjust_bottom=0.3, adjust_left=0.15, labelsize=16, fontfamily='Times New Roman')
plt.xticks(rotation=90)
guan.plot_without_starting_fig_ax(plt, fig, ax, timestamps_array, averaged_cpu_usage_array, style='o-')
legend_array = ['Averaged']
if max_cpu == 1:
guan.plot_without_starting_fig_ax(plt, fig, ax, timestamps_array, max_cpu_usage_array, style='o-')
legend_array.append('Max')
guan.plot_without_starting_fig_ax(plt, fig, ax, [], [], xlabel='Time', ylabel='CPU usage', fontsize=20)
plt.legend(legend_array)
plt.show()
plot_detailed_cpu_informationplot_detailed_cpu_information(filename='./cpu_usage', recent_num=60)
使用psutil获取CPU的使用率,画详细的CPU的使用率图,分CPU核心画图。
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | './cpu_usage' | |
recent_num | 60 |
调用了:guan.import_plt_and_start_fig_ax, guan.plot_without_starting_fig_ax
def plot_detailed_cpu_information(filename='./cpu_usage', recent_num=60):
import guan
from datetime import datetime
with open(filename+".txt", "r") as file:
lines = file.readlines()
lines = lines[::-1]
timestamps_array = []
i0 = 0
core_num = len(lines[0].strip().split())-4
detailed_cpu_usage_array = []
for line in lines:
i0 += 1
if i0 > recent_num:
break
cpu_information = line.strip()
information = cpu_information.split()
time_str = information[0]+' '+information[1]
time_format = "%Y-%m-%d %H:%M:%S"
timestamps_array.append(datetime.strptime(time_str, time_format))
detailed_cpu_usage = []
for core in range(core_num):
detailed_cpu_usage.append(float(information[4+core]))
detailed_cpu_usage_array.append(detailed_cpu_usage)
for core in range(core_num):
plt, fig, ax = guan.import_plt_and_start_fig_ax(adjust_bottom=0.3, adjust_left=0.15, labelsize=16, fontfamily='Times New Roman')
plt.xticks(rotation=90)
guan.plot_without_starting_fig_ax(plt, fig, ax, timestamps_array, [row[core] for row in detailed_cpu_usage_array], style='o-')
legend_array = []
legend_array.append(f'CPU {core+1}')
guan.plot_without_starting_fig_ax(plt, fig, ax, [], [], xlabel='Time', ylabel='CPU usage', fontsize=20)
plt.legend(legend_array)
plt.show()
get_mac_addressget_mac_address()
获取MAC地址
def get_mac_address():
import uuid
mac_address = uuid.UUID(int=uuid.getnode()).hex[-12:].upper()
mac_address = '-'.join([mac_address[i:i+2] for i in range(0, 11, 2)])
return mac_address
get_all_modules_in_one_packageget_all_modules_in_one_package(package_name='guan')
获取软件包中的所有模块名
| 参数 | 类型 | 默认值 |
|---|---|---|
package_name | 'guan' |
def get_all_modules_in_one_package(package_name='guan'):
import pkgutil
package = __import__(package_name)
module_names = [name for _, name, _ in pkgutil.iter_modules(package.__path__)]
return module_names
get_all_functions_in_one_moduleget_all_functions_in_one_module(module_name, package_name='guan')
获取软件包中一个模块的所有函数名
| 参数 | 类型 | 默认值 |
|---|---|---|
module_name | 必填 | |
package_name | 'guan' |
def get_all_functions_in_one_module(module_name, package_name='guan'):
import inspect
function_names = []
module = __import__(f"{package_name}.{module_name}", fromlist=[""])
for name, obj in inspect.getmembers(module):
if inspect.isfunction(obj):
function_names.append(name)
return function_names
get_all_functions_in_one_packageget_all_functions_in_one_package(package_name='guan', print_show=1)
获取软件包中的所有函数名
| 参数 | 类型 | 默认值 |
|---|---|---|
package_name | 'guan' | |
print_show | 1 |
调用了:guan.get_all_modules_in_one_package, guan.get_all_functions_in_one_module
def get_all_functions_in_one_package(package_name='guan', print_show=1):
import guan
module_names = guan.get_all_modules_in_one_package(package_name=package_name)
all_function_names = []
for module_name in module_names:
function_names = guan.get_all_functions_in_one_module(module_name, package_name='guan')
if print_show == 1:
print('Module:', module_name)
for name in function_names:
all_function_names.append(name)
if print_show == 1:
print('function:', name)
if print_show == 1:
print()
return all_function_names
get_calling_function_nameget_calling_function_name(layer=1)
获取调用本函数的函数名
| 参数 | 类型 | 默认值 |
|---|---|---|
layer | 1 |
def get_calling_function_name(layer=1):
import inspect
caller = inspect.stack()[layer]
calling_function_name = caller.function
return calling_function_name
count_number_of_import_statementscount_number_of_import_statements(filename, file_format='.py', num=1000)
统计Python文件中import的数量并排序
| 参数 | 类型 | 默认值 |
|---|---|---|
filename | 必填 | |
file_format | '.py' | |
num | 1000 |
def count_number_of_import_statements(filename, file_format='.py', num=1000):
with open(filename+file_format, 'r') as file:
lines = file.readlines()
import_array = []
for line in lines:
if 'import ' in line:
line = line.strip()
import_array.append(line)
from collections import Counter
import_statement_counter = Counter(import_array).most_common(num)
return import_statement_counter
get_current_versionget_current_version(package_name='guan')
获取软件包的本机版本
| 参数 | 类型 | 默认值 |
|---|---|---|
package_name | 'guan' |
def get_current_version(package_name='guan'):
import importlib.metadata
try:
current_version = importlib.metadata.version(package_name)
return current_version
except:
return None
get_latest_versionget_latest_version(package_name='guan', timeout=5)
获取Python软件包的最新版本
| 参数 | 类型 | 默认值 |
|---|---|---|
package_name | 'guan' | |
timeout | 5 |
def get_latest_version(package_name='guan', timeout=5):
import requests
url = f"https://pypi.org/pypi/{package_name}/json"
try:
response = requests.get(url, timeout=timeout)
except:
return None
if response.status_code == 200:
data = response.json()
latest_version = data["info"]["version"]
return latest_version
else:
return None
get_PID_arrayget_PID_array(name)
获取包含某个字符的进程PID值
| 参数 | 类型 | 默认值 |
|---|---|---|
name | 必填 |
def get_PID_array(name):
import subprocess
command = "ps -ef | grep "+name
result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode == 0:
ps_ef = result.stdout
import re
ps_ef_1 = re.split(r'\n', ps_ef)
id_running_array = []
for ps_ef_item in ps_ef_1:
if ps_ef_item != '':
ps_ef_2 = re.split(r'\s+', ps_ef_item)
id_running_array.append(ps_ef_2[1])
return id_running_array
find_git_repositoriesfind_git_repositories(base_path='./', ignored_directory_with_words=[])
寻找所有的git仓库
| 参数 | 类型 | 默认值 |
|---|---|---|
base_path | './' | |
ignored_directory_with_words | [] |
def find_git_repositories(base_path='./', ignored_directory_with_words=[]):
import os
git_repository_array = []
for root, dirs, files in os.walk(base_path):
if '.git' in dirs:
ignore_signal = 0
for word in ignored_directory_with_words:
if word in root:
ignore_signal = 1
break
if ignore_signal == 0:
git_repository_array.append(root)
return git_repository_array
get_git_repositories_to_commitget_git_repositories_to_commit(git_repository_array)
在git仓库列表中找到有修改待commit的
| 参数 | 类型 | 默认值 |
|---|---|---|
git_repository_array | 必填 |
def get_git_repositories_to_commit(git_repository_array):
import os
import subprocess
git_repository_array_to_commit = []
for repository in git_repository_array:
os.chdir(repository)
status = subprocess.check_output(['git', 'status']).decode('utf-8')
if 'nothing to commit, working tree clean' in status:
pass
else:
git_repository_array_to_commit.append(repository)
return git_repository_array_to_commit
statistics_of_git_commitsstatistics_of_git_commits(print_show=0, str_or_datetime='str')
每日git commit次数的统计
| 参数 | 类型 | 默认值 |
|---|---|---|
print_show | 0 | |
str_or_datetime | 'str' |
def statistics_of_git_commits(print_show=0, str_or_datetime='str'):
import subprocess
import collections
since_date = '100 year ago'
result = subprocess.run(
['git', 'log', f'--since={since_date}', '--pretty=format:%ad', '--date=short'],
stdout=subprocess.PIPE,
text=True)
commits = result.stdout.strip().split('\n')
counter = collections.Counter(commits)
daily_commit_counts = dict(sorted(counter.items()))
date_array = []
commit_count_array = []
for date, count in daily_commit_counts.items():
if print_show == 1:
print(f"{date}: {count} commits")
if str_or_datetime=='datetime':
import datetime
date_array.append(datetime.datetime.strptime(date, "%Y-%m-%d"))
elif str_or_datetime=='str':
date_array.append(date)
commit_count_array.append(count)
return date_array, commit_count_array
write_file_list_in_markdownwrite_file_list_in_markdown(directory='./', filename='a', reverse_positive_or_negative=1, starting_from_h1=None, banned_file_format=[], hide_file_format=None, divided_line=None, show_second_number=None, show_third_number=None)
将文件目录结构写入Markdown文件
| 参数 | 类型 | 默认值 |
|---|---|---|
directory | './' | |
filename | 'a' | |
reverse_positive_or_negative | 1 | |
starting_from_h1 | None | |
banned_file_format | [] | |
hide_file_format | None | |
divided_line | None | |
show_second_number | None | |
show_third_number | None |
def write_file_list_in_markdown(directory='./', filename='a', reverse_positive_or_negative=1, starting_from_h1=None, banned_file_format=[], hide_file_format=None, divided_line=None, show_second_number=None, show_third_number=None):
import os
f = open(filename+'.md', 'w', encoding="utf-8")
filenames1 = os.listdir(directory)
u0 = 0
for filename1 in filenames1[::reverse_positive_or_negative]:
filename1_with_path = os.path.join(directory,filename1)
if os.path.isfile(filename1_with_path):
if os.path.splitext(filename1)[1] not in banned_file_format:
if hide_file_format == None:
f.write('+ '+str(filename1)+'\n\n')
else:
f.write('+ '+str(os.path.splitext(filename1)[0])+'\n\n')
else:
u0 += 1
if divided_line != None and u0 != 1:
f.write('--------\n\n')
if starting_from_h1 == None:
f.write('#')
f.write('# '+str(filename1)+'\n\n')
filenames2 = os.listdir(filename1_with_path)
i0 = 0
for filename2 in filenames2[::reverse_positive_or_negative]:
filename2_with_path = os.path.join(directory, filename1, filename2)
if os.path.isfile(filename2_with_path):
if os.path.splitext(filename2)[1] not in banned_file_format:
if hide_file_format == None:
f.write('+ '+str(filename2)+'\n\n')
else:
f.write('+ '+str(os.path.splitext(filename2)[0])+'\n\n')
else:
i0 += 1
if starting_from_h1 == None:
f.write('#')
if show_second_number != None:
f.write('## '+str(i0)+'. '+str(filename2)+'\n\n')
else:
f.write('## '+str(filename2)+'\n\n')
j0 = 0
filenames3 = os.listdir(filename2_with_path)
for filename3 in filenames3[::reverse_positive_or_negative]:
filename3_with_path = os.path.join(directory, filename1, filename2, filename3)
if os.path.isfile(filename3_with_path):
if os.path.splitext(filename3)[1] not in banned_file_format:
if hide_file_format == None:
f.write('+ '+str(filename3)+'\n\n')
else:
f.write('+ '+str(os.path.splitext(filename3)[0])+'\n\n')
else:
j0 += 1
if starting_from_h1 == None:
f.write('#')
if show_third_number != None:
f.write('### ('+str(j0)+') '+str(filename3)+'\n\n')
else:
f.write('### '+str(filename3)+'\n\n')
filenames4 = os.listdir(filename3_with_path)
for filename4 in filenames4[::reverse_positive_or_negative]:
filename4_with_path = os.path.join(directory, filename1, filename2, filename3, filename4)
if os.path.isfile(filename4_with_path):
if os.path.splitext(filename4)[1] not in banned_file_format:
if hide_file_format == None:
f.write('+ '+str(filename4)+'\n\n')
else:
f.write('+ '+str(os.path.splitext(filename4)[0])+'\n\n')
else:
if starting_from_h1 == None:
f.write('#')
f.write('#### '+str(filename4)+'\n\n')
filenames5 = os.listdir(filename4_with_path)
for filename5 in filenames5[::reverse_positive_or_negative]:
filename5_with_path = os.path.join(directory, filename1, filename2, filename3, filename4, filename5)
if os.path.isfile(filename5_with_path):
if os.path.splitext(filename5)[1] not in banned_file_format:
if hide_file_format == None:
f.write('+ '+str(filename5)+'\n\n')
else:
f.write('+ '+str(os.path.splitext(filename5)[0])+'\n\n')
else:
if starting_from_h1 == None:
f.write('#')
f.write('##### '+str(filename5)+'\n\n')
filenames6 = os.listdir(filename5_with_path)
for filename6 in filenames6[::reverse_positive_or_negative]:
filename6_with_path = os.path.join(directory, filename1, filename2, filename3, filename4, filename5, filename6)
if os.path.isfile(filename6_with_path):
if os.path.splitext(filename6)[1] not in banned_file_format:
if hide_file_format == None:
f.write('+ '+str(filename6)+'\n\n')
else:
f.write('+ '+str(os.path.splitext(filename6)[0])+'\n\n')
else:
if starting_from_h1 == None:
f.write('#')
f.write('###### '+str(filename6)+'\n\n')
f.close()
get_html_from_tagsget_html_from_tags(link, tags=['title', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'li', 'a'])
从网页的标签中获取内容
| 参数 | 类型 | 默认值 |
|---|---|---|
link | 必填 | |
tags | ['title', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'li', 'a'] |
def get_html_from_tags(link, tags=['title', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'li', 'a']):
from bs4 import BeautifulSoup
import urllib.request
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
html = urllib.request.urlopen(link).read().decode('utf-8')
soup = BeautifulSoup(html, features="lxml")
all_tags = soup.find_all(tags)
content = ''
for tag in all_tags:
text = tag.get_text().replace('\n', '')
if content == '':
content = text
else:
content = content + '\n\n' + text
return content
get_links_from_htmlget_links_from_html(html_link, links_with_text=0)
从HTML中获取所有的链接
| 参数 | 类型 | 默认值 |
|---|---|---|
html_link | 必填 | |
links_with_text | 0 |
def get_links_from_html(html_link, links_with_text=0):
from bs4 import BeautifulSoup
import urllib.request
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
html = urllib.request.urlopen(html_link).read().decode('utf-8')
soup = BeautifulSoup(html, features="lxml")
a_tags = soup.find_all('a')
if links_with_text == 0:
link_array = [tag.get('href') for tag in a_tags if tag.get('href')]
return link_array
else:
link_array_with_text = [(tag.get('href'), tag.text) for tag in a_tags if tag.get('href')]
return link_array_with_text
check_linkcheck_link(url, timeout=3, allow_redirects=True)
检查链接的有效性
| 参数 | 类型 | 默认值 |
|---|---|---|
url | 必填 | |
timeout | 3 | |
allow_redirects | True |
def check_link(url, timeout=3, allow_redirects=True):
import requests
try:
response = requests.head(url, timeout=timeout, allow_redirects=allow_redirects)
if response.status_code == 200:
return True
else:
return False
except requests.exceptions.RequestException:
return False
check_link_arraycheck_link_array(link_array, timeout=3, allow_redirects=True, try_again=0, print_show=1)
检查链接数组中链接的有效性
| 参数 | 类型 | 默认值 |
|---|---|---|
link_array | 必填 | |
timeout | 3 | |
allow_redirects | True | |
try_again | 0 | |
print_show | 1 |
调用了:guan.check_link
def check_link_array(link_array, timeout=3, allow_redirects=True, try_again=0, print_show=1):
import guan
failed_link_array0 = []
for link in link_array:
if link=='#' or guan.check_link(link, timeout=timeout, allow_redirects=allow_redirects):
pass
else:
failed_link_array0.append(link)
if print_show:
print(link)
failed_link_array = []
if try_again:
if print_show:
print('\nTry again:\n')
for link in failed_link_array0:
if link=='#' or guan.check_link(link, timeout=timeout, allow_redirects=allow_redirects):
pass
else:
failed_link_array.append(link)
if print_show:
print(link)
else:
failed_link_array = failed_link_array0
return failed_link_array
creat_qrcodecreat_qrcode(data='https://www.guanjihuan.com', filename='a', file_format='.png')
生成二维码
| 参数 | 类型 | 默认值 |
|---|---|---|
data | 'https://www.guanjihuan.com' | |
filename | 'a' | |
file_format | '.png' |
def creat_qrcode(data="https://www.guanjihuan.com", filename='a', file_format='.png'):
import qrcode
img = qrcode.make(data)
img.save(filename+file_format)
download_with_scihubdownload_with_scihub(address=None, num=1)
通过Sci-Hub网站下载文献(该方法可能失效)
| 参数 | 类型 | 默认值 |
|---|---|---|
address | None | |
num | 1 |
def download_with_scihub(address=None, num=1):
from bs4 import BeautifulSoup
import re
import requests
import os
if num==1 and address!=None:
address_array = [address]
else:
address_array = []
for i in range(num):
address = input('\nInput:')
address_array.append(address)
for address in address_array:
r = requests.post('https://sci-hub.st/', data={'request': address})
print('\nResponse:', r)
print('Address:', r.url)
soup = BeautifulSoup(r.text, features='lxml')
pdf_URL = soup.embed['src']
# pdf_URL = soup.iframe['src'] # This is a code line of history version which fails to get pdf URL.
if re.search(re.compile('^https:'), pdf_URL):
pass
else:
pdf_URL = 'https:'+pdf_URL
print('PDF address:', pdf_URL)
name = re.search(re.compile('fdp.*?/'),pdf_URL[::-1]).group()[::-1][1::]
print('PDF name:', name)
print('Directory:', os.getcwd())
print('\nDownloading...')
r = requests.get(pdf_URL, stream=True)
with open(name, 'wb') as f:
for chunk in r.iter_content(chunk_size=32):
f.write(chunk)
print('Completed!\n')
if num != 1:
print('All completed!\n')
str_to_audiostr_to_audio(str='hello world', filename='str', rate=125, voice=1, read=1, save=0, compress=0, bitrate='16k', print_text=0)
将字符串转成音频
| 参数 | 类型 | 默认值 |
|---|---|---|
str | 'hello world' | |
filename | 'str' | |
rate | 125 | |
voice | 1 | |
read | 1 | |
save | 0 | |
compress | 0 | |
bitrate | '16k' | |
print_text | 0 |
def str_to_audio(str='hello world', filename='str', rate=125, voice=1, read=1, save=0, compress=0, bitrate='16k', print_text=0):
import pyttsx3
import guan
if print_text==1:
print(str)
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[voice].id)
engine.setProperty("rate", rate)
if save==1:
engine.save_to_file(str, filename+'.wav')
engine.runAndWait()
print('Wav file saved!')
if compress==1:
import os
os.rename(filename+'.wav', 'temp.wav')
guan.compress_wav_to_mp3('temp.wav', output_filename=filename+'.mp3', bitrate=bitrate)
os.remove('temp.wav')
if read==1:
engine.say(str)
engine.runAndWait()
txt_to_audiotxt_to_audio(txt_path, rate=125, voice=1, read=1, save=0, compress=0, bitrate='16k', print_text=0)
将txt文件转成音频
| 参数 | 类型 | 默认值 |
|---|---|---|
txt_path | 必填 | |
rate | 125 | |
voice | 1 | |
read | 1 | |
save | 0 | |
compress | 0 | |
bitrate | '16k' | |
print_text | 0 |
def txt_to_audio(txt_path, rate=125, voice=1, read=1, save=0, compress=0, bitrate='16k', print_text=0):
import pyttsx3
import guan
f = open(txt_path, 'r', encoding ='utf-8')
text = f.read()
if print_text==1:
print(text)
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[voice].id)
engine.setProperty("rate", rate)
if save==1:
import re
filename = re.split('[/,\\\]', txt_path)[-1][:-4]
engine.save_to_file(text, filename+'.wav')
engine.runAndWait()
print('Wav file saved!')
if compress==1:
import os
os.rename(filename+'.wav', 'temp.wav')
guan.compress_wav_to_mp3('temp.wav', output_filename=filename+'.mp3', bitrate=bitrate)
os.remove('temp.wav')
if read==1:
engine.say(text)
engine.runAndWait()
pdf_to_audiopdf_to_audio(pdf_path, rate=125, voice=1, read=1, save=0, compress=0, bitrate='16k', print_text=0)
将PDF文件转成音频
| 参数 | 类型 | 默认值 |
|---|---|---|
pdf_path | 必填 | |
rate | 125 | |
voice | 1 | |
read | 1 | |
save | 0 | |
compress | 0 | |
bitrate | '16k' | |
print_text | 0 |
调用了:guan.pdf_to_text, guan.compress_wav_to_mp3
def pdf_to_audio(pdf_path, rate=125, voice=1, read=1, save=0, compress=0, bitrate='16k', print_text=0):
import pyttsx3
import guan
text = guan.pdf_to_text(pdf_path)
text = text.replace('\n', ' ')
if print_text==1:
print(text)
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[voice].id)
engine.setProperty("rate", rate)
if save==1:
import re
filename = re.split('[/,\\\]', pdf_path)[-1][:-4]
engine.save_to_file(text, filename+'.wav')
engine.runAndWait()
print('Wav file saved!')
if compress==1:
import os
os.rename(filename+'.wav', 'temp.wav')
guan.compress_wav_to_mp3('temp.wav', output_filename=filename+'.mp3', bitrate=bitrate)
os.remove('temp.wav')
if read==1:
engine.say(text)
engine.runAndWait()
compress_wav_to_mp3compress_wav_to_mp3(wav_path, output_filename='a.mp3', bitrate='16k')
将wav音频文件压缩成MP3音频文件
| 参数 | 类型 | 默认值 |
|---|---|---|
wav_path | 必填 | |
output_filename | 'a.mp3' | |
bitrate | '16k' |
def compress_wav_to_mp3(wav_path, output_filename='a.mp3', bitrate='16k'):
# Note: Beside the installation of pydub, you may also need download FFmpeg on http://www.ffmpeg.org/download.html and add the bin path to the environment variable.
from pydub import AudioSegment
sound = AudioSegment.from_mp3(wav_path)
sound.export(output_filename,format="mp3",bitrate=bitrate)
convert_wordpress_xml_to_markdownconvert_wordpress_xml_to_markdown(xml_file='./a.xml', convert_content=1, replace_more=[])
将WordPress导出的XML格式文件转换成多个MarkDown格式的文件
| 参数 | 类型 | 默认值 |
|---|---|---|
xml_file | './a.xml' | |
convert_content | 1 | |
replace_more | [] |
def convert_wordpress_xml_to_markdown(xml_file='./a.xml', convert_content=1, replace_more=[]):
import xml.etree.ElementTree as ET
import re
tree = ET.parse(xml_file)
root = tree.getroot()
for item in root.findall('.//item'):
title = item.find('title').text
content = item.find('.//content:encoded', namespaces={'content': 'http://purl.org/rss/1.0/modules/content/'}).text
if convert_content == 1:
try:
content = re.sub(r'<!--.*?-->', '', content)
content = content.replace('<p>', '')
content = content.replace('</p>', '')
content = content.replace('<ol>', '')
content = content.replace('</ol>', '')
content = content.replace('<ul>', '')
content = content.replace('</ul>', '')
content = content.replace('<strong>', '')
content = content.replace('</strong>', '')
content = content.replace('</li>', '')
content = content.replace('<li>', '+ ')
content = content.replace('</h3>', '')
content = re.sub(r'<h2.*?>', '## ', content)
content = re.sub(r'<h3.*?>', '### ', content)
content = re.sub(r'<h4.*?>', '#### ', content)
for replace_item in replace_more:
content = content.replace(replace_item, '')
for _ in range(100):
content = content.replace('\n\n\n', '\n\n')
except:
print(f'提示:字符串替换出现问题!出现问题的内容为:{content}')
else:
pass
markdown_content = f"# {title}\n{content}"
markdown_file_path = f"{title}.md"
cleaned_filename = re.sub(r'[/:*?"<>|\'\\]', ' ', markdown_file_path)
with open(cleaned_filename, 'w', encoding='utf-8') as md_file:
md_file.write(markdown_content)
kelly_formulakelly_formula(p, b, a=1)
凯利公式
| 参数 | 类型 | 默认值 |
|---|---|---|
p | 必填 | |
b | 必填 | |
a | 1 |
def kelly_formula(p, b, a=1):
f=(p/a)-((1-p)/b)
return f
all_stocksall_stocks()
获取所有股票
def all_stocks():
import numpy as np
import akshare as ak
stocks = ak.stock_zh_a_spot_em()
title = np.array(stocks.columns)
stock_data = stocks.values
return title, stock_data
all_stock_symbolsall_stock_symbols()
获取所有股票的代码
调用了:guan.all_stocks
def all_stock_symbols():
import guan
title, stock_data = guan.all_stocks()
stock_symbols = stock_data[:, 1]
return stock_symbols
stock_symbols_classificationstock_symbols_classification()
股票代码的分类
def stock_symbols_classification():
import guan
import re
stock_symbols = guan.all_stock_symbols()
# 上交所主板
stock_symbols_60 = []
for stock_symbol in stock_symbols:
find_600 = re.findall(r'^600', stock_symbol)
find_601 = re.findall(r'^601', stock_symbol)
find_603 = re.findall(r'^603', stock_symbol)
find_605 = re.findall(r'^605', stock_symbol)
if find_600 != [] or find_601 != [] or find_603 != [] or find_605 != []:
stock_symbols_60.append(stock_symbol)
# 深交所主板
stock_symbols_00 = []
for stock_symbol in stock_symbols:
find_000 = re.findall(r'^000', stock_symbol)
find_001 = re.findall(r'^001', stock_symbol)
find_002 = re.findall(r'^002', stock_symbol)
find_003 = re.findall(r'^003', stock_symbol)
if find_000 != [] or find_001 != [] or find_002 != [] or find_003 != []:
stock_symbols_00.append(stock_symbol)
# 创业板
stock_symbols_30 = []
for stock_symbol in stock_symbols:
find_300 = re.findall(r'^300', stock_symbol)
find_301 = re.findall(r'^301', stock_symbol)
find_302 = re.findall(r'^302', stock_symbol)
if find_300 != [] or find_301 != [] or find_302 != []:
stock_symbols_30.append(stock_symbol)
# 科创板
stock_symbols_68 = []
for stock_symbol in stock_symbols:
find_688 = re.findall(r'^688', stock_symbol)
find_689 = re.findall(r'^689', stock_symbol)
if find_688 != [] or find_689 != []:
stock_symbols_68.append(stock_symbol)
# 北交所和新三板
stock_symbols_8_4_9 = []
for stock_symbol in stock_symbols:
find_83 = re.findall(r'^83', stock_symbol)
find_87 = re.findall(r'^87', stock_symbol)
find_430 = re.findall(r'^430', stock_symbol)
find_420 = re.findall(r'^420', stock_symbol)
find_400 = re.findall(r'^400', stock_symbol)
find_920 = re.findall(r'^920', stock_symbol)
if find_83 != [] or find_87 != [] or find_430 != [] or find_420 != [] or find_400 != [] or find_920 != []:
stock_symbols_8_4_9.append(stock_symbol)
# 检查遗漏的股票代码
stock_symbols_others = []
for stock_symbol in stock_symbols:
if stock_symbol not in stock_symbols_60 and stock_symbol not in stock_symbols_00 and stock_symbol not in stock_symbols_30 and stock_symbol not in stock_symbols_68 and stock_symbol not in stock_symbols_8_4_9:
stock_symbols_others.append(stock_symbol)
return stock_symbols_60, stock_symbols_00, stock_symbols_30, stock_symbols_68, stock_symbols_8_4_9, stock_symbols_others
statistics_of_stock_symbols_classificationstatistics_of_stock_symbols_classification()
股票代码各个分类的数量
调用了:guan.stock_symbols_classification
def statistics_of_stock_symbols_classification():
import guan
stock_symbols_60, stock_symbols_00, stock_symbols_30, stock_symbols_68, stock_symbols_8_4, stock_symbols_others = guan.stock_symbols_classification()
num_stocks_60 = len(stock_symbols_60)
num_stocks_00 = len(stock_symbols_00)
num_stocks_30 = len(stock_symbols_30)
num_stocks_68 = len(stock_symbols_68)
num_stocks_8_4 = len(stock_symbols_8_4)
num_stocks_others= len(stock_symbols_others)
return num_stocks_60, num_stocks_00, num_stocks_30, num_stocks_68, num_stocks_8_4, num_stocks_others
find_stock_name_from_symbolfind_stock_name_from_symbol(symbol='000002')
从股票代码获取股票名称
| 参数 | 类型 | 默认值 |
|---|---|---|
symbol | '000002' |
调用了:guan.all_stocks
def find_stock_name_from_symbol(symbol='000002'):
import guan
title, stock_data = guan.all_stocks()
for stock in stock_data:
if symbol in stock:
stock_name = stock[2]
return stock_name
sorted_market_capitalizationsorted_market_capitalization(num=10)
市值排序
| 参数 | 类型 | 默认值 |
|---|---|---|
num | 10 |
调用了:guan.all_stocks
def sorted_market_capitalization(num=10):
import numpy as np
import guan
title, stock_data = guan.all_stocks()
new_stock_data = []
for stock in stock_data:
if np.isnan(float(stock[9])):
continue
else:
new_stock_data.append(stock)
new_stock_data = np.array(new_stock_data)
list_index = np.argsort(new_stock_data[:, 17])
list_index = list_index[::-1]
if num == None:
num = len(list_index)
sorted_array = []
for i0 in range(num):
stock_symbol = new_stock_data[list_index[i0], 1]
stock_name = new_stock_data[list_index[i0], 2]
market_capitalization = new_stock_data[list_index[i0], 17]/1e8
sorted_array.append([i0+1, stock_symbol, stock_name, market_capitalization])
return sorted_array
sorted_market_capitalization_ussorted_market_capitalization_us(num=10)
美股市值排序
| 参数 | 类型 | 默认值 |
|---|---|---|
num | 10 |
def sorted_market_capitalization_us(num=10):
import akshare as ak
import numpy as np
stocks = ak.stock_us_spot_em()
stock_data = stocks.values
new_stock_data = []
for stock in stock_data:
if np.isnan(float(stock[9])):
continue
else:
new_stock_data.append(stock)
new_stock_data = np.array(new_stock_data)
list_index = np.argsort(new_stock_data[:, 9])
list_index = list_index[::-1]
if num == None:
num = len(list_index)
sorted_array = []
for i0 in range(num):
stock_symbol = new_stock_data[list_index[i0], 15]
stock_name = new_stock_data[list_index[i0], 1]
market_capitalization = new_stock_data[list_index[i0], 9]/1e8
sorted_array.append([i0+1, stock_symbol, stock_name, market_capitalization])
return sorted_array
history_data_of_one_stockhistory_data_of_one_stock(symbol='000002', period='daily', start_date='19000101', end_date='21000101')
获取单个股票的历史数据
| 参数 | 类型 | 默认值 |
|---|---|---|
symbol | '000002' | |
period | 'daily' | |
start_date | '19000101' | |
end_date | '21000101' |
def history_data_of_one_stock(symbol='000002', period='daily', start_date="19000101", end_date='21000101'):
# period = 'daily'
# period = 'weekly'
# period = 'monthly'
import numpy as np
import akshare as ak
stock = ak.stock_zh_a_hist(symbol=symbol, period=period, start_date=start_date, end_date=end_date)
title = np.array(stock.columns)
stock_data = stock.values[::-1]
return title, stock_data
plot_stock_lineplot_stock_line(date_array, opening_array, closing_array, high_array, low_array, lw_open_close=6, lw_high_low=2, xlabel='date', ylabel='price', title='', fontsize=20, labelsize=20, adjust_bottom=0.2, adjust_left=0.2, fontfamily='Times New Roman')
绘制股票图
| 参数 | 类型 | 默认值 |
|---|---|---|
date_array | 必填 | |
opening_array | 必填 | |
closing_array | 必填 | |
high_array | 必填 | |
low_array | 必填 | |
lw_open_close | 6 | |
lw_high_low | 2 | |
xlabel | 'date' | |
ylabel | 'price' | |
title | '' | |
fontsize | 20 | |
labelsize | 20 | |
adjust_bottom | 0.2 | |
adjust_left | 0.2 | |
fontfamily | 'Times New Roman' |
调用了:guan.import_plt_and_start_fig_ax
def plot_stock_line(date_array, opening_array, closing_array, high_array, low_array, lw_open_close=6, lw_high_low=2, xlabel='date', ylabel='price', title='', fontsize=20, labelsize=20, adjust_bottom=0.2, adjust_left=0.2, fontfamily='Times New Roman'):
import guan
plt, fig, ax = guan.import_plt_and_start_fig_ax(adjust_bottom=adjust_bottom, adjust_left=adjust_left, labelsize=labelsize, fontfamily=fontfamily)
if fontfamily=='Times New Roman':
ax.set_title(title, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_xlabel(xlabel, fontsize=fontsize, fontfamily='Times New Roman')
ax.set_ylabel(ylabel, fontsize=fontsize, fontfamily='Times New Roman')
else:
ax.set_title(title, fontsize=fontsize)
ax.set_xlabel(xlabel, fontsize=fontsize)
ax.set_ylabel(ylabel, fontsize=fontsize)
for i0 in range(len(date_array)):
if opening_array[i0] <= closing_array[i0]:
ax.vlines(date_array[i0], opening_array[i0], closing_array[i0], linestyle='-', color='red', lw=lw_open_close)
ax.vlines(date_array[i0], low_array[i0], high_array[i0], color='red', linestyle='-', lw=lw_high_low)
else:
ax.vlines(date_array[i0], opening_array[i0], closing_array[i0], linestyle='-', color='green', lw=lw_open_close)
ax.vlines(date_array[i0], low_array[i0], high_array[i0], color='green', linestyle='-', lw=lw_high_low)
plt.show()
plt.close('all')
statistics_of_guan_packagestatistics_of_guan_package(function_name=None)
Guan软件包的使用统计(仅仅统计装机数和import次数)
| 参数 | 类型 | 默认值 |
|---|---|---|
function_name | None |
调用了:guan.get_date, guan.get_time, guan.get_current_version, guan.get_mac_address
def statistics_of_guan_package(function_name=None):
import guan
try:
import socket
datetime_date = guan.get_date()
datetime_time = guan.get_time()
current_version = guan.get_current_version('guan')
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.settimeout(0.5)
client_socket.connect(('socket.guanjihuan.com', 12345))
mac_address = guan.get_mac_address()
if function_name == None:
message = {
'server': 'py.guanjihuan.com',
'date': datetime_date,
'time': datetime_time,
'version': current_version,
'MAC_address': mac_address,
}
else:
message = {
'server': 'py.guanjihuan.com',
'date': datetime_date,
'time': datetime_time,
'version': current_version,
'MAC_address': mac_address,
'function_name': function_name
}
import json
send_message = json.dumps(message)
client_socket.send(send_message.encode())
client_socket.close()
except:
pass
notification_of_upgradenotification_of_upgrade(timeout=5)
Guan软件包升级检查和提示(对于无法连接或者版本为最新的情况,检查结果都没有提示)
| 参数 | 类型 | 默认值 |
|---|---|---|
timeout | 5 |
调用了:guan.get_latest_version, guan.get_current_version
def notification_of_upgrade(timeout=5):
try:
import guan
latest_version = guan.get_latest_version(package_name='guan', timeout=timeout)
current_version = guan.get_current_version('guan')
if latest_version != None and current_version != None:
if latest_version != current_version:
print('升级提示:您当前使用的版本是 guan-'+current_version+',目前已经有最新版本 guan-'+latest_version+'。您可以通过以下命令对软件包进行升级:pip install --upgrade guan -i https://pypi.python.org/simple 或 pip install --upgrade guan')
except:
pass
自定义类和使用自定义类的函数 custom classes and functions using objects of custom classes
convert_atom_object_list_to_multiple_listsconvert_atom_object_list_to_multiple_lists(atom_object_list)
将原子对象列表转成多个独立列表
| 参数 | 类型 | 默认值 |
|---|---|---|
atom_object_list | 必填 |
def convert_atom_object_list_to_multiple_lists(atom_object_list):
name_list = []
index_list = []
x_list = []
y_list = []
z_list = []
energy_list = []
for atom_object in atom_object_list:
name_list.append(atom_object.name)
index_list.append(atom_object.index)
x_list.append(atom_object.x)
y_list.append(atom_object.y)
z_list.append(atom_object.z)
energy_list.append(atom_object.energy)
return name_list, index_list, x_list, y_list, z_list, energy_list
自定义类和使用自定义类的函数 custom classes and functions using objects of custom classes
convert_atom_object_list_to_atom_dict_listconvert_atom_object_list_to_atom_dict_list(atom_object_list)
将原子对象列表转成原子字典列表
| 参数 | 类型 | 默认值 |
|---|---|---|
atom_object_list | 必填 |
def convert_atom_object_list_to_atom_dict_list(atom_object_list):
atom_dict_list = []
for atom_object in atom_object_list:
atom_dict = {
'name': atom_object.name,
'index': atom_object.index,
'x': atom_object.x,
'y': atom_object.y,
'z': atom_object.z,
'energy': atom_object.energy,
}
atom_dict_list.append(atom_dict)
return atom_dict_list
自定义类和使用自定义类的函数 custom classes and functions using objects of custom classes
get_coordinate_array_from_atom_object_listget_coordinate_array_from_atom_object_list(atom_object_list)
从原子对象列表中获取 (x, y) 坐标数组
| 参数 | 类型 | 默认值 |
|---|---|---|
atom_object_list | 必填 |
def get_coordinate_array_from_atom_object_list(atom_object_list):
coordinate_array = []
for atom in atom_object_list:
x = atom.x
y = atom.y
coordinate_array.append([x, y])
return coordinate_array
自定义类和使用自定义类的函数 custom classes and functions using objects of custom classes
get_max_min_x_y_from_atom_object_listget_max_min_x_y_from_atom_object_list(atom_object_list)
从原子对象列表中获取 x 和 y 的最大值和最小值
| 参数 | 类型 | 默认值 |
|---|---|---|
atom_object_list | 必填 |
调用了:guan.get_coordinate_array_from_atom_object_list
def get_max_min_x_y_from_atom_object_list(atom_object_list):
import guan
coordinate_array = guan.get_coordinate_array_from_atom_object_list(atom_object_list)
x_array = []
for coordinate in coordinate_array:
x_array.append(coordinate[0])
y_array = []
for coordinate in coordinate_array:
y_array.append(coordinate[1])
max_x = max(x_array)
min_x = min(x_array)
max_y = max(y_array)
min_y = min(y_array)
return max_x, min_x, max_y, min_y
自定义类和使用自定义类的函数 custom classes and functions using objects of custom classes
get_index_via_coordinate_from_atom_object_listget_index_via_coordinate_from_atom_object_list(atom_object_list, x=0, y=0, z=0, eta=0.001)
从原子对象列表中获取满足坐标条件的索引
| 参数 | 类型 | 默认值 |
|---|---|---|
atom_object_list | 必填 | |
x | 0 | |
y | 0 | |
z | 0 | |
eta | 0.001 |
def get_index_via_coordinate_from_atom_object_list(atom_object_list, x=0, y=0, z=0, eta=1e-3):
for atom in atom_object_list:
x_i = atom.x
y_i = atom.y
z_i = atom.z
index = atom.index
if abs(x-x_i)<eta and abs(y-y_i)<eta and abs(z-z_i)<eta:
return index
自定义类和使用自定义类的函数 custom classes and functions using objects of custom classes
initialize_hamiltonian_from_atom_object_listinitialize_hamiltonian_from_atom_object_list(atom_object_list)
根据原子对象列表来初始化哈密顿量
| 参数 | 类型 | 默认值 |
|---|---|---|
atom_object_list | 必填 |
def initialize_hamiltonian_from_atom_object_list(atom_object_list):
import numpy as np
import guan
dim = guan.dimension_of_array(atom_object_list[0].energy)
num = len(atom_object_list)
hamiltonian = np.zeros((dim*num, dim*num))
for i0 in range(num):
hamiltonian[i0*dim+0:i0*dim+dim, i0*dim+0:i0*dim+dim] = atom_object_list[i0].energy
return hamiltonian
废弃函数/版本兼容(不推荐使用,并可能在未来的版本中被移除)
chatchat(prompt='你好', model=1, stream=1, stream_label=0)
AI 对话(当前默认模型为 'hunyuan-lite',无记忆)
| 参数 | 类型 | 默认值 |
|---|---|---|
prompt | '你好' | |
model | 1 | |
stream | 1 | |
stream_label | 0 |
def chat(prompt='你好', model=1, stream=1, stream_label=0):
import requests
url = "http://api.guanjihuan.com/chat"
data = {
"prompt": prompt,
"model": model,
}
if stream == 1:
if stream_label == 1:
print('\n--- Start Chat Stream Message ---\n')
requests_response = requests.post(url, json=data, stream=True)
response = ''
if requests_response.status_code == 200:
for line in requests_response.iter_lines():
if line:
if stream == 1:
print(line.decode('utf-8'), end='', flush=True)
response += line.decode('utf-8')
print()
else:
pass
if stream == 1:
if stream_label == 1:
print('\n--- End Chat Stream Message ---\n')
return response
废弃函数/版本兼容(不推荐使用,并可能在未来的版本中被移除)
chat_with_function_codechat_with_function_code(function_name, prompt='', model=1, stream=1)
加上函数代码的 AI 对话(当前默认模型为 'hunyuan-lite',无记忆)
| 参数 | 类型 | 默认值 |
|---|---|---|
function_name | 必填 | |
prompt | '' | |
model | 1 | |
stream | 1 |
调用了:guan.get_source, guan.chat
def chat_with_function_code(function_name, prompt='', model=1, stream=1):
import guan
function_source = guan.get_source(function_name)
if prompt == '':
response = guan.chat(prompt=function_source, model=model, stream=stream)
else:
response = guan.chat(prompt=function_source+'\n\n'+prompt, model=model, stream=stream)
return response
废弃函数/版本兼容(不推荐使用,并可能在未来的版本中被移除)
auto_chatauto_chat(prompt='你好', round=2, model=1, stream=1)
机器人自动对话(当前默认模型为 'hunyuan-lite',无记忆)
| 参数 | 类型 | 默认值 |
|---|---|---|
prompt | '你好' | |
round | 2 | |
model | 1 | |
stream | 1 |
调用了:guan.chat
def auto_chat(prompt='你好', round=2, model=1, stream=1):
import guan
response0 = prompt
for i0 in range(round):
print(f'\n【对话第 {i0+1} 轮】\n')
print('机器人 1: ')
response1 = guan.chat(prompt=response0, model=model, stream=stream)
print('机器人 2: ')
response0 = guan.chat(prompt=response1, model=model, stream=stream)
废弃函数/版本兼容(不推荐使用,并可能在未来的版本中被移除)
auto_chat_with_guideauto_chat_with_guide(prompt='你好', guide_message='(回答字数少于30个字,最后反问我一个问题)', round=5, model=1, stream=1)
机器人自动对话(引导对话)(当前默认模型为 'hunyuan-lite',无记忆)
| 参数 | 类型 | 默认值 |
|---|---|---|
prompt | '你好' | |
guide_message | '(回答字数少于30个字,最后反问我一个问题)' | |
round | 5 | |
model | 1 | |
stream | 1 |
调用了:guan.chat
def auto_chat_with_guide(prompt='你好', guide_message='(回答字数少于30个字,最后反问我一个问题)', round=5, model=1, stream=1):
import guan
response0 = prompt
for i0 in range(round):
print(f'\n【对话第 {i0+1} 轮】\n')
print('机器人 1: ')
response1 = guan.chat(prompt=response0+guide_message, model=model, stream=stream)
print('机器人 2: ')
response0 = guan.chat(prompt=response1+guide_message, model=model, stream=stream)
废弃函数/版本兼容(不推荐使用,并可能在未来的版本中被移除)
make_sh_filemake_sh_file(sh_filename='a', command_line='python a.py', cpu_num=1, task_name='task', cd_dir=0)
| 参数 | 类型 | 默认值 |
|---|---|---|
sh_filename | 'a' | |
command_line | 'python a.py' | |
cpu_num | 1 | |
task_name | 'task' | |
cd_dir | 0 |
调用了:guan.make_sh_file_for_qsub
def make_sh_file(sh_filename='a', command_line='python a.py', cpu_num=1, task_name='task', cd_dir=0):
import guan
print('Warning: The current function name has been deprecated, which will be deleted in the future version. Please change it into guan.make_sh_file_for_qsub().')
guan.make_sh_file_for_qsub(sh_filename=sh_filename, command_line=command_line, cpu_num=cpu_num, task_name=task_name, cd_dir=cd_dir)
废弃函数/版本兼容(不推荐使用,并可能在未来的版本中被移除)
plot_without_starting_figplot_without_starting_fig(plt, fig, ax, x_array, y_array, xlabel='x', ylabel='y', title='', fontsize=20, style='', y_min=None, y_max=None, linewidth=None, markersize=None, color=None, fontfamily='Times New Roman')
| 参数 | 类型 | 默认值 |
|---|---|---|
plt | 必填 | |
fig | 必填 | |
ax | 必填 | |
x_array | 必填 | |
y_array | 必填 | |
xlabel | 'x' | |
ylabel | 'y' | |
title | '' | |
fontsize | 20 | |
style | '' | |
y_min | None | |
y_max | None | |
linewidth | None | |
markersize | None | |
color | None | |
fontfamily | 'Times New Roman' |
调用了:guan.plot_without_starting_fig_ax
def plot_without_starting_fig(plt, fig, ax, x_array, y_array, xlabel='x', ylabel='y', title='', fontsize=20, style='', y_min=None, y_max=None, linewidth=None, markersize=None, color=None, fontfamily='Times New Roman'):
import guan
print('Warning: The current function name has been deprecated, which will be deleted in the future version. Please change it into guan.plot_without_starting_fig_ax().')
guan.plot_without_starting_fig_ax(plt, fig, ax, x_array, y_array, xlabel=xlabel, ylabel=ylabel, title=title, fontsize=fontsize, style=style, y_min=y_min, y_max=y_max, linewidth=linewidth, markersize=markersize, color=color, fontfamily=fontfamily)
废弃函数/版本兼容(不推荐使用,并可能在未来的版本中被移除)
draw_dots_and_lines_without_starting_figdraw_dots_and_lines_without_starting_fig(plt, fig, ax, coordinate_array, draw_dots=1, draw_lines=1, max_distance=1, line_style='-k', linewidth=1, dot_style='ro', markersize=3)
| 参数 | 类型 | 默认值 |
|---|---|---|
plt | 必填 | |
fig | 必填 | |
ax | 必填 | |
coordinate_array | 必填 | |
draw_dots | 1 | |
draw_lines | 1 | |
max_distance | 1 | |
line_style | '-k' | |
linewidth | 1 | |
dot_style | 'ro' | |
markersize | 3 |
调用了:guan.draw_dots_and_lines_without_starting_fig_ax
def draw_dots_and_lines_without_starting_fig(plt, fig, ax, coordinate_array, draw_dots=1, draw_lines=1, max_distance=1, line_style='-k', linewidth=1, dot_style='ro', markersize=3):
import guan
print('Warning: The current function name has been deprecated, which will be deleted in the future version. Please change it into guan.draw_dots_and_lines_without_starting_fig_ax().')
guan.draw_dots_and_lines_without_starting_fig_ax(plt, fig, ax, coordinate_array, draw_dots=draw_dots, draw_lines=draw_lines, max_distance=max_distance, line_style=line_style, linewidth=linewidth, dot_style=dot_style, markersize=markersize)
废弃函数/版本兼容(不推荐使用,并可能在未来的版本中被移除)
get_days_of_the_current_monthget_days_of_the_current_month(str_or_datetime='str')
| 参数 | 类型 | 默认值 |
|---|---|---|
str_or_datetime | 'str' |
调用了:guan.get_date_array_of_the_current_month
def get_days_of_the_current_month(str_or_datetime='str'):
import guan
print('Warning: The current function name has been deprecated, which will be deleted in the future version. Please change it into guan.get_date_array_of_the_current_month().')
date_array = guan.get_date_array_of_the_current_month(str_or_datetime=str_or_datetime)
return date_array
废弃函数/版本兼容(不推荐使用,并可能在未来的版本中被移除)
get_days_of_the_last_monthget_days_of_the_last_month(str_or_datetime='str')
| 参数 | 类型 | 默认值 |
|---|---|---|
str_or_datetime | 'str' |
调用了:guan.get_date_array_of_the_last_month
def get_days_of_the_last_month(str_or_datetime='str'):
import guan
print('Warning: The current function name has been deprecated, which will be deleted in the future version. Please change it into guan.get_date_array_of_the_last_month().')
date_array = guan.get_date_array_of_the_last_month(str_or_datetime=str_or_datetime)
return date_array
废弃函数/版本兼容(不推荐使用,并可能在未来的版本中被移除)
get_days_of_the_month_before_lastget_days_of_the_month_before_last(str_or_datetime='str')
| 参数 | 类型 | 默认值 |
|---|---|---|
str_or_datetime | 'str' |
调用了:guan.get_date_array_of_the_month_before_last
def get_days_of_the_month_before_last(str_or_datetime='str'):
import guan
print('Warning: The current function name has been deprecated, which will be deleted in the future version. Please change it into guan.get_date_array_of_the_month_before_last().')
date_array = guan.get_date_array_of_the_month_before_last(str_or_datetime=str_or_datetime)
return date_array
废弃函数/版本兼容(不推荐使用,并可能在未来的版本中被移除)
pdf_to_textpdf_to_text(pdf_path)
| 参数 | 类型 | 默认值 |
|---|---|---|
pdf_path | 必填 |
调用了:guan.pdf_to_text_with_pdfminer3k
def pdf_to_text(pdf_path):
import guan
print('Warning: The current function name has been deprecated, which will be deleted in the future version. Please change it into guan.pdf_to_text_with_pdfminer3k().')
content = guan.pdf_to_text_with_pdfminer3k(pdf_path)
return content
废弃函数/版本兼容(不推荐使用,并可能在未来的版本中被移除)
statistics_with_day_and_timestatistics_with_day_and_time(content='', filename='time_logging', file_format='.txt')
| 参数 | 类型 | 默认值 |
|---|---|---|
content | '' | |
filename | 'time_logging' | |
file_format | '.txt' |
调用了:guan.logging_with_day_and_time
def statistics_with_day_and_time(content='', filename='time_logging', file_format='.txt'):
import guan
print('Warning: The current function name has been deprecated, which will be deleted in the future version. Please change it into guan.logging_with_day_and_time().')
guan.logging_with_day_and_time(content=content, filename=filename, file_format=file_format)