norfetool 1.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: norfetool
3
+ Version: 1.0.1
4
+ Summary: Easier creation of SCI figures using PIL and pkl file tools, along with a simplified approach to setting plt styles. Added a management function for slurm scripts, facilitating easy content replacement within specified base files.
5
+ Home-page: https://github.com/liftes/PythonDraw
6
+ Author: norfe
7
+ Author-email: 21121598@bjtu.edu.cn
8
+ Maintainer: norfe
9
+ Maintainer-email: 21121598@bjtu.edu.cn
10
+ License: BSD License
11
+ Platform: all
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: BSD License
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: Implementation
18
+ Classifier: Programming Language :: Python :: 2
19
+ Classifier: Programming Language :: Python :: 2.7
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.4
22
+ Classifier: Programming Language :: Python :: 3.5
23
+ Classifier: Programming Language :: Python :: 3.6
24
+ Classifier: Topic :: Software Development :: Libraries
25
+ Requires-Dist: matplotlib
26
+ Requires-Dist: numpy
27
+ Dynamic: author
28
+ Dynamic: author-email
29
+ Dynamic: classifier
30
+ Dynamic: home-page
31
+ Dynamic: license
32
+ Dynamic: maintainer
33
+ Dynamic: maintainer-email
34
+ Dynamic: platform
35
+ Dynamic: requires-dist
36
+ Dynamic: summary
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: norfetool
3
+ Version: 1.0.1
4
+ Summary: Easier creation of SCI figures using PIL and pkl file tools, along with a simplified approach to setting plt styles. Added a management function for slurm scripts, facilitating easy content replacement within specified base files.
5
+ Home-page: https://github.com/liftes/PythonDraw
6
+ Author: norfe
7
+ Author-email: 21121598@bjtu.edu.cn
8
+ Maintainer: norfe
9
+ Maintainer-email: 21121598@bjtu.edu.cn
10
+ License: BSD License
11
+ Platform: all
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: BSD License
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: Implementation
18
+ Classifier: Programming Language :: Python :: 2
19
+ Classifier: Programming Language :: Python :: 2.7
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.4
22
+ Classifier: Programming Language :: Python :: 3.5
23
+ Classifier: Programming Language :: Python :: 3.6
24
+ Classifier: Topic :: Software Development :: Libraries
25
+ Requires-Dist: matplotlib
26
+ Requires-Dist: numpy
27
+ Dynamic: author
28
+ Dynamic: author-email
29
+ Dynamic: classifier
30
+ Dynamic: home-page
31
+ Dynamic: license
32
+ Dynamic: maintainer
33
+ Dynamic: maintainer-email
34
+ Dynamic: platform
35
+ Dynamic: requires-dist
36
+ Dynamic: summary
@@ -0,0 +1,7 @@
1
+ norfetools.py
2
+ setup.py
3
+ norfetool.egg-info/PKG-INFO
4
+ norfetool.egg-info/SOURCES.txt
5
+ norfetool.egg-info/dependency_links.txt
6
+ norfetool.egg-info/requires.txt
7
+ norfetool.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ matplotlib
2
+ numpy
@@ -0,0 +1 @@
1
+ norfetool
@@ -0,0 +1,276 @@
1
+ import matplotlib.pyplot as plt
2
+ from matplotlib.gridspec import GridSpec
3
+ from PIL import Image
4
+
5
+ import os
6
+ import re
7
+ import numpy as np
8
+ import pickle
9
+
10
+ import matplotlib as mpl
11
+
12
+ from contextlib import contextmanager
13
+ import warnings
14
+
15
+ # 设置网格透明度为0.2
16
+ mpl.rcParams['grid.alpha'] = 0.2
17
+
18
+ try:
19
+ plt.style.use(["science", "grid"])
20
+ except OSError:
21
+ warnings.warn(f"Matplotlib style load failed. Using default style.", UserWarning)
22
+
23
+
24
+ # 默认的DPI设置,用于保存图像
25
+ DPI_SAVE = 800
26
+
27
+
28
+ @contextmanager
29
+ def Set_style(styles = ["science", "grid", "nature"]):
30
+ with plt.style.context(styles):
31
+ yield
32
+
33
+
34
+ def SaveFig(flag, path, filepath="figure/",):
35
+ """
36
+ 保存绘制的图像到指定路径。
37
+
38
+ 参数:
39
+ flag (bool): 决定是否保存图像。如果为True,则保存图像;如果为False,则不执行任何操作。
40
+ path (str): 图像文件的名称,包括扩展名(例如 'image.png')。
41
+ filepath (str): 图像文件的保存路径,默认为 'figure/' 目录。
42
+
43
+ 返回:
44
+
45
+
46
+ 功能:
47
+ 此函数检查是否需要保存图像(基于`flag`参数),并将其保存在指定路径。
48
+ 如果目标路径不存在,会自动创建该路径。
49
+ 使用matplotlib的savefig方法,确保边界紧凑并设置高DPI,以便图像质量更高。
50
+ """
51
+ # 保存图片
52
+ if flag:
53
+ # 如果目录不存在,则创建
54
+ if not os.path.isdir(filepath):
55
+ os.makedirs(filepath)
56
+ # 保存图像
57
+ plt.savefig(os.path.join(filepath, path), bbox_inches='tight', dpi=DPI_SAVE)
58
+ plt.close()
59
+ else:
60
+ # 如果不保存图片,则显示图片
61
+ plt.show()
62
+ pass
63
+
64
+
65
+ def TestColorList(clist):
66
+ """
67
+ 显示色卡和颜色在不同图形中的应用示例。
68
+
69
+ 参数:
70
+ clist (list): 色卡列表,包含颜色定义。
71
+ """
72
+ num = len(clist)
73
+ gs = GridSpec(3, num + int(num / 2), figure=plt.figure(figsize=(6, 4)))
74
+ plt.subplots_adjust(wspace=0.3, hspace=0.2)
75
+
76
+ # 显示色卡
77
+ for i, color in enumerate(clist):
78
+ if type(color) != str:
79
+ color = tuple([int(i * 255) for i in color])
80
+ img = Image.new('RGB', (10, 10), color)
81
+ ax = plt.subplot(gs[0, i])
82
+ ax.set_xticks([])
83
+ ax.set_yticks([])
84
+ ax.axis("off")
85
+ ax.imshow(img)
86
+
87
+ # 正弦波形
88
+ ax = plt.subplot(gs[1:, :num])
89
+ xvalue = np.arange(0, 2 * np.pi, 0.1)
90
+ for i, color in enumerate(clist):
91
+ ax.plot(xvalue, np.sin((i + 0.5) * xvalue), "-", color=color, label="%d" % i)
92
+ ax.grid(":", alpha=0.3)
93
+ ax.set_xticklabels([])
94
+ ax.set_yticklabels([])
95
+ ax.legend(loc=4)
96
+
97
+ # 指数波形
98
+ ax = plt.subplot(gs[:, num:])
99
+ xvalue = np.arange(0, 0.5, 0.05)
100
+ for i, color in enumerate(clist):
101
+ ax.plot(xvalue, np.exp((i + 0.5) * xvalue), "s", color=color, markerfacecolor='none', label="%d" % i)
102
+ ax.set_xticks([])
103
+ ax.set_yticks([])
104
+ ax.legend(loc=2)
105
+ plt.show()
106
+ plt.close()
107
+
108
+
109
+ def SetColor(string, num_colors, extract_first_colors=False, ifshow=False):
110
+ """
111
+ 根据给定的colormap名称生成颜色列表并显示。可以选择生成均匀分布的颜色列表
112
+ 或者提取colormap的前几个颜色。
113
+
114
+ 参数:
115
+ string (str): colormap的名称。
116
+ num_colors (int): 要生成或提取的颜色数量。
117
+ extract_first_colors (bool): 如果为True,则仅提取colormap的前num_colors个颜色。
118
+ 如果为False,则根据num_colors在colormap中均匀分布生成颜色列表。
119
+
120
+ 返回:
121
+ list: 生成的颜色列表。
122
+ """
123
+ if extract_first_colors:
124
+ # 仅提取colormap的前num_colors个颜色
125
+ color_list = [plt.cm.get_cmap(string)(i) for i in range(num_colors)]
126
+ else:
127
+ # 生成均匀分布的颜色列表
128
+ array = np.linspace(0, 1, num_colors)
129
+ color_list = plt.cm.get_cmap(string)(array)
130
+
131
+ if ifshow:
132
+ TestColorList(color_list)
133
+ return color_list
134
+
135
+
136
+ def Set_axis_formatting(axis, nbins, decimals):
137
+ from matplotlib.ticker import MaxNLocator, FormatStrFormatter
138
+ """
139
+ 设置图表的轴格式。
140
+
141
+ 参数:
142
+ axis (str): 指定要设置的轴。'x' 设置x轴,'y' 设置y轴,'both' 设置两者。
143
+ nbins (int): 轴的主要刻度的数量。
144
+ decimals (int): 轴刻度标签的小数位数。
145
+ """
146
+ formatter = FormatStrFormatter(f'%.{decimals}f')
147
+
148
+ if axis == 'x' or axis == 'both':
149
+ plt.gca().xaxis.set_major_locator(MaxNLocator(nbins=nbins))
150
+ plt.gca().xaxis.set_major_formatter(formatter)
151
+
152
+ if axis == 'y' or axis == 'both':
153
+ plt.gca().yaxis.set_major_locator(MaxNLocator(nbins=nbins))
154
+ plt.gca().yaxis.set_major_formatter(formatter)
155
+
156
+
157
+ def Set_colorbar_ticks_outward(cbar,
158
+ major_len=None, minor_len=None,
159
+ major_width=None, minor_width=None):
160
+ """
161
+ 设置 colorbar 主/子刻度线朝外,支持默认或自定义长度和粗细。
162
+
163
+ 参数:
164
+ cbar : matplotlib.colorbar.Colorbar
165
+ major_len, minor_len : int or None
166
+ 刻度线长度;若为 None,则使用默认值。
167
+ major_width, minor_width : float or None
168
+ 刻度线宽度;若为 None,则使用默认值。
169
+ """
170
+ # 获取默认参数
171
+ default_major_len = mpl.rcParams['xtick.major.size']
172
+ default_minor_len = mpl.rcParams['xtick.minor.size']
173
+ default_major_width = mpl.rcParams['xtick.major.width']
174
+ default_minor_width = mpl.rcParams['xtick.minor.width']
175
+
176
+ # 使用默认值或用户值
177
+ major_len = major_len if major_len is not None else default_major_len
178
+ minor_len = minor_len if minor_len is not None else default_minor_len
179
+ major_width = major_width if major_width is not None else default_major_width
180
+ minor_width = minor_width if minor_width is not None else default_minor_width
181
+
182
+ # 应用设置
183
+ cbar.ax.tick_params(which='major', direction='out', length=major_len, width=major_width)
184
+ cbar.ax.minorticks_on()
185
+ cbar.ax.tick_params(which='minor', direction='out', length=minor_len, width=minor_width)
186
+
187
+
188
+
189
+ #############################################
190
+ ##################文件处理####################
191
+ #############################################
192
+
193
+
194
+ def Ensure_directory_exists(filename):
195
+ """
196
+ 检查文件的目录是否存在,如果不存在,则创建。
197
+ :param filename: 要检查的文件名或路径。
198
+ """
199
+ directory = os.path.dirname(filename)
200
+
201
+ # 如果目录名不为空且目录不存在,则创建
202
+ if directory and not os.path.exists(directory):
203
+ os.makedirs(directory)
204
+
205
+
206
+ def Save_data(temp_data_list, filename='temp_data_list.pkl'):
207
+ """
208
+ 保存 temp_data_list 到一个文件中。
209
+ :param temp_data_list: 要保存的数据列表。
210
+ :param filename: 保存数据的文件名,默认为 'temp_data_list.pkl'。
211
+ """
212
+ Ensure_directory_exists(filename)
213
+ with open(filename, 'wb') as file:
214
+ pickle.dump(temp_data_list, file)
215
+
216
+
217
+ def Load_data(filename='temp_data_list.pkl'):
218
+ """
219
+ 从文件中加载 temp_data_list。
220
+ :param filename: 包含数据的文件名,默认为 'temp_data_list.pkl'。
221
+ :return: 返回加载的数据列表。
222
+ """
223
+ with open(filename, 'rb') as file:
224
+ return pickle.load(file)
225
+
226
+
227
+ #############################################
228
+ #################字符串处理###################
229
+ #############################################
230
+ # 主要用于slurm的脚本批量提交
231
+
232
+
233
+ def Ensure_directory_exists(file_path):
234
+ """
235
+ 检查文件路径的目录是否存在,如果不存在则创建。
236
+
237
+ 参数:
238
+ - file_path: 文件的完整路径。
239
+ """
240
+ directory = os.path.dirname(file_path)
241
+
242
+ # 检查文件是否存在,存在则删除
243
+ if os.path.exists(file_path):
244
+ os.remove(file_path)
245
+
246
+ if not os.path.exists(directory):
247
+ os.makedirs(directory, exist_ok=True)
248
+
249
+
250
+ def Replace_strings_in_file(file_name, replace_dict, new_file_path):
251
+ """
252
+ 将文件中的多个旧字符串替换为对应的新字符串,并保存到新路径。
253
+
254
+ 参数:
255
+ - file_name: 原始文件路径。
256
+ - replace_dict: 一个字典,键为旧字符串,值为新字符串。
257
+ - new_file_path: 新文件保存路径,如果路径不存在会创建。
258
+ """
259
+ # 确保新文件路径存在,如果不存在则创建
260
+ Ensure_directory_exists(new_file_path)
261
+
262
+ # 读取文件内容
263
+ with open(file_name, 'r') as file:
264
+ file_contents = file.read()
265
+
266
+ # 遍历字典并替换所有旧字符串
267
+ new_contents = file_contents
268
+ for old_string, new_string in replace_dict.items():
269
+ new_contents = re.sub(re.escape(old_string), new_string, new_contents)
270
+
271
+ # 将修改后的内容写入新的文件路径
272
+ with open(new_file_path, 'w') as new_file:
273
+ new_file.write(new_contents)
274
+
275
+ print(f"File has been saved to {new_file_path} with the updated content.")
276
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+
4
+ from setuptools import setup, find_packages
5
+
6
+ setup(
7
+ name='norfetool',
8
+ version="1.0.1",
9
+ description=(
10
+ 'Easier creation of SCI figures using PIL and pkl file tools, along with a simplified approach to setting plt styles. Added a management function for slurm scripts, facilitating easy content replacement within specified base files.'
11
+ ),
12
+ # long_description=open('README.rst').read(),
13
+ author='norfe',
14
+ author_email='21121598@bjtu.edu.cn',
15
+ maintainer='norfe',
16
+ maintainer_email='21121598@bjtu.edu.cn',
17
+ license='BSD License',
18
+ # packages=find_packages(),
19
+ py_modules=["norfetool"],
20
+ platforms=["all"],
21
+ url='https://github.com/liftes/PythonDraw',
22
+ classifiers=[
23
+ 'Development Status :: 4 - Beta',
24
+ 'Operating System :: OS Independent',
25
+ 'Intended Audience :: Developers',
26
+ 'License :: OSI Approved :: BSD License',
27
+ 'Programming Language :: Python',
28
+ 'Programming Language :: Python :: Implementation',
29
+ 'Programming Language :: Python :: 2',
30
+ 'Programming Language :: Python :: 2.7',
31
+ 'Programming Language :: Python :: 3',
32
+ 'Programming Language :: Python :: 3.4',
33
+ 'Programming Language :: Python :: 3.5',
34
+ 'Programming Language :: Python :: 3.6',
35
+ 'Topic :: Software Development :: Libraries'
36
+ ],
37
+ install_requires=[
38
+ 'matplotlib',
39
+ 'numpy',
40
+ ]
41
+ )