wrfrun 0.1.7__py3-none-any.whl → 0.1.8__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.
wrfrun/core/error.py CHANGED
@@ -1,80 +1,110 @@
1
+ """
2
+ wrfrun.core.error
3
+ #################
4
+
5
+ This module defines all exceptions used in ``wrfrun``.
6
+
7
+ .. autosummary::
8
+ :toctree: generated/
9
+
10
+ WRFRunBasicError
11
+ ConfigError
12
+ WRFRunContextError
13
+ CommandError
14
+ OutputFileError
15
+ ResourceURIError
16
+ InputFileError
17
+ NamelistError
18
+ NamelistIDError
19
+ ExecRegisterError
20
+ GetExecClassError
21
+ ModelNameError
22
+ """
23
+
24
+
1
25
  class WRFRunBasicError(Exception):
2
26
  """
3
- Basic error type.
27
+ Basic exception class of ``wrfrun``. New exception **MUST** inherit this class.
4
28
  """
5
29
  pass
6
30
 
7
31
 
8
32
  class ConfigError(WRFRunBasicError):
9
33
  """
10
- Config cannot be used error.
34
+ Exception indicates the config of ``wrfrun`` or NWP model can't be used.
11
35
  """
12
36
  pass
13
37
 
14
38
 
15
39
  class WRFRunContextError(WRFRunBasicError):
16
40
  """
17
- Need to enter wrfrun context.
41
+ Exception indicates ``wrfrun`` is running out of the ``wrfrun`` context.
18
42
  """
19
43
  pass
20
44
 
21
45
 
22
46
  class CommandError(WRFRunBasicError):
23
47
  """
24
- The command is wrong.
48
+ Exception indicates the command of ``Executable`` can't be executed successfully.
25
49
  """
26
50
  pass
27
51
 
28
52
 
29
- class LoadConfigError(WRFRunBasicError):
53
+ class OutputFileError(WRFRunBasicError):
30
54
  """
31
- Failed to load config.
55
+ Exception indicates ``wrfrun`` can't find any output files with the given rules.
32
56
  """
33
57
  pass
34
58
 
35
59
 
36
- class OutputFileError(WRFRunBasicError):
60
+ class ResourceURIError(WRFRunBasicError):
37
61
  """
38
- No output found.
62
+ Exception indicates ``wrfrun`` can't parse the URI.
39
63
  """
40
64
  pass
41
65
 
42
66
 
43
- class ResourceURIError(WRFRunBasicError):
67
+ class InputFileError(WRFRunBasicError):
44
68
  """
45
- Error about resource namespace.
69
+ Exception indicates ``wrfrun`` can't find specified input files.
46
70
  """
47
71
  pass
48
72
 
49
73
 
50
- class InputFileError(WRFRunBasicError):
74
+ class NamelistError(WRFRunBasicError):
51
75
  """
52
- Input file error.
76
+ Exception indicates ``wrfrun`` can't find the namelist user want to use.
53
77
  """
54
78
  pass
55
79
 
56
80
 
57
- class NamelistError(WRFRunBasicError):
81
+ class NamelistIDError(WRFRunBasicError):
58
82
  """
59
- Error about namelist.
83
+ Exception indicates ``wrfrun`` can't register the specified namelist id.
60
84
  """
61
85
  pass
62
86
 
63
87
 
64
88
  class ExecRegisterError(WRFRunBasicError):
89
+ """
90
+ Exception indicates ``wrfrun`` can't register the specified ``Executable``.
91
+ """
65
92
  pass
66
93
 
67
94
 
68
95
  class GetExecClassError(WRFRunBasicError):
96
+ """
97
+ Exception indicates ``wrfrun`` can't find the specified ``Executable``.
98
+ """
69
99
  pass
70
100
 
71
101
 
72
102
  class ModelNameError(WRFRunBasicError):
