spinup.py 15.5 KB
Newer Older
1
# Copyright (c) 2018-2019 ISciences, LLC.
Dan Baston's avatar
Dan Baston committed
2 3 4 5 6 7 8 9 10 11 12 13
# All rights reserved.
#
# WSIM is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

14 15
import itertools

16 17
from . import attributes as attrs

Dan Baston's avatar
Dan Baston committed
18
from .config_base import ConfigBase as Config
19 20
from .commands import *
from .dates import format_yearmon, all_months, get_next_yearmon
21
from .paths import read_vars, date_range, Basis
22

23
from .actions import create_forcing_file, compute_return_periods, composite_anomalies, fit_var
24

Dan Baston's avatar
Dan Baston committed
25

26
def spinup(config, meta_steps):
27
    """
28 29
    Produces the Steps needed to spin up a model from a series
    of observed data files.
30 31
    """
    steps = []
32
    all_fits = meta_steps['all_fits']
33

34 35
    if config.should_run_lsm():
        print("Adding spinup LSM runs")
36

37 38 39
        steps += generate_garbage_state(config)
        steps += compute_climate_norms(config)
        steps += run_lsm_with_monthly_norms(config, years=100)
40

41
        forcing_1mo = Step.make_empty()
42
        for yearmon in config.historical_yearmons():
43
            steps += config.observed_data().prep_steps(yearmon=yearmon)
44
            for step in create_forcing_file(config.workspace(), config.observed_data(), yearmon=yearmon):
45
                forcing_1mo = forcing_1mo.merge(step)
46
        steps += create_tag(name=config.workspace().tag('spinup_1mo_forcing'),
47 48
                            dependencies=forcing_1mo.targets)
        forcing_1mo.replace_targets_with_tag_file(config.workspace().tag('spinup_1mo_forcing'))
49 50
        steps.append(forcing_1mo)

51
        steps += run_lsm_from_final_norm_state(config)
52

53
        for month in all_months:
54
            steps += mean_spinup_state(config, month, list(config.historical_years())[2:])
55

56
        steps += run_lsm_from_mean_spinup_state(config)
57 58 59 60 61 62 63 64
    else:
        results_1mo = Step.make_empty()
        for yearmon in config.historical_yearmons():
            for step in config.result_postprocess_steps(yearmon=yearmon):
                results_1mo = results_1mo.merge(step)
        steps += create_tag(name=config.workspace().tag('spinup_1mo_results'),
                            dependencies=results_1mo.targets)
        results_1mo.replace_targets_with_tag_file(config.workspace().tag('spinup_1mo_results'))
65

66
        steps.append(results_1mo)
67

68
    # Time-integrate the variables
69
    for window in config.integration_windows():
70
        steps += time_integrate_forcing(config, window)
71
        steps += time_integrate_results(config, window)
72

73

74
    # Compute monthly fits (and then anomalies) over the fit period
75
    for param in config.lsm_rp_vars() + config.forcing_rp_vars() + config.state_rp_vars():
76
        for month in all_months:
77
            steps += all_fits.require(fit_var(config, param=param, month=month))
78 79

    # Compute fits for time-integrated parameters
80 81
    for param in {**config.lsm_integrated_vars(), **config.forcing_integrated_vars()}.keys():
        for stat in {**config.lsm_integrated_vars(), **config.forcing_integrated_vars()}[param]:
82
            for window in config.integration_windows():
83
                assert window > 1
84
                for month in all_months:
85
                    steps += all_fits.require(fit_var(config, param=param, stat=stat, month=month, window=window))
86

87
    # Steps for anomalies and composite anomalies
88
    for window in [1] + config.integration_windows():
89
        for yearmon in config.historical_yearmons()[window-1:]:
90
            steps += compute_return_periods(config.workspace(),
91
                                            result_vars=config.lsm_rp_vars() if window == 1 else config.lsm_integrated_var_names(),
92
                                            forcing_vars=config.forcing_rp_vars() if window == 1 else config.forcing_integrated_var_names(),
93
                                            state_vars=config.state_rp_vars() if window==1 else None,
94 95
                                            yearmon=yearmon,
                                            window=window)
96

