shancx 1.8.92__py3-none-any.whl → 1.9.33.218__py3-none-any.whl

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.
Files changed (166) hide show
  1. shancx/3D/__init__.py +25 -0
  2. shancx/Algo/Class.py +11 -0
  3. shancx/Algo/CudaPrefetcher1.py +112 -0
  4. shancx/Algo/Fake_image.py +24 -0
  5. shancx/Algo/Hsml.py +391 -0
  6. shancx/Algo/L2Loss.py +10 -0
  7. shancx/Algo/MetricTracker.py +132 -0
  8. shancx/Algo/Normalize.py +66 -0
  9. shancx/Algo/OptimizerWScheduler.py +38 -0
  10. shancx/Algo/Rmageresize.py +79 -0
  11. shancx/Algo/Savemodel.py +33 -0
  12. shancx/Algo/SmoothL1_losses.py +27 -0
  13. shancx/Algo/Tqdm.py +62 -0
  14. shancx/Algo/__init__.py +121 -0
  15. shancx/Algo/checknan.py +28 -0
  16. shancx/Algo/iouJU.py +83 -0
  17. shancx/Algo/mask.py +25 -0
  18. shancx/Algo/psnr.py +9 -0
  19. shancx/Algo/ssim.py +70 -0
  20. shancx/Algo/structural_similarity.py +308 -0
  21. shancx/Algo/tool.py +704 -0
  22. shancx/Calmetrics/__init__.py +97 -0
  23. shancx/Calmetrics/calmetrics.py +14 -0
  24. shancx/Calmetrics/calmetricsmatrixLib.py +147 -0
  25. shancx/Calmetrics/rmseR2score.py +35 -0
  26. shancx/Clip/__init__.py +50 -0
  27. shancx/Cmd.py +126 -0
  28. shancx/Config_.py +26 -0
  29. shancx/Df/DataFrame.py +11 -2
  30. shancx/Df/__init__.py +17 -0
  31. shancx/Df/tool.py +0 -0
  32. shancx/Diffm/Psamples.py +18 -0
  33. shancx/Diffm/__init__.py +0 -0
  34. shancx/Diffm/test.py +207 -0
  35. shancx/Doc/__init__.py +214 -0
  36. shancx/E/__init__.py +178 -152
  37. shancx/Fillmiss/__init__.py +0 -0
  38. shancx/Fillmiss/imgidwJU.py +46 -0
  39. shancx/Fillmiss/imgidwLatLonJU.py +82 -0
  40. shancx/Gpu/__init__.py +55 -0
  41. shancx/H9/__init__.py +126 -0
  42. shancx/H9/ahi_read_hsd.py +877 -0
  43. shancx/H9/ahisearchtable.py +298 -0
  44. shancx/H9/geometry.py +2439 -0
  45. shancx/Hug/__init__.py +81 -0
  46. shancx/Inst.py +22 -0
  47. shancx/Lib.py +31 -0
  48. shancx/Mos/__init__.py +37 -0
  49. shancx/NN/__init__.py +235 -106
  50. shancx/Path1.py +161 -0
  51. shancx/Plot/GlobMap.py +276 -116
  52. shancx/Plot/__init__.py +491 -1
  53. shancx/Plot/draw_day_CR_PNG.py +4 -21
  54. shancx/Plot/exam.py +116 -0
  55. shancx/Plot/plotGlobal.py +325 -0
  56. shancx/{radar_nmc.py → Plot/radarNmc.py} +4 -34
  57. shancx/{subplots_single_china_map.py → Plot/single_china_map.py} +1 -1
  58. shancx/Point.py +46 -0
  59. shancx/QC.py +223 -0
  60. shancx/RdPzl/__init__.py +32 -0
  61. shancx/Read.py +72 -0
  62. shancx/Resize.py +79 -0
  63. shancx/SN/__init__.py +62 -123
  64. shancx/Time/GetTime.py +9 -3
  65. shancx/Time/__init__.py +66 -1
  66. shancx/Time/timeCycle.py +302 -0
  67. shancx/Time/tool.py +0 -0
  68. shancx/Train/__init__.py +74 -0
  69. shancx/Train/makelist.py +187 -0
  70. shancx/Train/multiGpu.py +27 -0
  71. shancx/Train/prepare.py +161 -0
  72. shancx/Train/renet50.py +157 -0
  73. shancx/ZR.py +12 -0
  74. shancx/__init__.py +333 -262
  75. shancx/args.py +27 -0
  76. shancx/bak.py +768 -0
  77. shancx/df2database.py +62 -2
  78. shancx/geosProj.py +80 -0
  79. shancx/info.py +38 -0
  80. shancx/netdfJU.py +231 -0
  81. shancx/sendM.py +59 -0
  82. shancx/tensBoard/__init__.py +28 -0
  83. shancx/wait.py +246 -0
  84. {shancx-1.8.92.dist-info → shancx-1.9.33.218.dist-info}/METADATA +15 -5
  85. shancx-1.9.33.218.dist-info/RECORD +91 -0
  86. {shancx-1.8.92.dist-info → shancx-1.9.33.218.dist-info}/WHEEL +1 -1
  87. my_timer_decorator/__init__.py +0 -10
  88. shancx/Dsalgor/__init__.py +0 -19
  89. shancx/E/DFGRRIB.py +0 -30
  90. shancx/EN/DFGRRIB.py +0 -30
  91. shancx/EN/__init__.py +0 -148
  92. shancx/FileRead.py +0 -44
  93. shancx/Gray2RGB.py +0 -86
  94. shancx/M/__init__.py +0 -137
  95. shancx/MN/__init__.py +0 -133
  96. shancx/N/__init__.py +0 -131
  97. shancx/Plot/draw_day_CR_PNGUS.py +0 -206
  98. shancx/Plot/draw_day_CR_SVG.py +0 -275
  99. shancx/Plot/draw_day_pre_PNGUS.py +0 -205
  100. shancx/Plot/glob_nation_map.py +0 -116
  101. shancx/Plot/radar_nmc.py +0 -61
  102. shancx/Plot/radar_nmc_china_map_compare1.py +0 -50
  103. shancx/Plot/radar_nmc_china_map_f.py +0 -121
  104. shancx/Plot/radar_nmc_us_map_f.py +0 -128
  105. shancx/Plot/subplots_compare_devlop.py +0 -36
  106. shancx/Plot/subplots_single_china_map.py +0 -45
  107. shancx/S/__init__.py +0 -138
  108. shancx/W/__init__.py +0 -132
  109. shancx/WN/__init__.py +0 -132
  110. shancx/code.py +0 -331
  111. shancx/draw_day_CR_PNG.py +0 -200
  112. shancx/draw_day_CR_PNGUS.py +0 -206
  113. shancx/draw_day_CR_SVG.py +0 -275
  114. shancx/draw_day_pre_PNGUS.py +0 -205
  115. shancx/makenetCDFN.py +0 -42
  116. shancx/mkIMGSCX.py +0 -92
  117. shancx/netCDF.py +0 -130
  118. shancx/radar_nmc_china_map_compare1.py +0 -50
  119. shancx/radar_nmc_china_map_f.py +0 -125
  120. shancx/radar_nmc_us_map_f.py +0 -67
  121. shancx/subplots_compare_devlop.py +0 -36
  122. shancx/tool.py +0 -18
  123. shancx/user/H8mess.py +0 -317
  124. shancx/user/__init__.py +0 -137
  125. shancx/user/cinradHJN.py +0 -496
  126. shancx/user/examMeso.py +0 -293
  127. shancx/user/hjnDAAS.py +0 -26
  128. shancx/user/hjnFTP.py +0 -81
  129. shancx/user/hjnGIS.py +0 -320
  130. shancx/user/hjnGPU.py +0 -21
  131. shancx/user/hjnIDW.py +0 -68
  132. shancx/user/hjnKDTree.py +0 -75
  133. shancx/user/hjnLAPSTransform.py +0 -47
  134. shancx/user/hjnMiscellaneous.py +0 -182
  135. shancx/user/hjnProj.py +0 -162
  136. shancx/user/inotify.py +0 -41
  137. shancx/user/matplotlibMess.py +0 -87
  138. shancx/user/mkNCHJN.py +0 -623
  139. shancx/user/newTypeRadar.py +0 -492
  140. shancx/user/test.py +0 -6
  141. shancx/user/tlogP.py +0 -129
  142. shancx/util_log.py +0 -33
  143. shancx/wtx/H8mess.py +0 -315
  144. shancx/wtx/__init__.py +0 -151
  145. shancx/wtx/cinradHJN.py +0 -496
  146. shancx/wtx/colormap.py +0 -64
  147. shancx/wtx/examMeso.py +0 -298
  148. shancx/wtx/hjnDAAS.py +0 -26
  149. shancx/wtx/hjnFTP.py +0 -81
  150. shancx/wtx/hjnGIS.py +0 -330
  151. shancx/wtx/hjnGPU.py +0 -21
  152. shancx/wtx/hjnIDW.py +0 -68
  153. shancx/wtx/hjnKDTree.py +0 -75
  154. shancx/wtx/hjnLAPSTransform.py +0 -47
  155. shancx/wtx/hjnLog.py +0 -78
  156. shancx/wtx/hjnMiscellaneous.py +0 -201
  157. shancx/wtx/hjnProj.py +0 -161
  158. shancx/wtx/inotify.py +0 -41
  159. shancx/wtx/matplotlibMess.py +0 -87
  160. shancx/wtx/mkNCHJN.py +0 -613
  161. shancx/wtx/newTypeRadar.py +0 -492
  162. shancx/wtx/test.py +0 -6
  163. shancx/wtx/tlogP.py +0 -129
  164. shancx-1.8.92.dist-info/RECORD +0 -99
  165. /shancx/{Dsalgor → Algo}/dsalgor.py +0 -0
  166. {shancx-1.8.92.dist-info → shancx-1.9.33.218.dist-info}/top_level.txt +0 -0
