Compare commits

..

9 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
12 changed files with 305 additions and 204 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

@@ -9,9 +9,9 @@ def logging_with_day_and_time(content='', filename='time_logging', file_format='
if content == '': if content == '':
f2.write(datetime_today+' '+datetime_time+'\n') f2.write(datetime_today+' '+datetime_time+'\n')
else: else:
f2.write(datetime_today+' '+datetime_time+' '+content+'\n') f2.write(datetime_today+' '+datetime_time+' '+str(content)+'\n')
# 使用该函数获取函数计算时间(秒) # 使用该函数运行某个函数并获取函数计算时间(秒)
def timer(function_name, *args, **kwargs): def timer(function_name, *args, **kwargs):
import time import time
start = time.time() start = time.time()
@@ -20,13 +20,66 @@ def timer(function_name, *args, **kwargs):
print(f"Running time of {function_name.__name__}: {end - start} seconds") print(f"Running time of {function_name.__name__}: {end - start} seconds")
return result return result
# 使用该函数实现 try except 结构 # 使用该函数运行某个函数并实现 try-except-pass 结构
def try_except(function_name, *args, **kwargs): def try_except(function_name, *args, **kwargs):
try: try:
return function_name(*args, **kwargs) return function_name(*args, **kwargs)
except: except:
pass 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): def print_array(array, line_break=0):
if line_break == 0: if line_break == 0:
@@ -101,6 +154,20 @@ def generate_random_int_number_for_a_specific_seed(seed=0, x_min=0, x_max=10):
rand_num = np.random.randint(x_min, x_max) # 左闭右开[x_min, x_max) rand_num = np.random.randint(x_min, x_max) # 左闭右开[x_min, x_max)
return rand_num 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): def get_string_between_two_patterns(original_string, start, end, include_start_and_end=0):
import re import re

View File

@@ -1,45 +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
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

@@ -1,7 +1,7 @@
# Module: file_reading_and_writing # Module: file_reading_and_writing
# 使用pickle将变量保存到文件支持几乎所有对象类型 # 使用pickle将变量保存到文件支持几乎所有对象类型
def dump_data(data, filename, file_format='.pkl'): def dump_data(data, filename='a', file_format='.pkl'):
import pickle import pickle
with open(filename+file_format, 'wb') as f: with open(filename+file_format, 'wb') as f:
pickle.dump(data, f) pickle.dump(data, f)
@@ -14,7 +14,7 @@ def load_data(filename, file_format='.pkl'):
return data return data
# 使用NumPy保存数组变量到npy文件二进制文件 # 使用NumPy保存数组变量到npy文件二进制文件
def save_npy_data(data, filename): def save_npy_data(data, filename='a'):
import numpy as np import numpy as np
np.save(filename+'.npy', data) np.save(filename+'.npy', data)
@@ -25,7 +25,7 @@ def load_npy_data(filename):
return data return data
# 使用NumPy保存数组变量到TXT文件文本文件 # 使用NumPy保存数组变量到TXT文件文本文件
def save_txt_data(data, filename): def save_txt_data(data, filename='a'):
import numpy as np import numpy as np
np.savetxt(filename+'.txt', data) np.savetxt(filename+'.txt', data)
@@ -421,13 +421,15 @@ def write_matrix_in_markdown_format(matrix, filename='a'):
dim_0 = matrix.shape[0] dim_0 = matrix.shape[0]
dim_1 = matrix.shape[1] dim_1 = matrix.shape[1]
with open(filename+'.md', 'w', encoding='UTF-8') as f: with open(filename+'.md', 'w', encoding='UTF-8') as f:
f.write(f'| Row\Column ')
for i1 in range(dim_1): for i1 in range(dim_1):
f.write(f'| column {i1+1} ') f.write(f'| column {i1+1} ')
f.write('|\n') f.write('|\n')
for i1 in range(dim_1): for i1 in range(dim_1+1):
f.write('| :---: ') f.write('| :---: ')
f.write('|\n') f.write('|\n')
for i0 in range(dim_0): for i0 in range(dim_0):
f.write(f'| row {i0+1} ')
for i1 in range(dim_1): for i1 in range(dim_1):
f.write(f'| {matrix[i0, i1]} ') f.write(f'| {matrix[i0, i1]} ')
f.write('|\n') f.write('|\n')

View File

@@ -1,79 +0,0 @@
# Module: functions_using_objects_of_custom_classes
# 将原子对象列表转成多个独立列表
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

View File