73
103
  """
74
- Name of the model isn't found in the config file.
104
+ Exception indicates ``wrfrun`` can't find config of the specified NWP model in the config file.
75
105
  """
76
106
  pass
77
107
 
78
108
 
79
- __all__ = ["WRFRunBasicError", "ConfigError", "WRFRunContextError", "CommandError", "LoadConfigError", "OutputFileError", "ResourceURIError", "InputFileError",
80
- "NamelistError", "ExecRegisterError", "GetExecClassError", "ModelNameError"]
109
+ __all__ = ["WRFRunBasicError", "ConfigError", "WRFRunContextError", "CommandError", "OutputFileError", "ResourceURIError", "InputFileError",
110
+ "NamelistError", "ExecRegisterError", "GetExecClassError", "ModelNameError", "NamelistIDError"]
wrfrun/core/replay.py CHANGED
@@ -1,6 +1,29 @@
1
+ """
2
+ wrfrun.core.replay
3
+ ##################
4
+
5
+ This module provides methods to read config from ``.replay`` file and reproduce the simulation.
6
+
7
+ .. autosummary::
8
+ :toctree: generated/
9
+
10
+ WRFRunExecutableRegisterCenter
11
+ replay_config_generator
12
+
13
+ WRFRUNExecDB
14
+ ************
15
+
16
+ In order to load ``Executable`` correctly based on the stored ``name`` in ``.replay`` files,
17
+ ``wrfrun`` uses ``WRFRUNExecDB``, which is the instance of :class:`WRFRunExecutableRegisterCenter`,
18
+ to records all ``Executable`` classes and corresponding ``name``.
19
+ When ``wrfrun`` replays the simulation, it gets the right ``Executable`` from ``WRFRUNExecDB`` and executes it.
20
+ """
21
+
22
+ from collections.abc import Generator
1
23
  from json import loads
2
24
  from os.path import exists
3
25
  from shutil import unpack_archive
26
+ from typing import Any
4
27
 
5
28
  from .base import ExecutableBase, ExecutableConfig
6
29
  from .config import WRFRUNConfig
@@ -12,7 +35,8 @@ WRFRUN_REPLAY_URI = ":WRFRUN_REPLAY:"
12
35
 
13
36
  class WRFRunExecutableRegisterCenter:
14
37
  """
15
- Record all executable class.
38
+ This class provides the method to records ``Executable``'s class with a unique ``name``.
39
+ Later you can get the class with the ``name``.
16
40
  """
17
41
  _instance = None
18
42
  _initialized = False
@@ -31,64 +55,73 @@ class WRFRunExecutableRegisterCenter:
31
55
 
32
56
  return cls._instance
33
57
 
34
- def register_exec(self, unique_iq: str, cls: type):
58
+ def register_exec(self, name: str, cls: type):
35
59
  """
36
- Register an executable class.
60
+ Register an ``Executable``'s class with a unique ``name``.
61
+
62
+ If the ``name`` has been used, :class:`ExecRegisterError` will be raised.
37
63
 
38
- :param unique_iq: Unique ID.
39
- :type unique_iq: str
40
- :param cls: Class.
64
+ :param name: ``Executable``'s unique name.
65
+ :type name: str
66
+ :param cls: ``Executable``'s class.
41
67
  :type cls: type
42
- :return:
43
- :rtype:
44
68
  """
45
- if unique_iq in self._exec_db:
46
- logger.error(f"'{unique_iq}' has been registered.")
47
- raise ExecRegisterError(f"'{unique_iq}' has been registered.")
69
+ if name in self._exec_db:
70
+ logger.error(f"'{name}' has been registered.")
71
+ raise ExecRegisterError(f"'{name}' has been registered.")
48
72
 
49
- self._exec_db[unique_iq] = cls
73
+ self._exec_db[name] = cls
50
74
 
51
- def is_registered(self, unique_id: str) -> bool:
75
+ def is_registered(self, name: str) -> bool:
52
76
  """
53
- Check if an executable class has been registered.
77
+ Check if an ``Executable``'s class has been registered.
54
78
 
55
- :param unique_id: Unique ID.
56
- :type unique_id: str
79
+ :param name: ``Executable``'s unique name.
80
+ :type name: str
57
81
  :return: True or False.
58
82
  :rtype: bool
59
83
  """
60
- if unique_id in self._exec_db:
84
+ if name in self._exec_db:
61
85
  return True
62
86
  else:
63
87
  return False
64
88
 
65
- def get_cls(self, unique_id: str) -> type:
89
+ def get_cls(self, name: str) -> type:
66
90
  """
67
- Get a registered executable class.
91
+ Get an ``Executable``'s class with the ``name``.
92
+
93
+ If the ``name`` can't be found, :class:`GetExecClassError` will be raised.
68
94
 
69
- :param unique_id: Unique ID.
70
- :type unique_id: str
71
- :return: Executable class.
95
+ :param name: ``Executable``'s unique name.
96
+ :type name: str
97
+ :return: ``Executable``'s class.
72
98
  :rtype: type
73
99
  """
74
- if unique_id not in self._exec_db:
75
- logger.error(f"Executable class '{unique_id}' not found.")
76
- raise GetExecClassError(f"Executable class '{unique_id}' not found.")
100
+ if name not in self._exec_db:
101
+ logger.error(f"Executable class '{name}' not found.")
102
+ raise GetExecClassError(f"Executable class '{name}' not found.")
77
103
 
78
- return self._exec_db[unique_id]
104
+ return self._exec_db[name]
79
105
 
80
106
 
81
107
  WRFRUNExecDB = WRFRunExecutableRegisterCenter()
82
108
 
83
109
 
84
- def replay_config_generator(replay_config_file: str):
110
+ def replay_config_generator(replay_config_file: str) -> Generator[tuple[str, ExecutableBase], Any, None]:
85
111
  """
86
- Replay the simulations.
112
+ This method can read the ``.replay`` file and returns a generator which yields ``Executable`` and their names.
113
+ If this method doesn't find ``config.json`` in the ``.replay`` file, ``FileNotFoundError`` will be raised.
114
+
115
+ The ``Executable`` you get from the generator has been initialized so you can execute it directly.
116
+
117
+ >>> replay_file = "./example.replay"
118
+ >>> for name, _exec in replay_config_generator(replay_file):
119
+ >>> _exec.replay()
87
120
 
88
- :param replay_config_file: Replay file path.
121
+ :param replay_config_file: Path of the ``.replay`` file.
89
122
  :type replay_config_file: str
90
- :return:
91
- :rtype:
123
+ :return: A generator that yields: ``(name, Executable)``
124
+ :rtype: Generator
92
125
  """
93
126
  logger.info(f"Loading replay resources from: {replay_config_file}")
94
127
  work_path = WRFRUNConfig.parse_resource_uri(WRFRUNConfig.WRFRUN_REPLAY_WORK_PATH)
wrfrun/core/server.py CHANGED
@@ -1,7 +1,24 @@
1
+ """
2
+ wrfrun.core.server
3
+ ##################
4
+
5
+ Currently, ``wrfrun`` provides the method to reads log file of WRF and calculates simulation progress.
6
+ In order to report the progress to user, ``wrfrun`` provides :class:`WRFRunServer` to set up a socket server.
7
+
8
+ .. autosummary::
9
+ :toctree: generated/
10
+
11
+ get_wrf_simulated_seconds
12
+ WRFRunServer
13
+ WRFRunServerHandler
14
+ stop_server
15
+ """
16
+
1
17
  import socket
2
18
  import socketserver
3
19
  import subprocess
4
20
  from datetime import datetime
21
+ from json import dumps
5
22
  from time import time
6
23
  from typing import Tuple, Optional
7
24
 
@@ -14,13 +31,13 @@ WRFRUN_SERVER_THREAD = None
14
31
 
15
32
  def get_wrf_simulated_seconds(start_datetime: datetime, log_file_path: Optional[str] = None) -> int:
16
33
  """
17
- Get how many seconds wrf has integrated.
34
+ Read the latest line of WRF's log file and calculate how many seconds WRF has integrated.
18
35
 
19
36
  :param start_datetime: WRF start datetime.
20
37
  :type start_datetime: datetime
21
38
  :param log_file_path: Absolute path of the log file to be parsed.
22
39
  :type log_file_path: str
23
- :return: Seconds.
40
+ :return: Integrated seconds. If this method fails to calculate the time, the returned value is ``-1``.
24
41
  :rtype: int
25
42
  """
26
43
  # use linux cmd to get the latest line of wrf log files
@@ -34,7 +51,6 @@ def get_wrf_simulated_seconds(start_datetime: datetime, log_file_path: Optional[
34
51
 
35
52
  time_string = log_text.split()[1]
36
53
 
37
- seconds = -1
38
54
  try:
39
55
  current_datetime = datetime.strptime(time_string, "%Y-%m-%d_%H:%M:%S")
40
56
  # remove timezone info so we can calculate.
@@ -44,16 +60,56 @@ def get_wrf_simulated_seconds(start_datetime: datetime, log_file_path: Optional[
44
60
  except ValueError:
45
61
  seconds = -1
46
62
 
47
- finally:
48
- return seconds
63
+ return seconds
49
64
 
50
65
 
51
66
  class WRFRunServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
52
67
  """
53
68
  A socket server to report time usage.
69
+
70
+ If you want to use the socket server, you need to give four arguments: ``start_date``,
71
+ ``wrf_simulate_seconds``, ``socket_address_port`` and ``WRFRunServerHandler``.
72
+
73
+ >>> start_date = datetime(2021, 3, 25, 8)
74
+ >>> simulate_seconds = 60 * 60 * 72
75
+ >>> socket_address_port = ("0.0.0.0", 54321)
76
+ >>> _wrfrun_server = WRFRunServer(start_date, simulate_seconds, socket_address_port, WRFRunServerHandler)
77
+
78
+ Usually you don't need to create socket server manually, because :class:`WRFRun` will handle this.
79
+
80
+ .. py:attribute:: start_timestamp
81
+ :type: datetime
82
+
83
+ The time the socket server start.
84
+
85
+ .. py:attribute:: start_date
86
+ :type: datetime
87
+
88
+ The simulation's start date.
89
+
90
+ .. py:attribute:: wrf_simulate_seconds
91
+ :type: int
92
+
93
+ The total seconds the simulation will integrate.
94
+
95
+ .. py:attribute:: wrf_log_path
96
+ :type: str
97
+
98
+ Path of the log file the server will read.
54
99
  """
55
100
 
56
101
  def __init__(self, start_date: datetime, wrf_simulate_seconds: int, *args, **kwargs) -> None:
102
+ """
103
+
104
+ :param start_date: The simulation's start date.
105
+ :type start_date: datetime
106
+ :param wrf_simulate_seconds: The total seconds the simulation will integrate.
107
+ :type wrf_simulate_seconds: int
108
+ :param args: Other positional arguments passed to parent class.
109
+ :type args:
110
+ :param kwargs: Other keyword arguments passed to parent class.
111
+ :type kwargs:
112
+ """
57
113
  super().__init__(*args, **kwargs)
58
114
 
59
115
  # record the time the server starts
@@ -72,7 +128,7 @@ class WRFRunServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
72
128
 
73
129
  def server_bind(self):
74
130
  """
75
- Bind address and port.
131
+ Bind and listen on the address and port.
76
132
  """
77
133
  # reuse address and port to prevent the error `Address already in use`
78
134
  self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
@@ -101,7 +157,6 @@ class WRFRunServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
101
157
  class WRFRunServerHandler(socketserver.StreamRequestHandler):
102
158
  """
103
159
  Socket server handler.
104
-
105
160
  """
106
161
  def __init__(self, request, client_address, server: WRFRunServer) -> None:
107
162
  super().__init__(request, client_address, server)
@@ -110,10 +165,12 @@ class WRFRunServerHandler(socketserver.StreamRequestHandler):
110
165
  self.server: WRFRunServer = server
111
166
 
112
167
  def calculate_time_usage(self) -> str:
113
- """Calculate time usage from server start (usually the time to run wrfrun)
168
+ """
169
+ Calculate the duration from the server's start time to the present,
170
+ which represents the time ``wrfrun`` has spent running the NWP model.
114
171
 
115
- Returns:
116
- str: Time usage in `"%H:%M:%S"`
172
+ :return: A time string in ``%H:%M:%S`` format.
173
+ :rtype: str
117
174
  """
118
175
  # get current timestamp
119
176
  current_timestamp = datetime.fromtimestamp(time())
@@ -137,10 +194,10 @@ class WRFRunServerHandler(socketserver.StreamRequestHandler):
137
194
 
138
195
  def calculate_progress(self) -> str:
139
196
  """
140
- Calculate the simulation progress.
197
+ Read the log file and calculate the simulation progress.
141
198
 
142
- :return:
143
- :rtype:
199
+ :return: A JSON string with two keys: ``status`` and ``progress``.
200
+ :rtype: str
144
201
  """
145
202
  start_date, simulate_seconds = self.server.get_wrf_simulate_settings()
146
203
 
@@ -157,7 +214,7 @@ class WRFRunServerHandler(socketserver.StreamRequestHandler):
157
214
  if status == "":
158
215
  status = "*"
159
216
 
160
- return f"{status}: {progress}%"
217
+ return dumps({"status": status, "progress": progress})
161
218
 
162
219
  def handle(self) -> None:
163
220
  """
@@ -186,11 +243,11 @@ class WRFRunServerHandler(socketserver.StreamRequestHandler):
186
243
 
187
244
 
188
245
  def stop_server(socket_ip: str, socket_port: int):
189
- """Try to stop server.
246
+ """
247
+ Stop the socket server.
190
248
 
191
- Args:
192
- socket_ip (str): Server IP.
193
- socket_port (int): Server Port.
249
+ :param socket_ip: Server address.
250
+ :param socket_port: Server port.
194
251
  """
195
252
  try:
196
253
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
wrfrun/data.py CHANGED
@@ -6,12 +6,11 @@ from typing import Union, List, Tuple
6
6
  from pandas import date_range
7
7
  # from seafog import goos_sst_find_data
8
8
 
9
- import cdsapi
10
-
11
9
  from .core.config import WRFRUNConfig
12
10
  from .utils import logger
13
11
 
14
- CDS_CLIENT = cdsapi.Client()
12
+ # lazy initialize
13
+ CDS_CLIENT = None
15
14
 
16
15
 
17
16
  class ERA5CONFIG:
@@ -214,6 +213,8 @@ def find_era5_data(date: Union[List[str], List[datetime]], area: Tuple[int, int,
214
213
  Returns: data path
215
214
 
216
215
  """
216
+ global CDS_CLIENT
217
+
217
218
  # check variables and datasets
218
219
  if not _check_variables_and_datasets(variables, dataset):
219
220
  logger.error(
@@ -281,8 +282,12 @@ def find_era5_data(date: Union[List[str], List[datetime]], area: Tuple[int, int,
281
282
  exit(1)
282
283
 
283
284
  # download data
284
- logger.info(
285
- f"Downloading data to {save_path}, it may take several tens of minutes, please wait...")
285
+ logger.info(f"Downloading data to {save_path}, it may take several tens of minutes, please wait...")
286
+
287
+ if CDS_CLIENT is None:
288
+ import cdsapi
289
+ CDS_CLIENT = cdsapi.Client()
290
+
286
291
  CDS_CLIENT.retrieve(dataset, params_dict, save_path)
287
292
 
288
293
  return save_path
@@ -1 +1,29 @@
1
+ """
2
+ wrfrun.extension
3
+ ################
4
+
5
+ Through extensions, developers can add more functionality to ``wrfrun``.
6
+ ``wrfrun`` now has the following extensions:
7
+
8
+ ========================================= ==========================================
9
+ :doc:`goos_sst </api/extension.goos_sst>` Process NEAR-GOOS SST data.
10
+ :doc:`littler </api/extension.littler>` Process LITTLE_R observation data.
11
+ ========================================= ==========================================
12
+
13
+ Other Submodules
14
+ ****************
15
+
16
+ =================================== ==========================================
17
+ :doc:`utils </api/extension.utils>` Utility methods can be used by extensions.
18
+ =================================== ==========================================
19
+
20
+ .. toctree::
21
+ :maxdepth: 1
22
+ :hidden:
23
+
24
+ goos_sst <extension.goos_sst>
25
+ littler <extension.littler>
26
+ utils <extension.utils>
27
+ """
28
+
1
29
  from .utils import *
@@ -0,0 +1,67 @@
1
+ """
2
+ wrfrun.extension.goos_sst
3
+ #########################
4
+
5
+ This extension can help you create a GRIB file from ERA5 skin temperature (SKT) data and NEAR-GOOS sea surface temperature (SST) data.
6
+
7
+ ================================================== =============================================
8
+ :doc:`goos_sst </api/extension.goos_sst.goos_sst>` Core functionality submodule.
9
+ :doc:`res </api/extension.goos_sst.res>` Resource files provided by this extension.
10
+ :doc:`utils </api/extension.goos_sst.utils>` Utility submodule used by the core submodule.
11
+ ================================================== =============================================
12
+
13
+ Important Note
14
+ **************
15
+
16
+ This extension relies on ``cfgrib`` package to create GRIB file.
17
+ While GRIB write support is experimental in ``cfgrib``,
18
+ this extension may **FAIL TO CREATE GRIB FILE**.
19
+
20
+ How This Extension Works
21
+ ************************
22
+
23
+ This extension provides a method which merges ERA5 reanalysis skin temperature (SKT) data and NEAR-GOOS SST data,
24
+ and write new data to a GRIB file.
25
+
26
+ How To Use This Extension
27
+ *************************
28
+
29
+ Prerequisite
30
+ ============
31
+
32
+ You need to have the following packages installed, because they are not included in ``wrfrun``'s dependency:
33
+
34
+ * cfgrib: Provide the method to create GRIB file.
35
+ * seafog: Provide the method to download and read NEAR-GOOS SST data.
36
+
37
+ And you also have downloaded an ERA5 reanalysis data (GRIB format) which contains SKT data.
38
+
39
+ How To Use
40
+ ==========
41
+
42
+ The code snap below shows you how to use this extension.
43
+
44
+ .. code-block:: Python
45
+ :caption: main.py
46
+
47
+ from wrfrun.extension.goos_sst import merge_era5_goos_sst_grib
48
+
49
+
50
+ if __name__ == '__main__':
51
+ era5_data_path = "data/ear5-reanalysis-data.grib"
52
+ merge_era5_goos_sst_grib(era5_data_path, "data/near-goos-data.grib")
53
+
54
+ Please check :func:`core.merge_era5_goos_sst_grib` for more information.
55
+
56
+ .. toctree::
57
+ :maxdepth: 1
58
+ :hidden:
59
+
60
+ core <extension.goos_sst.core>
61
+ res <extension.goos_sst.res>
62
+ utils <extension.goos_sst.utils>
63
+ """
64
+
65
+ from .core import *
66
+ from .res import *
67
+ from .utils import *