shancx/Hug/__init__.py ADDED
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # gdown --folder https://drive.google.com/drive/folders/1D3bf2G2o4Hv-Ale26YW18r1Wrh7oIAwK 文件夹下所有内容太
4
+ from modelscope.hub.snapshot_download import snapshot_download
5
+ model_dir = snapshot_download('', cache_dir='autodl-tmp', revision='master', ignore_file_pattern='.bn')
6
+ from datasets import load_dataset
7
+ dataset = load_dataset("ayz2/ldm_pdes", download_mode="force_redownload")
8
+ print(dataset)
9
+ # dataset.save_to_disk('/path/to/save/dataset')
10
+ for split_name, split_dataset in dataset.items():
11
+ chunk_size = 5000 # 每片的样本数量,可根据内存大小调整
12
+ for i in range(0, len(split_dataset), chunk_size):
13
+ subset = split_dataset.select(range(i, min(i + chunk_size, len(split_dataset))))
14
+ subset.save_to_disk(f"./{split_name}_chunk_{i // chunk_size}")
15
+
16
+ from huggingface_hub import hf_hub_download
17
+ from shancx import crDir
18
+ # 下载权重文件
19
+ repo_id = "ayz2/ldm_pdes"
20
+ filename = "ae_cylinder.ckpt"
21
+ crDir("/mnt/wtx_weather_forecast/scx/ldm_pdes_checkpoint")
22
+ save_dir = "/mnt/wtx_weather_forecast/scx/ldm_pdes_checkpoint"
23
+ save_path = hf_hub_download(repo_id=repo_id, filename=filename, cache_dir=save_dir)
24
+
25
+
26
+ print(f"权重文件已下载到: {save_path}")
27
+
28
+
29
+ from modelscope.hub.snapshot_download import snapshot_download
30
+ crDir("/mnt/wtx_weather_forecast/scx/ldm_pdes_checkpoint")
31
+ save_dir = "/mnt/wtx_weather_forecast/scx/ldm_pdes_checkpoint"
32
+ model_dir = snapshot_download('ayz2/ldm_pdes', cache_dir=save_dir, revision='master', ignore_file_pattern='.bn') 下载 ae_cylinder.ckpt"
33
+
34
+
35
+ from modelscope.hub.snapshot_download import snapshot_download
36
+ from shancx import crDir
37
+ save_dir = "/mnt/wtx_weather_forecast/scx/ldm_pdes_checkpoint"
38
+ crDir(save_dir)
39
+ model_dir = snapshot_download(
40
+ 'ayz2/ldm_pdes',
41
+ cache_dir=save_dir,
42
+ revision='master',
43
+ ignore_file_pattern='.bn')
44
+ print(f"模型已下载到: {model_dir}")
45
+
46
+
47
+
48
+
49
+
50
+ from google.colab import drive
51
+ import requests
52
+ import os
53
+
54
+ # 挂载 Google Drive
55
+ drive.mount('/content/drive')
56
+ ptname = "ae_cylinder.ckpt"
57
+ # 文件下载的URL
58
+ file_url = f"https://huggingface.co/datasets/ayz2/ldm_pdes/resolve/main/{ptname}"
59
+
60
+ # Google Drive中的保存路径(修改为你想保存的位置)
61
+ output_path = "/content/drive/My Drive/{ptname}"
62
+
63
+ # 下载文件并保存到指定路径
64
+ def download_file(url, output_path):
65
+ try:
66
+ with requests.get(url, stream=True) as response:
67
+ response.raise_for_status()
68
+ with open(output_path, "wb") as file:
69
+ for chunk in response.iter_content(chunk_size=8192):
70
+ if chunk: # 防止空块
71
+ file.write(chunk)
72
+ print(f"文件已成功下载并保存到 Google Drive: {output_path}")
73
+ except Exception as e:
74
+ print(f"下载文件时出错: {e}")
75
+ download_file(file_url, output_path)
76
+
77
+ import zipfile
78
+ def unzip_file(zip_path, extract_to):
79
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
80
+ zip_ref.extractall(extract_to)
81
+ unzip_file(output_path, os.getcwd())
shancx/Inst.py ADDED
@@ -0,0 +1,22 @@
1
+ import sys
2
+ import os
3
+ def current_dir_sys_path():
4
+ sys.path.append(os.getcwd()) #current_dir_sys_path()
5
+
6
+ import importlib
7
+ def instantiate_config(config):
8
+ if not "target" in config:
9
+ if config == '__is_first_stage__':
10
+ return None
11
+ elif config == "__is_unconditional__":
12
+ return None
13
+ raise KeyError("Expected key `target` to instantiate.")
14
+ return get_obj_from_str(config["target"])(**config.get("params", dict()))
15
+ def get_obj_from_str(string, reload=False):
16
+ module, cls = string.rsplit(".", 1)
17
+ if reload:
18
+ module_imp = importlib.import_module(module)
19
+ importlib.reload(module_imp)
20
+ return getattr(importlib.import_module(module, package=None), cls)
21
+
22
+
shancx/Lib.py ADDED
@@ -0,0 +1,31 @@
1
+ import cv2
2
+ import copy
3
+ import numpy as np
4
+
5
+ def QC(mat, dbzTH=10, areaTH=20): # 主QC函数
6
+ mat1 = copy.copy(mat)
7
+ varMask = np.where(mat1 > dbzTH, 1, 0)
8
+ varMask = varMask.astype(np.uint8)
9
+
10
+ ret, img_thre = cv2.threshold(varMask, 0, 255, cv2.THRESH_BINARY)
11
+ num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(img_thre, connectivity=8)
12
+ mask = np.zeros(varMask.shape, dtype=np.uint8)
13
+
14
+ for j in range(1, num_labels):
15
+ if stats[j, cv2.CC_STAT_AREA] >= areaTH:
16
+ mask[labels == j] = 255
17
+ mat1[mask != 255] = 0
18
+ return mat1
19
+
20
+ def QC_batch(mat, dbzTH=10, areaTH=20, phase="QC"): # 批量QC函数
21
+ from shancx.NN import _loggers
22
+ logger = _loggers(phase=phase)
23
+ for i in range(len(mat)):
24
+ logger.info(f"QC {i}")
25
+ mat[i] = QC(mat[i], dbzTH, areaTH)
26
+ return mat
27
+
28
+ """
29
+ pre = QC_simple(pre,areaTH=30) 二维灰度
30
+ pre = QC_ref(pre,areaTH=30) 三维灰度
31
+ """
shancx/Mos/__init__.py ADDED
@@ -0,0 +1,37 @@
1
+
2
+
3
+
4
+ import numpy as np
5
+ def start_points(size, split_size, overlap=0.0):
6
+ stride = int(split_size * (1 - overlap)) # 计算步长
7
+ points = [i * stride for i in range((size - split_size) // stride + 1)]
8
+ if size > points[-1] + split_size:
9
+ points.append(size - split_size)
10
+ return points
11
+
12
+ def weigthOverlap(overlap,radarpre,x,y,b,weight_sum):
13
+ weight = np.ones((256, 256))
14
+ for i in range(overlap):
15
+ weight[:, i] = 0.5 * (1 - np.cos(np.pi * i / overlap))
16
+ weight[:, -i-1] = 0.5 * (1 - np.cos(np.pi * i / overlap))
17
+ weight[i, :] = np.minimum(weight[i, :], 0.5 * (1 - np.cos(np.pi * i / overlap)))
18
+ weight[-i-1, :] = np.minimum(weight[-i-1, :], 0.5 * (1 - np.cos(np.pi * i / overlap)))
19
+ patch = radarpre * weight
20
+ b[x:x+256, y:y+256] = np.where(np.isnan(b[x:x+256, y:y+256]),
21
+ patch,
22
+ b[x:x+256, y:y+256] + patch)
23
+ weight_sum[x:x+256, y:y+256] = np.where(np.isnan(weight_sum[x:x+256, y:y+256]),
24
+ weight,
25
+ weight_sum[x:x+256, y:y+256] + weight)
26
+ return b,weight_sum
27
+
28
+ """
29
+ weight_sum = np.zeros_like(b)
30
+ b,weight_sum = weigthOverlap(overlap,radarpre,x,y,b,weight_sum)
31
+ b = np.divide(b, weight_sum, where=weight_sum!=0)
32
+
33
+ weight_sum = np.zeros_like(b)
34
+ overlap = 32
35
+ x_point = start_points(sat_data[0].shape[0], 256, overlap/256)
36
+ y_point = start_points(sat_data[0].shape[1], 256, overlap/256)
37
+ """
shancx/NN/__init__.py CHANGED
@@ -4,124 +4,253 @@ import os
4
4
  def start():
5
5
  print("import successful")
6
6
  # constants
7
- __author__ = 'shancx'
8
-
9
- __author_email__ = 'shancx@126.com'
10
-
11
- # @Time : 2023/09/27 下午8:52
12
- # @Author : shanchangxi
13
- # @File : util_log.py
14
- import time
15
- import logging
16
- from logging import handlers
17
-
18
- def mkDir(path):
19
- if "." in path:
20
- os.makedirs(os.path.dirname(path),exist_ok=True)
21
- else:
22
- os.makedirs(path, exist_ok=True)
23
-
24
- loggers = logging.getLogger()
25
- loggers.setLevel(logging.INFO)
26
- log_name = './project_N.log'
27
- mkDir(log_name)
28
- logfile = log_name
29
- time_rotating_file_handler = handlers.TimedRotatingFileHandler(filename=logfile, when='D', encoding='utf-8')
30
- time_rotating_file_handler.setLevel(logging.INFO)
31
- formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
32
- time_rotating_file_handler.setFormatter(formatter)
33
- loggers.addHandler(time_rotating_file_handler)
34
-
35
-
36
- """
37
- import tracback
38
- try:
7
+ __author__ = 'shancx'
8
+ __author_email__ = 'shanhe12@163.com'
9
+ __time__ = '20251028 21:16'
10
+ import logging
11
+ from logging.handlers import RotatingFileHandler
12
+ import os
13
+ from shancx import crDir
14
+ def _loggers(logger_name="loggers", root="./logs", phase="project", level=logging.INFO, screen=True, max_bytes=10*1024*1024, backup_count=5, overwrite=False,handlersflag=False):
15
+ '''set up logger with rotating file handler'''
16
+ l = logging.getLogger(logger_name)
17
+ if handlersflag:
18
+ if l.handlers:
19
+ return l
20
+ formatter = logging.Formatter(
21
+ "%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s", datefmt='%Y-%m-%d %H:%M:%S')
22
+ log_file = os.path.join(root, '{}.log'.format(phase))
23
+ crDir(log_file)
24
+ # Use RotatingFileHandler with 'w' mode to overwrite log file if needed
25
+ mode = 'w' if overwrite else 'a'
26
+ fh = RotatingFileHandler(log_file, mode=mode, maxBytes=max_bytes, backupCount=backup_count)
27
+ fh.setFormatter(formatter)
28
+ l.setLevel(level)
29
+ l.addHandler(fh)
30
+ if screen:
31
+ sh = logging.StreamHandler()
32
+ sh.setFormatter(formatter)
33
+ l.addHandler(sh)
34
+ return l
39
35
 
40
- except Exception as e:
41
-
42
- logger.info(traceback.format_exc())
36
+ """
37
+ logger = _loggers(logger_name="test_logger", root=curpathplus, phase="test_log", overwrite=True, screen=True)
38
+ # 测试日志输出
39
+ for i in range(5):
40
+ logger.info(f"这是日志消息 {i+1}")
41
+ time.sleep(1)
43
42
  """
44
43
 
45
44
 
46
- """
47
- from main import makeAll,options
48
- from multiprocessing import Pool
49
- import datetime
50
- from config import logger,output
51
- import time
52
- import pandas as pd
45
+ import logging
46
+ from logging.handlers import RotatingFileHandler
53
47
  import os
54
- from itertools import product
55
- import threading
56
-
57
- def excuteCommand(cmd):
58
- print(cmd)
59
- os.system(cmd)
48
+ from shancx import crDir
49
+ import multiprocessing
50
+ def _loggersPlus(logger_name="loggers", root="./logs", phase="project", level=logging.INFO,
51
+ screen=True, max_bytes=10 * 1024 * 1024, backup_count=5, overwrite=False,
52
+ handlersflag=False, enable_rotating=None):
53
+ l = logging.getLogger(logger_name)
54
+ if handlersflag:
55
+ if l.handlers:
56
+ return l
57
+ formatter = logging.Formatter(
58
+ "%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s",
59
+ datefmt='%Y-%m-%d %H:%M:%S'
60
+ )
61
+ log_file = os.path.join(root, '{}.log'.format(phase))
62
+ crDir(log_file)
63
+ mode = 'w' if overwrite else 'a'
64
+ if enable_rotating is None:
65
+ enable_rotating = (multiprocessing.current_process().name == 'MainProcess')
66
+
67
+ if enable_rotating:
68
+ fh = RotatingFileHandler(
69
+ log_file,
70
+ mode=mode,
71
+ maxBytes=max_bytes,
72
+ backupCount=backup_count
73
+ )
74
+ else:
75
+ fh = logging.FileHandler(log_file, mode=mode)
76
+
77
+ fh.setFormatter(formatter)
78
+ l.setLevel(level)
79
+ l.addHandler(fh)
80
+
81
+ if screen:
82
+ sh = logging.StreamHandler()
83
+ sh.setFormatter(formatter)
84
+ l.addHandler(sh)
85
+ return l
60
86
 
61
- def gpuPro(makeListUTC, isPhase, isDebug, gpu, isOverwrite):
62
- productList = product(makeListUTC, [isPhase], [isDebug], [gpu], [isOverwrite])
63
87
 
64
- with Pool(4) as p:
65
- p.map(makeAll, productList)
88
+ import logging
89
+ def setlogger(level=logging.INFO):
90
+
91
+ logging.basicConfig(
92
+ level=level, # 动态接受级别参数
93
+ format="%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s",
94
+ handlers=[logging.StreamHandler()],
95
+ force=True # 强制覆盖现有配置(Python 3.8+)
96
+ )
97
+ return logging.getLogger()
98
+ '''
99
+ # 使用示例
100
+ if __name__ == "__main__":
101
+ logger = setlogger(level=logging.DEBUG) # 设置为DEBUG级别
102
+ logger.debug("这条日志会显示") # 默认情况下DEBUG不显示,但因为我们设置了级别,现在会显示
103
+ logger.info("这是一条INFO日志")
104
+ '''
105
+ import os
106
+ import glob
107
+ import logging
108
+ from datetime import datetime
109
+ from shancx import loggers as logger
110
+ def cleanupLogs(log_dir='/mnt/wtx_weather_forecast/scx/SATH9SEAStest/logs', keep_count=10,
111
+ pattern='*.log', recursive=False, dry_run=False):
112
+ stats = {'total_dirs': 0, 'deleted_files': 0, 'errors': []}
113
+ def _cleanup_dir(directory):
114
+ stats['total_dirs'] += 1
115
+ if not os.path.exists(directory):
116
+ logging.warning(f"目录不存在: {directory}")
117
+ return
118
+ file_paths = glob.glob(os.path.join(directory, pattern))
119
+ log_files = [(path, os.path.getmtime(path)) for path in file_paths]
120
+ log_files.sort(key=lambda x: x[1], reverse=True)
121
+ if len(log_files) <= keep_count:
122
+ logging.info(f"目录 {directory} 中的文件数量 ({len(log_files)}) 不超过保留数量 ({keep_count}),无需清理")
123
+ return
124
+ files_to_delete = log_files[keep_count:]
125
+ for file_path, mtime in files_to_delete:
126
+ try:
127
+ if dry_run:
128
+ logging.info(f"[试运行] 将删除: {file_path} (修改时间: {datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S')})")
129
+ else:
130
+ os.remove(file_path)
131
+ logging.info(f"已删除: {file_path} (修改时间: {datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S')})")
132
+ stats['deleted_files'] += 1
133
+ except Exception as e:
134
+ error_msg = f"删除失败 {file_path}: {str(e)}"
135
+ logging.error(error_msg)
136
+ stats['errors'].append(error_msg)
137
+ if recursive:
138
+ for root, _, _ in os.walk(log_dir):
139
+ _cleanup_dir(root)
140
+ else:
141
+ _cleanup_dir(log_dir)
142
+ return stats
143
+ """
144
+ if __name__ == "__main__":
145
+ dir = "/mnt/wtx_weather_forecast/scx/SATH9SEAStest/logs/H9SEAS/"
146
+ stats = cleanupLogs(dir,3, '*.log', False, False)
147
+ logging.info(f"清理完成: 处理目录数={stats['total_dirs']}, 删除文件数={stats['deleted_files']}, 错误数={len(stats['errors'])}")
148
+ if stats['errors']:
149
+ logging.error(f"错误详情: {stats['errors']}")
150
+ """
66
151
 
67
- if __name__ == '__main__':
68
- cfg = options()
69
- isPhase = cfg.isPhase
70
- isDebug = cfg.isDebug
71
- sepSec = cfg.sepSec
72
- gpu = cfg.gpu
73
- pool = cfg.pool
74
- isOverwrite = cfg.isOverwrite
75
- timeList = pd.date_range(cfg.times[0], cfg.times[-1], freq=f"{sepSec}s")
76
- logger.info(f"时间段check {timeList}")
77
- gpuNum = 2
78
- eachGPU = 4
152
+ from itertools import product
153
+ from concurrent.futures import ProcessPoolExecutor as PoolExecutor, as_completed
154
+ import sys
155
+ from tqdm import tqdm
156
+ def validate_param_list(param_list):
157
+ if len(param_list) == 0:
158
+ raise ValueError("param_list cannot be empty.")
159
+ for sublist in param_list:
160
+ if len(sublist) == 0:
161
+ raise ValueError("Sub-lists in param_list cannot be empty.")
162
+ def Mul_sub(task, param_list, num=6):
163
+ print(f"Pro num {num}")
164
+ validate_param_list(param_list)
165
+ if len(param_list) == 1:
166
+ product_list = [(x,) for x in param_list[0]]
167
+ else:
168
+ product_list = list(product(*param_list))
169
+ with PoolExecutor(max_workers=num) as executor:
170
+ try:
171
+ futures = [executor.submit(task, item) for item in product_list]
172
+ for future in tqdm(as_completed(futures), total=len(futures), desc="Processing tasks", unit="task"):
173
+ future.result()
174
+ except KeyboardInterrupt:
175
+ sys.exit(1)
176
+ print("All tasks completed")
79
177
 
80
- makeListUTC = []
81
- for UTC in timeList:
82
- UTCStr = UTC.strftime("%Y%m%d%H%M")
83
- outpath = f"{output}/{UTCStr[:4]}/{UTCStr[:8]}/MSP2_WTX_AIW_QPF_L88_CHN_{UTCStr}_00000-00300-00006.nc"
84
- if not os.path.exists(outpath) or isOverwrite:
85
- makeListUTC.append(UTC)
86
- [print(element) for element in makeListUTC]
178
+ from concurrent.futures import ThreadPoolExecutor
179
+ from itertools import product
180
+ def Mul_TH(task, param_list, max_workers=6):
181
+ print(f"Thread num: {max_workers}")
182
+ validate_param_list(param_list)
183
+ task_args = [
184
+ (arg,) if len(param_list) == 1 else arg
185
+ for arg in (
186
+ param_list[0] if len(param_list) == 1
187
+ else product(*param_list)
188
+ )
189
+ ]
190
+ with ThreadPoolExecutor(max_workers) as ex:
191
+ try:
192
+ list(ex.map(task, task_args))
193
+ except KeyboardInterrupt:
194
+ print("\n用户中断操作")
195
+ ex.shutdown(wait=False)
196
+ sys.exit(1)
87
197
 
88
- phaseCMD = "--isPhase" if isPhase else ""
89
- debugCMD = "--isDebug" if isDebug else ""
90
- OverwriteCMD = "--isOverwrite"
91
- gpuCMD = f"--gpu={gpu}"
92
- # cmdList = list(map(lambda x:f"python main.py --times={x.strftime('%Y%m%d%H%M')} {phaseCMD} {debugCMD} {OverwriteCMD} {gpuCMD}",makeListUTC))
93
- cmdList = list(map(lambda x:f"python main.py --times={x.strftime('%Y%m%d%H%M')} {phaseCMD} {debugCMD} {gpuCMD}",makeListUTC))
198
+ import traceback
199
+ import shutil, os
200
+ def safe_del(path):
201
+ try:
202
+ shutil.rmtree(path) if os.path.isdir(path) else None
203
+ print(f"{path} deleted")
204
+ except Exception:
205
+ print(traceback.format_exc())
94
206
 
95
- with Pool(pool) as p:
96
- p.map(excuteCommand, cmdList)
207
+ """
208
+ safe_del("./data")
97
209
  """
98
210
 
211
+ import os, glob
212
+ def clean_files(folder, keep=0):
213
+ if os.path.isdir(folder):
214
+ try:
215
+ files = [os.path.join(folder, f) for f in os.listdir(folder)
216
+ if os.path.isfile(os.path.join(folder, f))]
217
+ if keep > 0 and len(files) > keep:
218
+ files.sort(key=os.path.getmtime)
219
+ [os.remove(f) for f in files[:-keep]]
220
+ elif keep == 0:
221
+ [os.remove(f) for f in files]
222
+ except Exception as e:
223
+ print(traceback.format_exc())
99
224
 
100
- '''
101
- # @Time : 2023/09/27 下午8:52
102
- # @Author : shanchangxi
103
- # @File : util_log.py
104
- import time
105
- import logging
106
- from logging import handlers
107
-
108
- logger = logging.getLogger()
109
- logger.setLevel(logging.INFO)
110
- log_name = 'project_tim_tor.log'
111
- logfile = log_name
112
- time_rotating_file_handler = handlers.TimedRotatingFileHandler(filename=logfile, when='D', encoding='utf-8')
113
- time_rotating_file_handler.setLevel(logging.INFO)
114
- formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
115
- time_rotating_file_handler.setFormatter(formatter)
116
- logger.addHandler(time_rotating_file_handler)
117
- print_handler = logging.StreamHandler()
118
- print_handler.setFormatter(formatter)
119
- logger.addHandler(print_handler)
120
-
121
- '''
122
-
123
- '''
124
- ###解决方法 pip install torch==2.4.0 torchvision torchaudio三个同时安装 python 3.12 解决cuda启动不了的问题
225
+ """
226
+ clean_files("./logs", keep=10)
227
+ clean_files("./temp")
228
+ """
125
229
 
126
- Res网络
127
- '''
230
+ # import os
231
+ # from datetime import datetime
232
+ # from shancx.NN import _loggers
233
+ # from shancx import lock_file
234
+ # from shancx.wait import check_lock
235
+ # from shancx import crDir
236
+ # logger =_loggers()
237
+ # def check_process_data(UTC, sat_cd,basepath ="/mnt/wtx_weather_forecast/scx/test/lock_files" ):
238
+ # try:
239
+ # UTCStr = UTC.strftime("%Y%m%d%H%M")
240
+ # file = f"/mnt/wtx_weather_forecast/scx/test/lock_files/{sat_cd}/{UTCStr[:4]}/{UTCStr[:8]}/File_{UTCStr}.lock"
241
+ # crDir(file)
242
+ # if not lock_file(file):
243
+ # if check_lock(file):
244
+ # logger.info("data is making or maked")
245
+ # return True ,file
246
+ # return False,file
247
+ # except Exception as e:
248
+ # logger.error(f"Error in check_and_process_data: {str(e)}")
249
+ # return False,file
250
+ # """
251
+ # flag1,file = check_process_data(UTC, "H9SEAS" )
252
+ # if flag1:
253
+ # sys.exit()
254
+ # if os.path.exists(output_path): #配合使用
255
+ # sys.exit()
256
+ # """