@@ -59,33 +59,6 @@ def auto_chat_with_guide(prompt='你好', guide_message='回答字数少于30
print('机器人 2: ') print('机器人 2: ')
response0 = guan.chat(prompt=response1+guide_message, model=model, stream=stream) 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秒左右 # CPU性能测试十亿次循环的浮点加法运算的时间约30秒左右
def cpu_test_with_addition(print_show=1): def cpu_test_with_addition(print_show=1):
import time import time
@@ -328,26 +301,86 @@ def get_memory_info():
used_memory_percent = memory_info.percent used_memory_percent = memory_info.percent
return total_memory, used_memory, available_memory, used_memory_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): def get_cpu_usage(interval=1):
import psutil import psutil
cpu_usage = psutil.cpu_percent(interval=interval) cpu_usage = psutil.cpu_percent(interval=interval)
return cpu_usage return cpu_usage
# 获取每个CPU核心的使用率返回列表 # 使用psutil获取每个CPU核心的使用率返回列表
def get_cpu_usage_array_per_core(interval=1): def get_cpu_usage_array_per_core(interval=1):
import psutil import psutil
cpu_usage_array_per_core = psutil.cpu_percent(interval=interval, percpu=True) cpu_usage_array_per_core = psutil.cpu_percent(interval=interval, percpu=True)
return cpu_usage_array_per_core return cpu_usage_array_per_core
# 获取使用率最高的CPU核心的使用率 # 使用psutil获取使用率最高的CPU核心的使用率
def get_cpu_max_usage_for_all_cores(interval=1): def get_cpu_max_usage_for_all_cores(interval=1):
import guan import guan
cpu_usage_array_per_core = guan.get_cpu_usage_array_per_core(interval=interval) cpu_usage_array_per_core = guan.get_cpu_usage_array_per_core(interval=interval)
max_cpu_usage = max(cpu_usage_array_per_core) max_cpu_usage = max(cpu_usage_array_per_core)
return max_cpu_usage return max_cpu_usage
# 获取非零使用率的CPU核心的平均使用率 # 使用psutil获取非零使用率的CPU核心的平均使用率
def get_cpu_averaged_usage_for_non_zero_cores(interval=1): def get_cpu_averaged_usage_for_non_zero_cores(interval=1):
import guan import guan
cpu_usage_array_per_core = guan.get_cpu_usage_array_per_core(interval=interval) 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) averaged_cpu_usage = sum(cpu_usage_array_per_core_new)/len(cpu_usage_array_per_core_new)
return averaged_cpu_usage 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): def get_cpu_information_for_times(interval=1, sleep_interval=0, times=60):
import guan import guan
import time import time
@@ -375,7 +408,7 @@ def get_cpu_information_for_times(interval=1, sleep_interval=0, times=60):
time.sleep(sleep_interval) time.sleep(sleep_interval)
return cpu_information_array 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): def write_cpu_information_to_file(filename='./cpu_usage', interval=1, sleep_interval=59, times=60):
import guan import guan
guan.make_file(filename+'.txt') 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.write('\n')
f.close() f.close()
# 画CPU的使用率图。默认为画最近的60个数据以及不画CPU核心的最大使用率。 # 使用psutil获取CPU的使用率画CPU的使用率图。默认为画最近的60个数据以及不画CPU核心的最大使用率。
def plot_cpu_information(filename='./cpu_usage', recent_num=60, max_cpu=0): def plot_cpu_information(filename='./cpu_usage', recent_num=60, max_cpu=0):
import guan import guan
from datetime import datetime 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.legend(legend_array)
plt.show() plt.show()
# 画详细的CPU的使用率图分CPU核心画图。 # 使用psutil获取CPU的使用率画详细的CPU的使用率图分CPU核心画图。
def plot_detailed_cpu_information(filename='./cpu_usage', recent_num=60): def plot_detailed_cpu_information(filename='./cpu_usage', recent_num=60):
import guan import guan
from datetime import datetime from datetime import datetime
@@ -1006,7 +1039,8 @@ def stock_symbols_classification():
for stock_symbol in stock_symbols: for stock_symbol in stock_symbols:
find_300 = re.findall(r'^300', stock_symbol) find_300 = re.findall(r'^300', stock_symbol)
find_301 = re.findall(r'^301', 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_30.append(stock_symbol)
# 科创板 # 科创板
stock_symbols_68 = [] stock_symbols_68 = []
@@ -1015,24 +1049,23 @@ def stock_symbols_classification():
find_689 = re.findall(r'^689', stock_symbol) find_689 = re.findall(r'^689', stock_symbol)
if find_688 != [] or find_689 != []: if find_688 != [] or find_689 != []:
stock_symbols_68.append(stock_symbol) stock_symbols_68.append(stock_symbol)
# 新三板 # 北交所和新三板
stock_symbols_8_4 = [] stock_symbols_8_4_9 = []
for stock_symbol in stock_symbols: for stock_symbol in stock_symbols:
find_82 = re.findall(r'^82', stock_symbol)
find_83 = re.findall(r'^83', stock_symbol) find_83 = re.findall(r'^83', stock_symbol)
find_87 = re.findall(r'^87', 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_430 = re.findall(r'^430', stock_symbol)
find_420 = re.findall(r'^420', stock_symbol) find_420 = re.findall(r'^420', stock_symbol)
find_400 = re.findall(r'^400', 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 != []: find_920 = re.findall(r'^920', stock_symbol)
stock_symbols_8_4.append(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 = [] stock_symbols_others = []
for stock_symbol in stock_symbols: 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: 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.others.append(stock_symbol) stock_symbols_others.append(stock_symbol)
return stock_symbols_60, stock_symbols_00, stock_symbols_30, stock_symbols_68, stock_symbols_8_4, stock_symbols_others 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(): def statistics_of_stock_symbols_classification():
@@ -1174,7 +1207,7 @@ def statistics_of_guan_package(function_name=None):
except: except:
pass pass
# Guan软件包升级检查和提示如果无法连接或者版本为最新,那么均没有提示) # Guan软件包升级检查和提示对于无法连接或者版本为最新的情况,检查结果都没有提示)
def notification_of_upgrade(timeout=5): def notification_of_upgrade(timeout=5):
try: try:
import guan import guan
@@ -1185,3 +1218,139 @@ def notification_of_upgrade(timeout=5):
print('升级提示:您当前使用的版本是 guan-'+current_version+',目前已经有最新版本 guan-'+latest_version+'。您可以通过以下命令对软件包进行升级pip install --upgrade guan -i https://pypi.python.org/simple 或 pip install --upgrade guan') print('升级提示:您当前使用的版本是 guan-'+current_version+',目前已经有最新版本 guan-'+latest_version+'。您可以通过以下命令对软件包进行升级pip install --upgrade guan -i https://pypi.python.org/simple 或 pip install --upgrade guan')
except: 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 + data processing
+ decorators + decorators
+ others + others
+ custom classes
+ functions using objects of custom classes
## About this package ## About this package