97 98 99
            steps += composite_anomalies(config.workspace(),
                                         yearmon=yearmon,
                                         window=window)
100 101 102 103

    # Fit distribution of composite anomalies
    for window in [1] + config.integration_windows():
        steps += fit_composite_anomalies(config, window=window)
104

105
    return steps
106

Dan Baston's avatar
Dan Baston committed
107

108 109 110 111 112
def generate_garbage_state(config):
    """
    Generate a "garbage" initial state with detention variables set to zero
    and soil moisture at 30% of capacity
    """
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    return [
        wsim_merge(
            inputs=[read_vars(config.static_data().wc().file,
                              config.static_data().wc().var + "@[email protected][0.3*x+1e-5]->Ws",
                              config.static_data().wc().var + "@[0]->Dr",
                              config.static_data().wc().var + "@[0]->Ds",
                              config.static_data().wc().var + "@[0]->Snowpack",
                              config.static_data().wc().var + "@[0]->snowmelt_month")],
            attrs=[
                "yearmon=000001",
                "Ws:units=mm",
                "Dr:units=mm",
                "Ds:units=mm",
                "Snowpack:units=mm"
            ],
            output=config.workspace().initial_state()
        )
    ]
131

Dan Baston's avatar
Dan Baston committed
132 133

def compute_climate_norms(config: Config) -> List[Step]:
134 135 136 137 138 139 140 141 142
    """
    Read forcing data for the full historical range and generate a set of
    twelve "monthly norm" forcing files.
    """
    steps = []

    for month in all_months:
        historical_yearmons = [format_yearmon(year, month) for year in config.historical_years()]

143 144
        steps.append(
            wsim_integrate(
Dan Baston's avatar
Dan Baston committed
145 146
                inputs=[config.observed_data().precip_monthly(yearmon=yearmon).read_as('Pr')
                        for yearmon in historical_yearmons],
147 148
                stats=['ave'],
                keepvarnames=True,
149
                output=config.workspace().climate_norm_forcing(month=month, temporary=True)
150 151
            ).merge(
            wsim_integrate(
Dan Baston's avatar
Dan Baston committed
152 153
                inputs=[config.observed_data().temp_monthly(yearmon=yearmon).read_as('T')
                        for yearmon in historical_yearmons],
154 155
                stats=['ave'],
                keepvarnames=True,
156
                output=config.workspace().climate_norm_forcing(month=month, temporary=True)
157 158
            )).merge(
            wsim_integrate(
Dan Baston's avatar
Dan Baston committed
159 160
                inputs=[config.observed_data().p_wetdays(yearmon=yearmon).read_as('pWetDays')
                        for yearmon in historical_yearmons],
161 162
                stats=['ave'],
                keepvarnames=True,
163 164 165 166 167
                output=config.workspace().climate_norm_forcing(month=month, temporary=True)
            )).merge(
            move(
                config.workspace().climate_norm_forcing(month=month, temporary=True),
                config.workspace().climate_norm_forcing(month=month, temporary=False)
168 169
            ))
        )
170 171

    return steps
172

Dan Baston's avatar
Dan Baston committed
173 174

def run_lsm_with_monthly_norms(config: Config, *, years: int) -> List[Step]:
175 176 177 178 179
    """
    Run the LSM from the garbage initial state using monthly norm forcing
    for 100 years, discarding the results generated in the process.
    Store only the final state.
    """
180 181 182 183 184 185 186
    return [
        wsim_lsm(
            state=config.workspace().initial_state(),
            forcing=[config.workspace().climate_norm_forcing(month=month) for month in all_months],
            elevation=config.static_data().elevation(),
            flowdir=config.static_data().flowdir(),
            wc=config.static_data().wc(),
187
            results=None,
188 189 190 191
            next_state=config.workspace().final_state_norms(),
            loop=years
        )
    ]
192

Dan Baston's avatar
Dan Baston committed
193 194

def run_lsm_from_final_norm_state(config: Config) -> List[Step]:
195 196 197 198 199
    """
    Run the LSM over the entire historical period, and retain the state files
    for each iteration. Discard the results.
    """

200 201
    # Set the yearmon in final state from climate norms run to be the first
    # forcing date in our historical record
