Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.96 KB | None | 0 0
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "markdown",
  5. "metadata": {},
  6. "source": [
  7. "# Demonstration of generating domain and state files for MetSim\n",
  8. "\n",
  9. "The first cell is a simple setup column that gets the libraries that we need loaded. Then we grab all of the data that we're going to use and compute what will be the spatial extent of the data. We also set some paths that we will write our files out to."
  10. ]
  11. },
  12. {
  13. "cell_type": "code",
  14. "execution_count": null,
  15. "metadata": {},
  16. "outputs": [],
  17. "source": [
  18. "%pylab inline\n",
  19. "import os\n",
  20. "import sys\n",
  21. "import glob\n",
  22. "import numpy as np\n",
  23. "import xarray as xr\n",
  24. "import pandas as pd\n",
  25. "import metsim\n",
  26. "\n",
  27. "# Path to your ascii files\n",
  28. "data_dir = 'your/path/here'\n",
  29. "\n",
  30. "# Where to save the files\n",
  31. "OUT_DOMAIN = 'your/path/here'\n",
  32. "OUT_STATE = 'your/path/here'\n",
  33. "\n",
  34. "# List of all of the ascii files\n",
  35. "data_files = os.listdir(data_dir)\n",
  36. "\n",
  37. "# Unique listing of latitudes and longitudes to include\n",
  38. "# This is dependent on your files having naming scheme FILENAME_LAT_LON\n",
  39. "# You may have to adjust the part inside of the `float` call as necessary\n",
  40. "lats = np.unique([float(f.split('_')[1]) for f in data_files])\n",
  41. "lons = np.unique([float(f.split('_')[2]) for f in data_files])\n",
  42. "\n",
  43. "# Grid cells that you actually have data for\n",
  44. "# Again, you may have to adjust this if your file naming scheme is different\n",
  45. "mask_locs = list(map(lambda l: [float(ll) for ll in l], [x.split('_')[1:] for x in data_files]))"
  46. ]
  47. },
  48. {
  49. "cell_type": "markdown",
  50. "metadata": {},
  51. "source": [
  52. "## Generation of the domain dataset\n",
  53. "\n",
  54. "The domain dataset has three variables that represent the spatial extent of the run. The variables we will generate are:\n",
  55. "\n",
  56. "* Mask: A simple way to tell if a grid-cell should be processed. Values greater than 0 will be run.\n",
  57. "* Elevation: The elevation of the grid cell in meters.\n"
  58. ]
  59. },
  60. {
  61. "cell_type": "code",
  62. "execution_count": null,
  63. "metadata": {},
  64. "outputs": [],
  65. "source": [
  66. "coords = {'lat': lats, 'lon': lons}\n",
  67. "shape = (len(lats), len(lons))\n",
  68. "dims = ('lat', 'lon')\n",
  69. "domain = xr.Dataset(coords=coords)\n",
  70. "domain['elev'] = xr.DataArray(data=np.full(shape, np.nan), coords=coords, dims=dims)\n",
  71. "domain['mask'] = xr.DataArray(data=np.full(shape, np.nan), coords=coords, dims=dims)\n",
  72. "\n",
  73. "# Add the data\n",
  74. "for loc in mask_locs:\n",
  75. " loc_dict = {'lat': loc[0], 'lon': loc[1]}\n",
  76. " domain['elev'].loc[loc_dict] = 1 # your elevation here\n",
  77. " domain['mask'].loc[loc_dict] = 1\n",
  78. "\n",
  79. "print(domain)\n",
  80. "domain.to_netcdf(OUT_DOMAIN)"
  81. ]
  82. },
  83. {
  84. "cell_type": "markdown",
  85. "metadata": {},
  86. "source": [
  87. "## Generation of the state dataset\n",
  88. "\n",
  89. "The state dataset requires the three variables that represent the spatial extent and a 90 day history.\n",
  90. "\n",
  91. "There are three required variables. Each of them should be given as a 90 day record prior to the start date. They are:\n",
  92. "\n",
  93. " * Daily minimum temperature\n",
  94. " * Daily maximum temperature\n",
  95. " * Daily precipitation\n",
  96. "\n",
  97. "In newer revisions of MetSim the SWE variable can be omitted from the state, but we will add it regardless.\n",
  98. "\n",
  99. "This just fills the state with random information. You should **not** do this, but will have to choose how to get this information yourself.\n"
  100. ]
  101. },
  102. {
  103. "cell_type": "code",
  104. "execution_count": null,
  105. "metadata": {},
  106. "outputs": [],
  107. "source": [
  108. "# Calculate the dates required\n",
  109. "metsim_start = pd.datetime(1949, 1, 1)\n",
  110. "state_start = metsim_start - pd.Timedelta('90 days')\n",
  111. "state_stop = metsim_start - pd.Timedelta('1 days')\n",
  112. "dates = pd.date_range(state_start, state_stop)\n",
  113. "\n",
  114. "# Required variables that have time\n",
  115. "varnames = ['prec', 't_min', 't_max']\n",
  116. "coords = {'time': dates, 'lon': lons, 'lat': lats}\n",
  117. "shape = (len(dates), len(domain['lat']), len(domain['lon']))\n",
  118. "dims = ('time', 'lat', 'lon')\n",
  119. "\n",
  120. "# Initialize the state dataset\n",
  121. "state = xr.Dataset(coords=coords)\n",
  122. "for var in varnames: \n",
  123. " state[var] = xr.DataArray(data=np.full(shape, np.nan), coords=coords, dims=dims, name=var)\n",
  124. "\n",
  125. "# Now add SWE\n",
  126. "shape = (len(domain['lat']), len(domain['lon']))\n",
  127. "coords = {'lon': lons, 'lat': lats}\n",
  128. "dims = ('lat', 'lon')\n",
  129. "state['swe'] = xr.DataArray(data=np.full(shape, np.nan), coords=coords, dims=dims, name='swe')\n",
  130. "\n",
  131. "# Fill in the data\n",
  132. "for loc in mask_locs:\n",
  133. " loc_dict = {'lat': loc[0], 'lon': loc[1]}\n",
  134. " state['t_min'].loc[loc_dict] = np.random.random(90)\n",
  135. " state['t_max'].loc[loc_dict] = np.random.random(90)\n",
  136. " state['prec'].loc[loc_dict] = np.random.random(90)\n",
  137. " state['swe'].loc[loc_dict] = 0.0\n",
  138. "\n",
  139. "print(state)\n",
  140. "state.to_netcdf(OUT_STATE)"
  141. ]
  142. }
  143. ],
  144. "metadata": {
  145. "kernelspec": {
  146. "display_name": "Python 3",
  147. "language": "python",
  148. "name": "python3"
  149. },
  150. "language_info": {
  151. "codemirror_mode": {
  152. "name": "ipython",
  153. "version": 3
  154. },
  155. "file_extension": ".py",
  156. "mimetype": "text/x-python",
  157. "name": "python",
  158. "nbconvert_exporter": "python",
  159. "pygments_lexer": "ipython3",
  160. "version": "3.6.8"
  161. },
  162. "latex_envs": {
  163. "LaTeX_envs_menu_present": true,
  164. "autocomplete": false,
  165. "bibliofile": "biblio.bib",
  166. "cite_by": "apalike",
  167. "current_citInitial": 1,
  168. "eqLabelWithNumbers": true,
  169. "eqNumInitial": 1,
  170. "hotkeys": {
  171. "equation": "Ctrl-E",
  172. "itemize": "Ctrl-I"
  173. },
  174. "labels_anchors": false,
  175. "latex_user_defs": false,
  176. "report_style_numbering": false,
  177. "user_envs_cfg": false
  178. }
  179. },
  180. "nbformat": 4,
  181. "nbformat_minor": 2
  182. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement