LIVVext 1.0.0__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.
livvext/__init__.py ADDED
@@ -0,0 +1,35 @@
1
+ # coding=utf-8
2
+ # Copyright (c) 2015-2018, UT-BATTELLE, LLC
3
+ # All rights reserved.
4
+ #
5
+ # Redistribution and use in source and binary forms, with or without
6
+ # modification, are permitted provided that the following conditions are met:
7
+ #
8
+ # 1. Redistributions of source code must retain the above copyright notice, this
9
+ # list of conditions and the following disclaimer.
10
+ #
11
+ # 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ # this list of conditions and the following disclaimer in the documentation
13
+ # and/or other materials provided with the distribution.
14
+ #
15
+ # 3. Neither the name of the copyright holder nor the names of its contributors
16
+ # may be used to endorse or promote products derived from this software without
17
+ # specific prior written permission.
18
+ #
19
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20
+ # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
+ # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
+
30
+ """
31
+ Storage for global variables. These are set upon startup in the options module
32
+ """
33
+
34
+ __version_info__ = (1, 0, 0)
35
+ __version__ = ".".join(str(vi) for vi in __version_info__)
@@ -0,0 +1,189 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+ import matplotlib.pyplot as plt
5
+ import numpy as np
6
+ import pandas as pd
7
+ import xarray as xr
8
+ from livvkit import elements as el
9
+ from loguru import logger
10
+
11
+ import livvext.common as lxc
12
+
13
+ DAYS_PER_MONTH = np.array([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])
14
+ IMG_GROUP = "components"
15
+ DESCRIBE_COMPONENTS = """
16
+ Annual cycle of components of SMB from {model}, {dset_a}.
17
+ Sign of component based on its contribution to total.
18
+ """
19
+
20
+
21
+ def main(args, config):
22
+ _files = [lxc.proc_climo_file(config, "climo_remap", mon) for mon in range(1, 13)]
23
+ model_data = xr.open_mfdataset(
24
+ _files,
25
+ combine="nested",
26
+ concat_dim="time",
27
+ )
28
+
29
+ mons = [f"{mon:02d}" for mon in np.arange(0, 12) + 1]
30
+ obs_data = lxc.load_obs(
31
+ config, sea=mons, mode="_monthlyPSR_", single_ds="dset_a", expect_one_time=False
32
+ )
33
+ obs_aavg = {}
34
+ model_aavg = {}
35
+ diffs_aavg = {}
36
+ mask_r = {}
37
+ area_r = {}
38
+
39
+ fig, axes = plt.subplots(1, 2, figsize=(12, 5), sharey=True)
40
+ mons = np.arange(1, 12 + 1)
41
+ obs_data_out = {}
42
+ model_data_out = {}
43
+
44
+ for idx, data_var in enumerate(config["data_vars"]):
45
+ logger.info(f"WORKING ON {data_var['title']}")
46
+ _obs_in = {}
47
+
48
+ aavg_config = data_var.get("aavg", None)
49
+
50
+ if aavg_config is not None:
51
+ _aavg_units = aavg_config["units"]
52
+ _aavg_scale = aavg_config["scale"]
53
+ _do_sum = aavg_config["sum"]
54
+ else:
55
+ _aavg_units = ""
56
+ _aavg_scale = 1.0
57
+ _do_sum = False
58
+
59
+ for rvers in obs_data:
60
+ _obs_in[rvers] = lxc.parse_var(
61
+ data_var[rvers], obs_data[rvers], config["scales"][rvers]
62
+ )
63
+
64
+ try:
65
+ _model_plt = (
66
+ lxc.parse_var(data_var["model"], model_data, config["scales"]["model"])
67
+ / 365
68
+ )
69
+ except KeyError:
70
+ logger.error(f"MODEL DATA NOT FOUND FOR {data_var['model']}")
71
+ continue
72
+
73
+ obs_aavg[data_var["title"]] = {}
74
+ diffs_aavg[data_var["title"]] = {}
75
+ mask_r[data_var["title"]] = {}
76
+ area_r[data_var["title"]] = {}
77
+
78
+ for _vers in ["dset_a"]:
79
+ obs_aavg[data_var["title"]][_vers], mask_r[_vers], area_r[_vers], _ = (
80
+ lxc.area_avg(
81
+ _obs_in[_vers],
82
+ {},
83
+ area_file=config["masks"][_vers].format(
84
+ icesheet=config["icesheet"]
85
+ ),
86
+ area_var="area",
87
+ mask_var="Icemask",
88
+ sum_out=_do_sum,
89
+ )
90
+ )
91
+ model_aavg[data_var["title"]], _, _, _ = lxc.area_avg(
92
+ _model_plt,
93
+ {},
94
+ area_file=config["masks"]["model"].format(icesheet=config["icesheet"]),
95
+ area_var="area",
96
+ mask_var="Icemask",
97
+ sum_out=_do_sum,
98
+ )
99
+ if data_var.get("primary_var", False):
100
+ color = "k"
101
+ lw = 2.0
102
+ else:
103
+ color = f"C{idx}"
104
+ lw = 1.1
105
+
106
+ _obs_plt = (
107
+ obs_aavg[data_var["title"]]["dset_a"]
108
+ * data_var["ac_contrib_sign"]["dset_a"]
109
+ * _aavg_scale
110
+ )
111
+ # if isinstance(_obs_plt, np.ma.masked_array):
112
+ # _obs_plt = _obs_plt.compressed().squeeze()
113
+
114
+ _model_plt = (
115
+ model_aavg[data_var["title"]]
116
+ * data_var["ac_contrib_sign"]["model"]
117
+ * 365
118
+ * _aavg_scale
119
+ )
120
+ obs_data_out[data_var["title"]] = _obs_plt
121
+ model_data_out[data_var["title"]] = _model_plt
122
+
123
+ var_label = f" {data_var['title']}"
124
+ axes[0].plot(mons, _model_plt, label=var_label, color=color, marker=".", lw=lw)
125
+ axes[1].plot(
126
+ mons,
127
+ _obs_plt.squeeze(),
128
+ label=var_label,
129
+ color=color,
130
+ marker=".",
131
+ lw=lw,
132
+ )
133
+ logger.info(f"DONE - WORKING ON {data_var['title']}")
134
+
135
+ obs_data_out["month"] = np.arange(1, 12 + 1)
136
+ model_data_out["month"] = np.arange(1, 12 + 1)
137
+
138
+ obs_data_out = pd.DataFrame(obs_data_out)
139
+ obs_data_out.index = obs_data_out["month"]
140
+
141
+ obs_data_out.to_csv(
142
+ Path(
143
+ args.out,
144
+ f"annual_cycle_{lxc.img_file_prefix(config)}"
145
+ f"{config['dataset_names']['dset_a'].replace(' ', '_').replace('.', '_')}.csv",
146
+ )
147
+ )
148
+ model_data_out = pd.DataFrame(model_data_out)
149
+ model_data_out.index = model_data_out["month"]
150
+ model_data_out.to_csv(
151
+ Path(
152
+ args.out,
153
+ f"annual_cycle_{lxc.img_file_prefix(config)}_"
154
+ f"{config['dataset_names']['model']}.csv",
155
+ )
156
+ )
157
+
158
+ if _aavg_units == "":
159
+ axes[0].set_ylabel(f"[{config['units']}]")
160
+ else:
161
+ axes[0].set_ylabel(f"[{_aavg_units}]")
162
+ for axis in axes:
163
+ axis.grid(visible=True, ls="--", lw=0.5)
164
+
165
+ axis.set_xlabel("Month")
166
+ axis.set_xticks(mons, lxc.MON_NAMES)
167
+ axis.legend(fontsize=8)
168
+
169
+ _ = axes[0].set_title(config["dataset_names"]["model"])
170
+ _ = axes[1].set_title(config["dataset_names"]["dset_a"])
171
+
172
+ plt.tight_layout()
173
+
174
+ img_file = os.path.join(
175
+ args.out, f"{lxc.img_file_prefix(config)}_components_annual_cycle.png"
176
+ )
177
+ fig.savefig(img_file)
178
+ img_link = os.path.join(
179
+ "imgs", os.path.basename(args.out), os.path.basename(img_file)
180
+ )
181
+ img_elem = el.Image(
182
+ "SMB component annual cycles",
183
+ " ".join(DESCRIBE_COMPONENTS.split()).format(**config["dataset_names"]),
184
+ img_link,
185
+ height=args.img_height,
186
+ group=f"{IMG_GROUP}_ANN",
187
+ relative_to="",
188
+ )
189
+ return [img_elem]