Compare commits

...

15 Commits

Author SHA1 Message Date
b60e485691 0.1.186 2025-08-15 15:40:19 +08:00
28118fbd88 0.1.185 2025-08-15 13:48:05 +08:00
92221832d6 0.1.183 2025-08-02 11:57:07 +08:00
c068394f9b 0.1.182 2025-07-11 15:35:47 +08:00
e65ea73992 0.1.181 2025-07-10 16:14:06 +08:00
8f0bae617d 0.1.179 2025-07-10 09:45:49 +08:00
9b92f0df24 0.1.178 2025-04-22 02:40:46 +08:00
f4a7e70c82 0.1.177 2025-04-13 04:11:39 +08:00
b0e29a164a 0.1.176 2025-04-08 10:09:37 +08:00
c35688a49e 0.1.175 2025-03-24 18:00:26 +08:00
83601c45af 0.1.174 2025-03-24 17:49:26 +08:00
0de9394118 0.1.173 2025-03-24 17:38:56 +08:00
944bbc6a77 0.1.172 2025-03-24 05:04:11 +08:00
0d5c72dc1f 0.1.171 2025-03-24 04:37:54 +08:00
7176bc5d57 0.1.170 2025-03-23 20:42:10 +08:00
12 changed files with 407 additions and 269 deletions

View File

@@ -1,7 +1,7 @@
[metadata]
# replace with your username:
name = guan
version = 0.1.169
version = 0.1.186
author = guanjihuan
author_email = guanjihuan@163.com
description = An open source python package

View File

@@ -1,6 +1,6 @@
Metadata-Version: 2.4
Name: guan
Version: 0.1.169
Version: 0.1.186
Summary: An open source python package
Home-page: https://py.guanjihuan.com
Author: guanjihuan

View File

@@ -8,14 +8,11 @@ src/guan/Hamiltonian_of_examples.py
src/guan/__init__.py
src/guan/band_structures_and_wave_functions.py
src/guan/basic_functions.py
src/guan/custom_classes.py
src/guan/data_processing.py
src/guan/decorators.py
src/guan/density_of_states.py
src/guan/deprecated.py
src/guan/figure_plotting.py
src/guan/file_reading_and_writing.py
src/guan/functions_using_objects_of_custom_classes.py
src/guan/machine_learning.py
src/guan/others.py
src/guan/quantum_transport.py

View File

@@ -14,7 +14,4 @@ from .figure_plotting import *
from .data_processing import *
from .decorators import *
from .others import *
from .custom_classes import *
from .functions_using_objects_of_custom_classes import *
from .deprecated import *
statistics_of_guan_package()

View File