Dan Baston's avatar
Dan Baston committed
202
    initial_yearmon = config.historical_yearmons()[0]
203 204 205 206 207 208 209 210 211 212 213 214 215 216

    make_initial_state = Step(
        targets=config.workspace().spinup_state(yearmon=initial_yearmon),
        dependencies=config.workspace().final_state_norms(),
        commands=[
            [
                'ncatted',
                '-a', 'yearmon,global,m,c,"{}"'.format(initial_yearmon),
                config.workspace().final_state_norms(),
                config.workspace().spinup_state(yearmon=initial_yearmon)
            ]
        ]
    )

217 218 219
    # Making each iteration an individual target is in some ways cleaner and would
    # allow restarting in case of failure. But the runtime becomes dominated by the
    # R startup and I/O, and takes about 5 seconds / iteration instead of 1 second /iteration.
220
    run_lsm = wsim_lsm(
221
        forcing=[config.workspace().forcing(yearmon=date_range(config.historical_yearmons()), window=1)],
222 223 224 225
        state=config.workspace().spinup_state(yearmon=initial_yearmon),
        elevation=config.static_data().elevation(),
        flowdir=config.static_data().flowdir(),
        wc=config.static_data().wc(),
226
        results=None,
227
        next_state=config.workspace().spinup_state_pattern()
Dan Baston's avatar
Dan Baston committed
228
    ).replace_targets_with_tag_file(config.workspace().tag('spinup_from_climate_norm_final_state'))
229 230 231 232 233

    return [
        make_initial_state,
        run_lsm
    ]
234

Dan Baston's avatar
Dan Baston committed
235 236

def mean_spinup_state(config: Config, month: int, years: Iterable[int]) -> List[Step]:
237 238 239 240 241
    """
    Average the values from spinup states for "month" over "years"
    """
    spinup_states = [config.workspace().spinup_state(yearmon=format_yearmon(year, month)) for year in years]

242 243 244 245 246 247
    return [
        wsim_integrate(
            inputs=spinup_states,
            stats=['ave'],
            output=config.workspace().spinup_mean_state(month=month),
            keepvarnames=True
Dan Baston's avatar
Dan Baston committed
248
        ).replace_dependencies(config.workspace().tag('spinup_from_climate_norm_final_state'))
249
    ]
250

Dan Baston's avatar
Dan Baston committed
251 252

def run_lsm_from_mean_spinup_state(config: Config) -> List[Step]:
253 254 255 256 257
    """
    Run the model for the entire historical period, retaining results and states
    """
    first_timestep = config.historical_yearmons()[0]
    first_month = int(first_timestep[4:])
Dan Baston's avatar
Dan Baston committed
258 259
    postprocess_steps = list(itertools.chain(*[config.result_postprocess_steps(yearmon=yearmon)
                                               for yearmon in config.historical_yearmons()]))
260 261 262 263 264 265 266 267 268 269 270
    make_initial_state = Step(
        comment="Create initial state file",
        targets=config.workspace().state(yearmon=first_timestep),
        dependencies=config.workspace().spinup_mean_state(month=first_month),
        commands=[
            [
                'ncatted',
                '-a'
                'yearmon,global,c,c,"{}"'.format(first_timestep),
                config.workspace().spinup_mean_state(month=first_month),
                config.workspace().state(yearmon=first_timestep)
271
            ]
272 273 274 275
        ]
    )

    run_lsm = wsim_lsm(
Dan Baston's avatar
Dan Baston committed
276
        comment="LSM run from mean spinup state",
277
        forcing=[config.workspace().forcing(yearmon=date_range(config.historical_yearmons()), window=1)],
278 279 280 281 282 283
        state=config.workspace().state(yearmon=first_timestep),
        elevation=config.static_data().elevation(),
        flowdir=config.static_data().flowdir(),
        wc=config.static_data().wc(),
        results=config.workspace().results(window=1, yearmon='%T'),
        next_state=config.workspace().state(yearmon='%T')
284
    ).merge(*itertools.chain(*postprocess_steps))
285

