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/WN/__init__.py DELETED
@@ -1,132 +0,0 @@
1
- #!/usr/bin/python
2
- # -*- coding: utf-8 -*-
3
- import os
4
- def start():
5
- print("import successful")
6
- # constants
7
-
8
- __author__ = 'shancx'
9
-
10
- __author_email__ = 'shancx@126.com'
11
-
12
- # @Time : 2023/09/27 下午8:52
13
- # @Author : shanchangxi
14
- # @File : util_log.py
15
- import time
16
- import logging
17
- from logging import handlers
18
-
19
- def mkDir(path):
20
- if "." in path:
21
- os.makedirs(os.path.dirname(path),exist_ok=True)
22
- else:
23
- os.makedirs(path, exist_ok=True)
24
-
25
- loggers = logging.getLogger()
26
- loggers.setLevel(logging.INFO)
27
- log_name = './project_W.log'
28
- mkDir(log_name)
29
- logfile = log_name
30
- time_rotating_file_handler = handlers.TimedRotatingFileHandler(filename=logfile, when='D', encoding='utf-8')
31
- time_rotating_file_handler.setLevel(logging.INFO)
32
- formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
33
- time_rotating_file_handler.setFormatter(formatter)
34
- loggers.addHandler(time_rotating_file_handler)
35
-
36
- """
37
- import tracback
38
- try:
39
-
40
- except Exception as e:
41
-
42
- logger.info(traceback.format_exc())
43
- """
44
- '''
45
- ##定義一個streamHandler
46
- # print_handler = logging.StreamHandler()
47
- # print_handler.setFormatter(formatter)
48
- # loggers.addHandler(print_handler)
49
- '''
50
-
51
- """
52
- from main import makeAll,options
53
- from multiprocessing import Pool
54
- import datetime
55
- from config import logger,output
56
- import time
57
- import pandas as pd
58
- import os
59
- from itertools import product
60
- import threading
61
-
62
- def excuteCommand(cmd):
63
- print(cmd)
64
- os.system(cmd)
65
-
66
- def gpuPro(makeListUTC, isPhase, isDebug, gpu, isOverwrite):
67
- productList = product(makeListUTC, [isPhase], [isDebug], [gpu], [isOverwrite])
68
-
69
- with Pool(4) as p:
70
- p.map(makeAll, productList)
71
-
72
- if __name__ == '__main__':
73
- cfg = options()
74
- isPhase = cfg.isPhase
75
- isDebug = cfg.isDebug
76
- sepSec = cfg.sepSec
77
- gpu = cfg.gpu
78
- pool = cfg.pool
79
- isOverwrite = cfg.isOverwrite
80
- timeList = pd.date_range(cfg.times[0], cfg.times[-1], freq=f"{sepSec}s")
81
- logger.info(f"时间段check {timeList}")
82
- gpuNum = 2
83
- eachGPU = 4
84
-
85
- makeListUTC = []
86
- for UTC in timeList:
87
- UTCStr = UTC.strftime("%Y%m%d%H%M")
88
- outpath = f"{output}/{UTCStr[:4]}/{UTCStr[:8]}/MSP2_WTX_AIW_QPF_L88_CHN_{UTCStr}_00000-00300-00006.nc"
89
- if not os.path.exists(outpath) or isOverwrite:
90
- makeListUTC.append(UTC)
91
- [print(element) for element in makeListUTC]
92
-
93
- phaseCMD = "--isPhase" if isPhase else ""
94
- debugCMD = "--isDebug" if isDebug else ""
95
- OverwriteCMD = "--isOverwrite"
96
- gpuCMD = f"--gpu={gpu}"
97
- # cmdList = list(map(lambda x:f"python main.py --times={x.strftime('%Y%m%d%H%M')} {phaseCMD} {debugCMD} {OverwriteCMD} {gpuCMD}",makeListUTC))
98
- cmdList = list(map(lambda x:f"python main.py --times={x.strftime('%Y%m%d%H%M')} {phaseCMD} {debugCMD} {gpuCMD}",makeListUTC))
99
-
100
- with Pool(pool) as p:
101
- p.map(excuteCommand, cmdList)
102
- """
103
-
104
-
105
- '''
106
- # @Time : 2023/09/27 下午8:52
107
- # @Author : shanchangxi
108
- # @File : util_log.py
109
- import time
110
- import logging
111
- from logging import handlers
112
-
113
- logger = logging.getLogger()
114
- logger.setLevel(logging.INFO)
115
- log_name = 'project_tim_tor.log'
116
- logfile = log_name
117
- time_rotating_file_handler = handlers.TimedRotatingFileHandler(filename=logfile, when='D', encoding='utf-8')
118
- time_rotating_file_handler.setLevel(logging.INFO)
119
- formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
120
- time_rotating_file_handler.setFormatter(formatter)
121
- logger.addHandler(time_rotating_file_handler)
122
- print_handler = logging.StreamHandler()
123
- print_handler.setFormatter(formatter)
124
- logger.addHandler(print_handler)
125
-
126
- '''
127
-
128
- '''
129
- ###解决方法 pip install torch==2.4.0 torchvision torchaudio三个同时安装 python 3.12 解决cuda启动不了的问题
130
-
131
- Res网络
132
- '''
shancx/code.py DELETED
@@ -1,331 +0,0 @@
1
- '''
2
- df to station
3
-
4
- from hjnwtx.mkNCHJN import envelope,cropDF
5
- import numpy as np
6
- import pandas as pd
7
- import copy
8
- from hjnwtx.examMeso import getPointIdx
9
- import datetime
10
- import os.path
11
- import traceback
12
- import os.path as osp
13
- import pandas as pd
14
- import netCDF4 as nc
15
- from matrixLib import F1,TS,ACC,PO,FAR,sun_rain_Matrix,pre1h_Matrix,pre1h_Matrix_New
16
- from hjnwtx.hjnMiscellaneous import options
17
- import glob
18
- import pygrib as pg
19
- from multiprocessing import Pool
20
- from concurrent.futures import ThreadPoolExecutor as Pool_T
21
- import matplotlib.pyplot as plt
22
- from hjnwtx.examMeso import getPoint
23
- from dateutil.relativedelta import relativedelta
24
- import warnings
25
- import numpy as np
26
- from hjnwtx.mkNCHJN import mkDir
27
- import numpy as np
28
- from hjnwtx.mkNCHJN import envelope,cropDF
29
- from config import InterCObs15MPath,GlobStationPath
30
- import copy
31
- from shancx import Mul_sub
32
- import glob
33
- from shancx.radar_nmc import drawimg_coor,drawimg
34
- from getGFS import GetTP
35
- import datetime
36
-
37
- """
38
- mqpfStationPath,cldasPath_old,
39
- """
40
- from config import (mqpfPath,mqpfCSVPath,NMCStationPath,exam_pngPath,NMCStationPath_bak,
41
- YTWMPath,midPath,logger)
42
- # from parseCY import getJson
43
- from itertools import product
44
- # from config import cldasPath,
45
- from matplotlib.font_manager import FontProperties
46
- import argparse
47
- from hjnwtx.examMeso import classify1h
48
-
49
- plt.rcParams["font.sans-serif"]=["SimHei"] #设置字体
50
- plt.rcParams["axes.unicode_minus"]=False #该语句解决图像中的“-”负号的乱码问题
51
-
52
- from hjn.hjnLAPSTransform import LAPSTransfrom
53
- from sklearn.metrics import confusion_matrix
54
- # 禁止显示警告
55
- warnings.filterwarnings("ignore")
56
- import matplotlib.pyplot as plt
57
- from hjnwtx.colormap import cmp_hjnwtx
58
-
59
-
60
- ENV = envelope(54.2,12.21,73,134.99)
61
- # env_Range = envelope(85.05112877980659, -85.09887122019342,-179.56702040954826,179.63297959045173)
62
- env_Range = ENV
63
- df_areaID = pd.read_csv("./stationID_Base.csv")
64
- # df_areaID = df_areaID[~np.pd.isna(df_areaID["area_code"])]
65
- df_areaID = df_areaID[~pd.isna(df_areaID["area_code"])]
66
- df_areaID.rename(columns={"area_code": "stationID"}, inplace=True)
67
- df_areaID = copy.deepcopy(cropDF(df_areaID, ENV))
68
-
69
- class envelope():
70
- def __init__(self,n,s,w,e):
71
- self.n,self.s,self.w,self.e=n,s,w,e
72
- def __str__(self):
73
- return ("n:%s,s:%s,w:%s,e:%s"%(self.n,self.s,self.w,self.e))
74
- def cropDF(df,evn):
75
- return df[(df["Lat"]>evn.s)&(df["Lat"]<evn.n)&(df["Lon"]>evn.w)&(df["Lon"]<evn.e)]
76
-
77
- def makeCHNDF(df_Station,shape_v =[4200,6200] ,col_flg = "PRE1"):
78
- # env_Range = envelope(85.05112877980659, -85.09887122019342,-179.56702040954826,179.63297959045173)
79
- df_Station_C = cropDF(df_Station, env_Range)
80
- df_Station_C = df_Station_C[df_Station_C[f"{col_flg}"]<9999]
81
- CHNMAt = np.full(shape_v,np.nan)
82
- latIdx, lonIdx = getPointIdx(df_Station_C, env_Range.n,env_Range.w, 0.01)
83
- CHNMAt[latIdx,lonIdx] = df_Station_C[f"{col_flg}"]
84
- return CHNMAt
85
- # makeCHNDF(df_areaID,shape_v =[4200,6200] ,col_flg = "PRE1")
86
- # y_coords2 , x_coords2 = np.where(mask_labels2 == True)
87
- # # First subplot
88
- # im1 = axs[0].imshow(inputs_img1, cmap=cmp_hjnwtx["radar_nmc"], vmin=5, vmax=70)
89
- # for (x, y) in zip(x_coords2, y_coords2):
90
- # axs[0].plot(x, y, 'ro', markersize=25) # Increase point size
91
- # axs[0].text(x, y, f'{(labels_img2[y, x] * 6):.1f}', color='white', fontsize=12, ha='center', va='center') # Label the corresponding value
92
- # plt.plot(list(x_coords2), list(y_coords2), 'ro')
93
- def getRealPath(CST):
94
- CSTstr = CST.strftime("%Y%m%d%H%M")
95
- year = CSTstr[:4]
96
- month = CSTstr[4:8]
97
- path1 = f"{InterCObs15MPath}/{year}/{month}/{CSTstr[:12]}00_*.csv"
98
- return path1
99
-
100
- def getRealTimeCSV(CST,df_area):
101
- logger.info(f"开始读取实况数据")
102
- all = None
103
- # UTC = CST+relativedelta(hours=-8)
104
- for i in range(2):
105
- for jj in range(10):
106
- CSTAdd = (CST+relativedelta(hours=1+i))
107
- pathInterCObs15Mstr = getRealPath(CSTAdd)
108
- pathInterCObs15M = glob.glob(pathInterCObs15Mstr)
109
- if len(pathInterCObs15M) > 0:
110
- df = pd.read_csv(pathInterCObs15M[0])
111
- df['Area_code'] = df['area_code'].apply(lambda x : x.replace("WTX","WNI") ).astype(str)
112
- df.rename(columns={"Area_code":"stationID","pre_1h":f"PRE{i+1}"},inplace=True)
113
- break
114
- else:
115
- print(pathInterCObs15M," Real DATA path missing")
116
- return None
117
- df = df[["stationID",f"PRE{i+1}"]]
118
- df = pd.merge(df,df_area,on="stationID")
119
- if all is None:
120
- all = df
121
- else:
122
- all = pd.merge(all,df[["stationID",f"PRE{i+1}"]],on="stationID" )
123
- # all.rename(columns={"PRE_x":"PRE1","PRE_y":"PRE2","PRE_z":"PRE3"},inplace=True)
124
- logger.info(f"Real QPF length {len(all)}")
125
- return all
126
-
127
-
128
- if __name__ == '__main__':
129
-
130
- import datetime
131
- import os.path
132
- import traceback
133
- import os.path as osp
134
- import pandas as pd
135
- import netCDF4 as nc
136
- from matrixLib import F1,TS,ACC,PO,FAR,sun_rain_Matrix,pre1h_Matrix,pre1h_Matrix_New
137
- from hjnwtx.hjnMiscellaneous import options
138
- import glob
139
- import pygrib as pg
140
- from multiprocessing import Pool
141
- from concurrent.futures import ThreadPoolExecutor as Pool_T
142
- import matplotlib.pyplot as plt
143
- from hjnwtx.examMeso import getPoint
144
- from dateutil.relativedelta import relativedelta
145
- import warnings
146
- import numpy as np
147
- from hjnwtx.mkNCHJN import mkDir
148
- import numpy as np
149
- from hjnwtx.mkNCHJN import envelope,cropDF
150
- from config import InterCObs15MPath
151
- import copy
152
- from shancx import Mul_sub
153
- import glob
154
- from shancx.radar_nmc import drawimg_coor,drawimg
155
- from getGFS import GetTP
156
-
157
- """
158
- mqpfStationPath,cldasPath_old,
159
- """
160
- from config import (mqpfPath,mqpfCSVPath,NMCStationPath,exam_pngPath,NMCStationPath_bak,
161
- YTWMPath,midPath,logger)
162
- # from parseCY import getJson
163
- from itertools import product
164
- # from config import cldasPath,
165
- from matplotlib.font_manager import FontProperties
166
- import argparse
167
- from hjnwtx.examMeso import classify1h
168
-
169
- plt.rcParams["font.sans-serif"]=["SimHei"] #设置字体
170
- plt.rcParams["axes.unicode_minus"]=False #该语句解决图像中的“-”负号的乱码问题
171
-
172
- from hjn.hjnLAPSTransform import LAPSTransfrom
173
- from sklearn.metrics import confusion_matrix
174
- # 禁止显示警告
175
- warnings.filterwarnings("ignore")
176
- import matplotlib.pyplot as plt
177
-
178
- ENV = envelope(85.05112877980659, -85.09887122019342, -179.61702040954827, 179.63297959045173)
179
- df_areaID = pd.read_csv("./stationID_Base.csv")
180
- # df_areaID = df_areaID[~np.pd.isna(df_areaID["area_code"])]
181
- df_areaID = df_areaID[~pd.isna(df_areaID["area_code"])]
182
- df_areaID.rename(columns={"area_code": "stationID"}, inplace=True)
183
- df_areaID = copy.deepcopy(cropDF(df_areaID, ENV))
184
- def cropDF(df,evn):
185
- return df[(df["Lat"]>evn.s)&(df["Lat"]<evn.n)&(df["Lon"]>evn.w)&(df["Lon"]<evn.e)]
186
- df = pd.read_csv("/home/scx/sta_glob1.csv") #['sta', 'lat', 'lon']
187
- envList = {}
188
- for i in range(len(df)):
189
- # print(df.iloc[i])
190
- lonC = np.round(df.iloc[i].lon.astype(np.float64),2)
191
- latC = np.round(df.iloc[i].lat.astype(np.float64),2)
192
- Site_Code = df.iloc[i].sta
193
- envList[Site_Code] = envelope(latC+1.20,latC-1.20,lonC-1.20,lonC+1.20) #envelope(latC+1.28,latC-1.27,lonC-1.28,lonC+1.27)
194
-
195
- def getRardarStation(conf):
196
- sta = conf[0]
197
- logger.info(conf)
198
- df1 = cropDF(df_areaID,envList[f"{sta}"])
199
- return df1
200
- from shancx import Mul_sub
201
- data = Mul_sub(getRardarStation,[df["sta"]],31)
202
- print()
203
- dfStation = pd.concat(data)
204
- df_unique = dfStation.drop_duplicates(subset='stationID')
205
- # df_unique.to_csv("dfStation5.csv",index=False)
206
-
207
- df_areaID = df_unique
208
- CST = datetime.datetime(2024,8,31,1,0)
209
- RealData = getRealTimeCSV(CST,df_areaID)
210
- print()
211
- Data = makeCHNDF(RealData,shape_v =[4200,6200] ,col_flg = "PRE1") # y_coords2 , x_coords2 = np.where(Data >0.1)
212
- y_coords2 , x_coords2 = np.where(Data >=0.1)
213
- with nc.Dataset('/mnt/wtx_weather_forecast/WTX_DATA/RADA/MQPF/2024/20240829/MSP2_WTX_AIW_QPF_L88_CHN_202408291800_00000-00300-00006.nc') as dataNC:
214
- # for i in dataPG:
215
- # print(i)
216
- latArr = dataNC["lat"][:]
217
- lonArr = dataNC["lon"][:]
218
- pre = dataNC["MQPF"][:]
219
- from shancx.radar_nmc import drawimg
220
- from shancx.radar_nmc_china_map_f
221
- from shancx import crDir
222
- now_str = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
223
- plt.imshow(pre[0,:,:],vmin=0,vmax=10,cmap=cmp_hjnwtx["pre_tqw"])
224
- plt.plot(list(x_coords2), list(y_coords2), 'ro', markersize=1)
225
- plt.colorbar()
226
- outpath = f"./radar_nmc/temp_{now_str}.png"
227
- crDir(outpath)
228
- plt.savefig(outpath)
229
- plt.close()
230
-
231
-
232
- from shancx.radar_nmc import drawimg
233
- from shancx import crDir
234
- now_str = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
235
- plt.imshow(pre[0,:,:],vmin=0,vmax=10,cmap=cmp_hjnwtx["pre_tqw"])
236
- plt.plot(list(y_coords2), list(x_coords2), 'ro')
237
- plt.colorbar()
238
- outpath = f"./radar_nmc/temp_{now_str}.png"
239
- crDir(outpath)
240
- plt.savefig(outpath)
241
- plt.close()
242
-
243
-
244
-
245
- # plt.subplot(3, 3, 3)
246
- # plt.imshow(outputs_image, cmap=cmp_hjnwtx["pre_tqw"], vmin=0, vmax=200)
247
- # plt.plot(list(x_coords2), list(y_coords2), 'ro')
248
- # addline()
249
- '''
250
-
251
- '''
252
-
253
- FilterSites
254
-
255
- import datetime
256
- import os.path
257
- import traceback
258
- import os.path as osp
259
- import pandas as pd
260
- import netCDF4 as nc
261
- from matrixLib import F1,TS,ACC,PO,FAR,sun_rain_Matrix,pre1h_Matrix,pre1h_Matrix_New
262
- from hjnwtx.hjnMiscellaneous import options
263
- import glob
264
- import pygrib as pg
265
- from multiprocessing import Pool
266
- from concurrent.futures import ThreadPoolExecutor as Pool_T
267
- import matplotlib.pyplot as plt
268
- from hjnwtx.examMeso import getPoint
269
- from dateutil.relativedelta import relativedelta
270
- import warnings
271
- import numpy as np
272
- from hjnwtx.mkNCHJN import mkDir
273
- import numpy as np
274
- from hjnwtx.mkNCHJN import envelope,cropDF
275
- from config import InterCObs15MPath
276
- import copy
277
- from shancx import Mul_sub
278
- import glob
279
- from shancx.radar_nmc import drawimg_coor,drawimg
280
- from getGFS import GetTP
281
-
282
- """
283
- mqpfStationPath,cldasPath_old,
284
- """
285
- from config import (mqpfPath,mqpfCSVPath,NMCStationPath,exam_pngPath,NMCStationPath_bak,
286
- YTWMPath,midPath,logger)
287
- # from parseCY import getJson
288
- from itertools import product
289
- # from config import cldasPath,
290
- from matplotlib.font_manager import FontProperties
291
- import argparse
292
- from hjnwtx.examMeso import classify1h
293
-
294
- plt.rcParams["font.sans-serif"]=["SimHei"] #设置字体
295
- plt.rcParams["axes.unicode_minus"]=False #该语句解决图像中的“-”负号的乱码问题
296
-
297
- from hjn.hjnLAPSTransform import LAPSTransfrom
298
- from sklearn.metrics import confusion_matrix
299
- # 禁止显示警告
300
- warnings.filterwarnings("ignore")
301
- import matplotlib.pyplot as plt
302
-
303
- ENV = envelope(85.05112877980659, -85.09887122019342, -179.61702040954827, 179.63297959045173)
304
- df_areaID = pd.read_csv("./stationID_Base.csv")
305
- # df_areaID = df_areaID[~np.pd.isna(df_areaID["area_code"])]
306
- df_areaID = df_areaID[~pd.isna(df_areaID["area_code"])]
307
- df_areaID.rename(columns={"area_code": "stationID"}, inplace=True)
308
- df_areaID = copy.deepcopy(cropDF(df_areaID, ENV))
309
- def cropDF(df,evn):
310
- return df[(df["Lat"]>evn.s)&(df["Lat"]<evn.n)&(df["Lon"]>evn.w)&(df["Lon"]<evn.e)]
311
- df = pd.read_csv("/home/scx/sta_glob1.csv") #['sta', 'lat', 'lon']
312
- envList = {}
313
- for i in range(len(df)):
314
- # print(df.iloc[i])
315
- lonC = np.round(df.iloc[i].lon.astype(np.float64),2)
316
- latC = np.round(df.iloc[i].lat.astype(np.float64),2)
317
- Site_Code = df.iloc[i].sta
318
- envList[Site_Code] = envelope(latC+0.26,latC-0.25,lonC-0.26,lonC+0.25) #envelope(latC+1.28,latC-1.27,lonC-1.28,lonC+1.27)
319
-
320
- def getRardarStation(conf):
321
- sta = conf[0]
322
- logger.info(conf)
323
- df1 = cropDF(df_areaID,envList[f"{sta}"])
324
- return df1
325
- from shancx import Mul_sub
326
- data = Mul_sub(getRardarStation,[df["sta"]],31)
327
- print()
328
- dfStation = pd.concat(data)
329
- df_unique = dfStation.drop_duplicates(subset='stationID')
330
- df_unique.to_csv("dfStation5.csv",index=False)
331
- '''
shancx/draw_day_CR_PNG.py DELETED
@@ -1,200 +0,0 @@
1
- import matplotlib.pyplot as plt
2
- import datetime
3
- from hjnwtx.colormap import cmp_hjnwtx
4
- import time
5
- import os
6
- import time
7
- import shutil
8
-
9
- from dateutil.relativedelta import relativedelta
10
- import glob
11
- from config import logger
12
- import argparse
13
- import pandas as pd
14
- import re
15
- import netCDF4 as nc
16
- from multiprocessing import Pool
17
- from itertools import product
18
- import numpy as np
19
- import copy
20
- import traceback
21
-
22
-
23
- from multiprocessing import Process, Queue
24
-
25
- import io
26
- import cartopy.crs as ccrs
27
- import cartopy.feature as cfeature
28
- import cartopy.io.shapereader as shpreader
29
- from shancx import crDir
30
-
31
- def add_china_map(ax):
32
- # 在地图上添加地形特征
33
- ax.add_feature(cfeature.COASTLINE, edgecolor='gray')
34
- ax.add_feature(cfeature.BORDERS, linestyle=':', edgecolor='gray')
35
- ax.add_feature(cfeature.LAKES, alpha=0.8)
36
- # 添加省份轮廓
37
- provinces = shpreader.natural_earth(resolution='10m', category='cultural', name='admin_1_states_provinces')
38
- provinces_features = shpreader.Reader(provinces).geometries()
39
- ax.add_geometries(provinces_features, ccrs.PlateCarree(), facecolor='none', edgecolor='gray', linestyle=':', linewidth=0.5, alpha=0.8)
40
-
41
-
42
- def draw_subplot(args):
43
- index, tp, vmax, vmin, cmap,time_index, name = args
44
- # print(time_index)
45
- # logger.info(f"Processing index: {index}")
46
- # logger.info(time_index)
47
- fig, ax = plt.subplots(figsize=(10, 10))
48
-
49
- # 创建绘图和设置坐标系
50
- # fig = plt.figure(figsize=(10, 8))
51
- ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
52
-
53
- # 设置图像显示的范围
54
- ax.set_extent([73, 135, 18, 54], ccrs.PlateCarree()) # 根据需要调整
55
-
56
- # 添加中国地图的边界和特征,包括省份轮廓
57
- add_china_map(ax)
58
-
59
- ax.imshow(tp, vmin=0, vmax=100, cmap=cmp_hjnwtx["radar_nmc"], transform=ccrs.PlateCarree(), extent=[73, 134.99, 12.21, 54.2], alpha=1)
60
-
61
-
62
- # ax.imshow(tp, vmax=vmax, vmin=vmin, cmap=cmap)
63
- ax.axis('off')
64
- # ax.text(0.5, 0.5, str(index), transform=ax.transAxes, color='white', fontsize=20, ha='center', va='center')
65
- ax.text(0.95, 0.95, f'{time_index}', transform=ax.transAxes, color='white', fontsize=20, ha='right', va='bottom')
66
- ax.text(0.925, 0.925, f'{str(index)}', transform=ax.transAxes, color='white', fontsize=20, ha='right', va='top')
67
- fig.tight_layout()
68
-
69
- buf = io.BytesIO()
70
- plt.savefig(buf, format='png')
71
- buf.seek(0)
72
- plt.close(fig)
73
- return (index, buf) #返回两个数为元组
74
-
75
- # 修改读取部分
76
- def drawpic(tp, Count,timeList, name="temp"):
77
- vmax = 70
78
- vmin = 0
79
- cmap = cmp_hjnwtx["radar_nmc"]
80
- args_list = [ (index, tp[index, :, :], vmax, vmin, cmap,timeList[index], name) for index in range(2 * Count)]
81
-
82
- with Pool(31) as pool:
83
- results = pool.map(draw_subplot, args_list)
84
-
85
- buffers = [result[1] for result in results]
86
- combined_fig, axs = plt.subplots(2, Count, figsize=(10 * Count, 20))
87
- for i in range(2):
88
- for j in range(Count):
89
- index = i * Count + j
90
- ax = axs[i, j]
91
- ax.imshow(plt.imread(buffers[index]), cmap=cmap)
92
- ax.axis('off')
93
-
94
- now_str = datetime.datetime.now().strftime("%Y%m%d%H%M")
95
- plt.tight_layout()
96
- outpath = f"./{timeList[0].strftime('%Y%m%d%H%M')}_CR/{name}_{now_str}.png"
97
- crDir(outpath)
98
- plt.savefig(outpath)
99
- plt.close(combined_fig)
100
-
101
- BASE_TARGET_PATH = "/mnt/wtx_weather_forecast/WTX_DATA/RADA/MQPF"
102
-
103
-
104
- def get_mqpf_paths(UCTstr):
105
- year = UCTstr[:4]
106
- date = UCTstr[:8]
107
- mqpfPath_pattern = os.path.join(BASE_TARGET_PATH,year, date,f"MSP2_WTX_AIW_REF_L88_CHN_{UCTstr}_00000-00300-00006.nc")
108
- # mqpfPath_pattern = os.path.join(BASE_TARGET_PATH,year, date,f"MSP2_WTX_AIW_MQPF_L88_CHN_{UCTstr}_00000-00300-00006.nc")
109
-
110
- return mqpfPath_pattern
111
-
112
- def map_data(conf):
113
- CST = conf[0]
114
- UCT = CST + relativedelta(hours=-8)
115
- UCTstr = UCT.strftime("%Y%m%d%H%M")
116
- mqpfPath_pattern = get_mqpf_paths(UCTstr)
117
- mqpfPath_list = glob.glob(mqpfPath_pattern)
118
- if len(mqpfPath_list) == 0:
119
- data_loss = re.findall(r"(2024\d{8}?)",mqpfPath_pattern)
120
- print("data_loss",data_loss)
121
- print("data_loss_path",mqpfPath_pattern)
122
- tj_list.append(data_loss[0])
123
- return np.full((1, 4200, 6200), np.nan)
124
- else:
125
- try:
126
- with nc.Dataset(mqpfPath_list[0]) as dataNC:
127
- mqpf = dataNC.variables["CR"][:]
128
- mqpf = mqpf[:1]
129
- if mqpf.shape != (1, 4200, 6200):
130
- logger.info(mqpf.shape )
131
- logger.info(mqpfPath_list[0])
132
- print("mqpf shape error",mqpf.shape)
133
- mqpf = mqpf[:,:-1, :-1]
134
- if mqpf.shape != (1, 4200, 6200):
135
- return np.full((1, 4200, 6200), np.nan)
136
- else:
137
- return mqpf
138
- print("mqpf",UCTstr,mqpf.shape)
139
- tj_list1.append(mqpfPath_pattern)
140
- return mqpf
141
- except Exception as e:
142
- print(traceback.format_exc())
143
- return np.full((1, 4200, 6200), np.nan)
144
-
145
- def options():
146
- parser = argparse.ArgumentParser(description='hjn')
147
- # parser.add_argument('--times', type=str, default='202406290000,202406300000')
148
- parser.add_argument('--times', type=str, default='202407210000,202407220000')
149
- parser.add_argument('--pac', type=str, default='100000')
150
- # parser.add_argument('--combine', action='store_true', default=False)
151
- parser.add_argument('--combine',action='store_true',default=False)
152
- parser.add_argument('--isDebug',action='store_true',default=False)
153
- parser.add_argument('--isDraw',action='store_true',default=False)
154
- parser.add_argument('--freq', type=str, default="1H")
155
- parser.add_argument('--tag',type=str, default=datetime.datetime.now().strftime("%Y%m%d%H%M"))
156
- config= parser.parse_args()
157
- print(config)
158
- config.times = config.times.split(",")
159
- config.pac = config.pac.split(",")
160
- if len(config.times) == 1:
161
- config.times = [config.times[0], config.times[0]]
162
- config.times = [datetime.datetime.strptime(config.times[0], "%Y%m%d%H%M"),
163
- datetime.datetime.strptime(config.times[1], "%Y%m%d%H%M")]
164
- return config
165
- if __name__ == '__main__':
166
- cfg = options()
167
- sCST = cfg.times[0]
168
- eCST = cfg.times[-1]
169
- sCSTstr = sCST.strftime("%Y%m%d")
170
- tj_list = []
171
- tj_list1= []
172
- start = datetime.datetime.now()
173
- timeList = pd.date_range(sCST,eCST,freq="360s",inclusive="left")
174
- # for CST in timeList:
175
- productList = product(timeList)
176
- with Pool(31) as p:
177
- Data = p.map(map_data,productList)
178
- end = datetime.datetime.now()
179
- print(start-end)
180
- Data_con = np.concatenate(Data,axis=0)
181
- loss_len = 240 - Data_con.shape[0]
182
- sCSTstr = sCST.strftime("%Y%m%d")
183
- eCSTstr = eCST.strftime("%Y%m%d")
184
- # Data_con1 = Data_con.filled()
185
- # np.save(f"data_{sCSTstr}_{eCSTstr}.npy",Data_con1)
186
- Data_con_120 = copy.copy(Data_con)
187
- drawpic(Data_con_120[:int(len(Data_con_120)/2)], int(len(Data_con_120)/4),timeList[:int(len(Data_con_120)/2)],name=f"temp120_{sCSTstr}_loss_{loss_len}_")
188
- print("done 120")
189
- end1 = datetime.datetime.now()
190
- print(end1-end)
191
- Data_con_240 = copy.copy(Data_con)
192
- print(Data_con_240[120:].shape)
193
- drawpic(Data_con_120[int(len(Data_con_120)/2):], int(len(Data_con_120)/4),timeList[int(len(Data_con_120)/2):],name=f"temp120_240_{sCSTstr}_{loss_len}_")
194
- print(datetime.datetime.now()-end1)
195
- print("done 120-240")
196
- logger.info("success")
197
-
198
-
199
- # "/mnt/wtx_weather_forecast/WTX_DATA/RADA/MQPF/2024/20240704/MSP2_WTX_AIW_REF_L88_CHN_202407040324_00000-00300-00006.nc"
200
-