@@ -1,12 +1,15 @@
# Module: band_structures_and_wave_functions
# 计算哈密顿量的本征值
def calculate_eigenvalue(hamiltonian):
def calculate_eigenvalue(hamiltonian, hermitian=True):
import numpy as np
if np.array(hamiltonian).shape==():
eigenvalue = np.real(hamiltonian)
else:
eigenvalue, eigenvector = np.linalg.eigh(hamiltonian)
if hermitian:
eigenvalue, eigenvector = np.linalg.eigh(hamiltonian)
else:
eigenvalue, eigenvector = np.linalg.eig(hamiltonian)
return eigenvalue
# 输入哈密顿量函数(带一组参数),计算一组参数下的本征值,返回本征值向量组
@@ -65,10 +68,13 @@ def calculate_eigenvalue_with_two_parameters(x_array, y_array, hamiltonian_funct
i0 += 1
return eigenvalue_array
# 计算哈密顿量的本征矢(厄密矩阵)
def calculate_eigenvector(hamiltonian):
# 计算哈密顿量的本征矢
def calculate_eigenvector(hamiltonian, hermitian=True):
import numpy as np
eigenvalue, eigenvector = np.linalg.eigh(hamiltonian)
if hermitian:
eigenvalue, eigenvector = np.linalg.eigh(hamiltonian)
else:
eigenvalue, eigenvector = np.linalg.eig(hamiltonian)
return eigenvector
# 施密特正交化

View File

@@ -1,11 +0,0 @@
# Module: custom_classes
# 原子类
class Atom:
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

View File

@@ -1,7 +1,7 @@
# Module: data_processing
# 获取运行的日期和时间并写入文件
def statistics_with_day_and_time(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')
@@ -9,9 +9,9 @@ def statistics_with_day_and_time(content='', filename='time_logging', file_forma
if content == '':
f2.write(datetime_today+' '+datetime_time+'\n')
else:
f2.write(datetime_today+' '+datetime_time+' '+content+'\n')
f2.write(datetime_today+' '+datetime_time+' '+str(content)+'\n')
# 使用该函数获取函数计算时间(秒)
# 使用该函数运行某个函数并获取函数计算时间(秒)
def timer(function_name, *args, **kwargs):
import time
start = time.time()
@@ -20,13 +20,93 @@ def timer(function_name, *args, **kwargs):
print(f"Running time of {function_name.__name__}: {end - start} seconds")
return result
# 使用该函数实现 try except 结构
# 使用该函数运行某个函数并实现 try-except-pass 结构
def try_except(function_name, *args, **kwargs):
try:
return function_name(*args, **kwargs)
except:
pass
# 使用 multiprocessing.Pool 实现自动分配任务并行
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
# 循环一个参数计算某个函数,并返回计算结果的数组
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
# 循环两个参数计算某个函数,并返回计算结果的数组
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
# 循环三个参数计算某个函数,并返回计算结果的数组
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
# 打印数组
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()
# 以显示编号的样式,打印数组
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)
# 获取矩阵的维度考虑单一数值的矩阵维度为1
def dimension_of_array(array):
import numpy as np
@@ -37,6 +117,78 @@ def dimension_of_array(array):
dim = array.shape[0]
return dim
# 检查矩阵是否为厄米矩阵相对误差为1e-5)
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))
# 判断一个数是否接近于整数
def close_to_integer(value, abs_tol=1e-3):
import math
result = math.isclose(value, round(value), abs_tol=abs_tol)
return result
# 从列表中删除某个匹配的元素
def remove_item_in_one_array(array, item):
new_array = [x for x in array if x != item]
return new_array
# 根据子数组的第index个元素对子数组进行排序index从0开始
def sort_array_by_index_element(original_array, index):
sorted_array = sorted(original_array, key=lambda x: x[index])
return sorted_array
# 随机获得一个整数,左闭右闭
def get_random_number(start=0, end=1):
import random
rand_number = random.randint(start, end) # 左闭右闭 [start, end]
return rand_number
# 选取一个种子生成固定的随机整数,左闭右开
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
# 使用Numpy库计算总体标准差
def standard_deviation(data_array):
import numpy as np
std_result = np.std(data_array)
return std_result
# ​​使用公式计算总体标准差
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
# 获取两个模式之间的字符串
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 ''
# 删除某个字符串中两个模式之间的内容,返回新字符串
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)
# 获取旋转矩阵(输入为角度)
def get_rotation_matrix(angle_deg):
import numpy as np
@@ -88,11 +240,6 @@ def convert_matrix_data_into_xyz_data(x_array, y_array, matrix):
z_array[ix*len_y+iy] = matrix[ix, iy]
return x_array, y_array, z_array
# 从列表中删除某个匹配的元素
def remove_item_in_one_array(array, item):
new_array = [x for x in array if x != item]
return new_array
# 并行计算前的预处理,把参数分成多份
def preprocess_for_parallel_calculations(parameter_array_all, task_num=1, task_index=0):
import numpy as np
@@ -127,78 +274,6 @@ def run_programs_sequentially(program_files=['./a.py', './b.py'], execute='pytho
end = time.time()
print('Total running time = '+str((end-start)/60)+' min')
# 判断一个数是否接近于整数
def close_to_integer(value, abs_tol=1e-3):
import math
result = math.isclose(value, round(value), abs_tol=abs_tol)
return result
# 根据子数组的第index个元素对子数组进行排序index从0开始
def sort_array_by_index_element(original_array, index):
sorted_array = sorted(original_array, key=lambda x: x[index])
return sorted_array
# 随机获得一个整数,左闭右闭
def get_random_number(start=0, end=1):
import random
rand_number = random.randint(start, end) # 左闭右闭 [start, end]
return rand_number
# 选取一个种子生成固定的随机整数,左闭右开
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
# 获取两个模式之间的字符串
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 ''
# 删除某个字符串中两个模式之间的内容,返回新字符串
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)
# 打印数组
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()
# 以显示编号的样式,打印数组
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)
# 根据一定的字符长度来分割文本
def split_text(text, width=100):
split_text_list = [text[i:i+width] for i in range(0, len(text), width)]

View File

@@ -1,40 +0,0 @@
# Module: deprecated
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)
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)
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)
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
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
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
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

View File