Dan Baston's avatar
Dan Baston committed
286
    tag_steps = create_tag(name=config.workspace().tag('spinup_1mo_results'),
Dan Baston's avatar
Dan Baston committed
287 288 289 290
                           dependencies=[config.workspace().results(window=1, yearmon=y)
                                         for y in config.historical_yearmons()] +
                                        [config.workspace().state(yearmon=get_next_yearmon(y))
                                         for y in config.historical_yearmons()])
Dan Baston's avatar
Dan Baston committed
291
    run_lsm.replace_targets_with_tag_file(config.workspace().tag('spinup_1mo_results'))
292 293 294

    return [
        make_initial_state,
295 296
        run_lsm,
        *tag_steps
297 298
    ]

Dan Baston's avatar
Dan Baston committed
299

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
def time_integrate_forcing(config:Config, window: int, *, basis: Optional[Basis]=None) -> List[Step]:
    """
    Integrate forcing variables over the given time window
    """
    yearmons_in = config.historical_yearmons()
    yearmons_out = yearmons_in[window-1:]

    integrate = wsim_integrate(
        inputs= [read_vars(config.workspace().forcing(window=1, yearmon=date_range(yearmons_in)),
        *config.forcing_integrated_vars(basis=basis).keys())
        ],
        window=window,
        stats=[stat + '::' + ','.join(varname) for stat, varname in config.forcing_integrated_stats(basis=basis).items()],
        attrs=[attrs.integration_window(var='*', months=window)],
        output=config.workspace().forcing(yearmon=date_range(yearmons_out),
                                          window=window)
    )

    tag_name = config.workspace().tag('{}spinup_{}mo_forcing'.format((basis.value + '_' if basis else ''), window))

    tag_steps = create_tag(name=tag_name, dependencies=integrate.targets)

    integrate.replace_targets_with_tag_file(tag_name)
    integrate.replace_dependencies(
        config.workspace().tag('{}spinup_1mo_forcing'.format((basis.value + '_') if basis else '')))

    return [
327 328
        integrate,
        *tag_steps
329 330 331
    ]


332
def time_integrate_results(config: Config, window: int, *, basis: Optional[Basis]=None) -> List[Step]:
333
    """
334
    Integrate specified LSM results (and any included forcing variables) over the given time window
335
    """
336
    yearmons_in = config.historical_yearmons()
337
    yearmons_out = yearmons_in[window-1:]
338

339
    integrate = wsim_integrate(
340
        inputs=[read_vars(config.workspace().results(window=1, yearmon=date_range(yearmons_in), basis=basis),
341
                         *config.lsm_integrated_vars(basis=basis).keys())
342
                         ],
343
        window=window,
344
        stats=[stat + '::' + ','.join(varname) for stat, varname in config.lsm_integrated_stats(basis=basis).items()],
345
        attrs=[attrs.integration_window(var='*', months=window)],
346
        output=config.workspace().results(yearmon=date_range(yearmons_out),
347 348
                                          window=window,
                                          basis=basis)
349 350
    )

351
    tag_name = config.workspace().tag('{}spinup_{}mo_results'.format((basis.value + '_' if basis else ''), window))
352 353 354 355

    tag_steps = create_tag(name=tag_name, dependencies=integrate.targets)

    integrate.replace_targets_with_tag_file(tag_name)
Dan Baston's avatar
Dan Baston committed
356
    integrate.replace_dependencies(
357
        config.workspace().tag('{}spinup_1mo_results'.format((basis.value + '_') if basis else '')))
358

359
    return [
360 361
        integrate,
        *tag_steps
362
    ]
363

Dan Baston's avatar
Dan Baston committed
364 365

def fit_composite_anomalies(config: Config, *, window: int) -> List[Step]:
366 367 368 369 370
    fit_yearmons = config.result_fit_yearmons()[window-1:]

    return [
        wsim_fit(
            distribution=config.distribution,
371
            inputs=[
Dan Baston's avatar
Dan Baston committed
372 373 374
                read_vars(config.workspace().composite_anomaly(yearmon=date_range(fit_yearmons[0], fit_yearmons[-1]),
                                                               window=window),
                          indicator)
375
            ],
376 377
            output=config.workspace().fit_composite_anomalies(indicator=indicator, window=window),
            window=window
378
        )
379
        for indicator in ('surplus', 'deficit')
380
    ]