@@ -1,7 +1,7 @@
# Module: file_reading_and_writing
# 使用pickle将变量保存到文件支持几乎所有对象类型
def dump_data(data, filename, 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)
@@ -14,7 +14,7 @@ def load_data(filename, file_format='.pkl'):
return data
# 使用NumPy保存数组变量到npy文件二进制文件
def save_npy_data(data, filename):
def save_npy_data(data, filename='a'):
import numpy as np
np.save(filename+'.npy', data)
@@ -25,7 +25,7 @@ def load_npy_data(filename):
return data
# 使用NumPy保存数组变量到TXT文件文本文件
def save_txt_data(data, filename):
def save_txt_data(data, filename='a'):
import numpy as np
np.savetxt(filename+'.txt', data)
@@ -244,11 +244,16 @@ def write_two_dimensional_data_without_xy_array_and_without_opening_file(matrix,
f.write('\n')
# 创建一个sh文件用于提交任务PBS
def make_sh_file_for_qsub(sh_filename='a', command_line='python a.py', cpu_num=1, task_name='task', cd_dir=0):
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' \
+'#PBS -N '+task_name+'\n' \
+'#PBS -l nodes=1:ppn='+str(cpu_num)+'\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
@@ -256,11 +261,13 @@ def make_sh_file_for_qsub(sh_filename='a', command_line='python a.py', cpu_num=1
f.write(sh_content)
# 创建一个sh文件用于提交任务Slurm
def make_sh_file_for_sbatch(sh_filename='a', command_line='python a.py', cpu_num=1, task_name='task', cd_dir=0):
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' \
+'#SBATCH --job-name='+task_name+'\n' \
+'#SBATCH --cpus-per-task='+str(cpu_num)+'\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
@@ -271,10 +278,10 @@ def make_sh_file_for_sbatch(sh_filename='a', command_line='python a.py', cpu_num
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' \
+'#BSUB -J '+task_name+'\n' \
+'#BSUB -n '+str(cpu_num)+'\n'
+f'#BSUB -J {task_name}\n'
if bsub_q==1:
sh_content += '#BSUB -q '+queue_name+'\n'
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
@@ -414,13 +421,15 @@ def write_matrix_in_markdown_format(matrix, filename='a'):
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):
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')

View File

@@ -1,62 +0,0 @@
# functions_using_objects_of_custom_classes
# 将原子对象列表转成原子字典列表
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
# 从原子对象列表中获取 (x, y) 坐标数组
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
# 从原子对象列表中获取 x 和 y 的最大值和最小值
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
# 从原子对象列表中获取满足坐标条件的索引
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
# 根据原子对象列表来初始化哈密顿量
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

View File

@@ -59,33 +59,6 @@ def auto_chat_with_guide(prompt='你好', guide_message='回答字数少于30
print('机器人 2: ')
response0 = guan.chat(prompt=response1+guide_message, model=model, stream=stream)
# 在云端服务器上运行函数(需要函数是独立可运行的代码)
def run(function_name, *args, **kwargs):
import requests
import guan
url = "http://run.guanjihuan.com/run_function"
function_source = guan.get_source(function_name)
data = {
"function_name": function_name.__name__,
"function_source": function_source,
'args': str(args),
'kwargs': str(kwargs),
}
return_data = None
try:
response = requests.post(url, json=data)
if response.status_code == 200:
result = response.json()
print_data = result['print_data']
print(print_data, end='')
encoded_return_data = result['encoded_return_data']
import base64
import pickle
return_data = pickle.loads(base64.b64decode(encoded_return_data))
except:
pass
return return_data
# CPU性能测试十亿次循环的浮点加法运算的时间约30秒左右
def cpu_test_with_addition(print_show=1):
import time
@@ -328,26 +301,86 @@ def get_memory_info():
used_memory_percent = memory_info.percent
return total_memory, used_memory, available_memory, used_memory_percent
# 获取CPU的平均使用率
# 获取CPU使用率基于性能计数器适用于Windows系统
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
# 获取CPU使用率基于/proc/stat适用于Linux系统
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
# 使用psutil获取CPU的平均使用率
def get_cpu_usage(interval=1):
import psutil
cpu_usage = psutil.cpu_percent(interval=interval)
return cpu_usage
# 获取每个CPU核心的使用率返回列表
# 使用psutil获取每个CPU核心的使用率返回列表
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
# 获取使用率最高的CPU核心的使用率
# 使用psutil获取使用率最高的CPU核心的使用率
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
# 获取非零使用率的CPU核心的平均使用率
# 使用psutil获取非零使用率的CPU核心的平均使用率
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)
@@ -355,7 +388,7 @@ def get_cpu_averaged_usage_for_non_zero_cores(interval=1):
averaged_cpu_usage = sum(cpu_usage_array_per_core_new)/len(cpu_usage_array_per_core_new)
return averaged_cpu_usage
# 在一定数量周期内得到CPU的使用率信息。默认为1秒钟收集一次(interval+sleep_interval)*times 为收集的时间范围范围默认为60秒即1分钟后返回列表总共得到60组数据。其中数字第一列和第二列分别是平均值和最大值。
# 使用psutil在一定数量周期内得到CPU的使用率信息。默认为1秒钟收集一次(interval+sleep_interval)*times 为收集的时间范围范围默认为60秒即1分钟后返回列表总共得到60组数据。其中数字第一列和第二列分别是平均值和最大值。
def get_cpu_information_for_times(interval=1, sleep_interval=0, times=60):
import guan
import time
@@ -375,7 +408,7 @@ def get_cpu_information_for_times(interval=1, sleep_interval=0, times=60):
time.sleep(sleep_interval)
return cpu_information_array
# 将得到的CPU的使用率信息写入文件。默认为1分钟收集一次(interval+sleep_interval)*times 为收集的时间范围范围默认为60分钟即1小时写入文件一次总共得到60组数据。其中数字第一列和第二列分别是平均值和最大值。
# 使用psutil获取CPU的使用率将得到的CPU的使用率信息写入文件。默认为1分钟收集一次(interval+sleep_interval)*times 为收集的时间范围范围默认为60分钟即1小时写入文件一次总共得到60组数据。其中数字第一列和第二列分别是平均值和最大值。
def write_cpu_information_to_file(filename='./cpu_usage', interval=1, sleep_interval=59, times=60):
import guan
guan.make_file(filename+'.txt')
@@ -393,7 +426,7 @@ def write_cpu_information_to_file(filename='./cpu_usage', interval=1, sleep_inte
f.write('\n')
f.close()
# 画CPU的使用率图。默认为画最近的60个数据以及不画CPU核心的最大使用率。
# 使用psutil获取CPU的使用率画CPU的使用率图。默认为画最近的60个数据以及不画CPU核心的最大使用率。
def plot_cpu_information(filename='./cpu_usage', recent_num=60, max_cpu=0):
import guan
from datetime import datetime
@@ -426,7 +459,7 @@ def plot_cpu_information(filename='./cpu_usage', recent_num=60, max_cpu=0):
plt.legend(legend_array)
plt.show()
# 画详细的CPU的使用率图分CPU核心画图。
# 使用psutil获取CPU的使用率画详细的CPU的使用率图分CPU核心画图。
def plot_detailed_cpu_information(filename='./cpu_usage', recent_num=60):
import guan
from datetime import datetime
@@ -1006,7 +1039,8 @@ def stock_symbols_classification():
for stock_symbol in stock_symbols:
find_300 = re.findall(r'^300', stock_symbol)
find_301 = re.findall(r'^301', stock_symbol)
if find_300 != [] or find_301 != []:
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 = []
@@ -1015,24 +1049,23 @@ def stock_symbols_classification():
find_689 = re.findall(r'^689', stock_symbol)
if find_688 != [] or find_689 != []:
stock_symbols_68.append(stock_symbol)
# 新三板
stock_symbols_8_4 = []
# 北交所和新三板
stock_symbols_8_4_9 = []
for stock_symbol in stock_symbols:
find_82 = re.findall(r'^82', stock_symbol)
find_83 = re.findall(r'^83', stock_symbol)
find_87 = re.findall(r'^87', stock_symbol)
find_88 = re.findall(r'^88', 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)
if find_82 != [] or find_83 != [] or find_87 != [] or find_88 != [] or find_430 != [] or find_420 != [] or find_400 != []:
stock_symbols_8_4.append(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:
stock_symbols_others.others.append(stock_symbol)
return stock_symbols_60, stock_symbols_00, stock_symbols_30, stock_symbols_68, stock_symbols_8_4, stock_symbols_others
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
# 股票代码各个分类的数量
def statistics_of_stock_symbols_classification():
@@ -1174,7 +1207,7 @@ def statistics_of_guan_package(function_name=None):
except:
pass
# Guan软件包升级检查和提示如果无法连接或者版本为最新,那么均没有提示)
# Guan软件包升级检查和提示对于无法连接或者版本为最新的情况,检查结果都没有提示)
def notification_of_upgrade(timeout=5):
try:
import guan
@@ -1184,4 +1217,140 @@ def notification_of_upgrade(timeout=5):
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
pass
# --- 自定义类和使用自定义类的函数 custom classes and functions using objects of custom classes ---
# 原子类
class Atom:
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
# 将原子对象列表转成多个独立列表
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
# 将原子对象列表转成原子字典列表
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
# 从原子对象列表中获取 (x, y) 坐标数组
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
# 从原子对象列表中获取 x 和 y 的最大值和最小值
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
# 从原子对象列表中获取满足坐标条件的索引
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
# 根据原子对象列表来初始化哈密顿量
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
# --- 废弃函数/版本兼容不推荐使用并可能在未来的版本中被移除deprecated ---
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)
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)
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)
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
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
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
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
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)

View File

@@ -28,8 +28,6 @@ import guan
+ data processing
+ decorators
+ others
+ custom classes
+ functions using objects of custom classes
## About this package