test_integration_3inversions.py 6.38 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import os
import time
import shutil


import pytest

from pycif.utils.classes.setup import Setup
from pycif.utils.datastores.dump import read_datastore
from pycif.utils.yml import ordered_dump
from pycif.utils.path import init_dir


@pytest.mark.dummy
@pytest.mark.article
@pytest.mark.parametrize(
    "settings", [
        {"mode": "4dvar", "minimizer": "M1QN3"},
        {"mode": "4dvar", "minimizer": "congrad"},
        {"mode": "analytical"},
        {"mode": "ensrf"}]
)
def test_integration_inversion(dummy_config_inversion, settings):
    """
    Integration test that runs the dummy_forward model.
    """

    tmpdir, config, tag = dummy_config_inversion
    
    # Changing mode
    nsimmax = 5
    if config["datavect"]["components"]["fluxes"]\
            ["parameters"]["CH4"]["hresol"] == "hpixels":
        nsimmax = 10
    
    elif config["datavect"]["components"]["fluxes"]\
            ["parameters"]["CH4"]["hresol"] == "global" \
            and settings.get("minimizer", "congrad"):
        nsimmax = 1
        
    if settings["mode"] == "4dvar":
        mode = {
            "plugin": {"name": "4dvar", "version": "std"},
            "minimizer": {
                "plugin": {"name": settings["minimizer"], "version": "std"},
                "simulator": {
                    "plugin": {"name": "gausscost", "version": "std"},
                    "reload_from_previous": True
                },
                "maxiter": nsimmax,
                "nsim": nsimmax,
                "epsg": 0.02,
                "df1": 0.01
            },
            "save_out_netcdf": True
        }
        prior_dir = os.path.join(tmpdir, "obsoperator/fwd_-001/obsvect")
        posterior_dir = os.path.join(tmpdir, "obsoperator/fwd_-002/obsvect")
    
    elif settings["mode"] == "analytical":
        mode = {"plugin": {"name": "analytic", "version": "std",
                           "dump_nc_base_control": True}}
        prior_dir = os.path.join(tmpdir, "obsvect_prior")
        posterior_dir = os.path.join(tmpdir, "obsvect_posterior")
        return
    
    elif settings["mode"] == "ensrf":
        nsimmax *= 2
        mode = {"plugin": {"name": "EnSRF", "version": "std"},
                "nsample": nsimmax}
        prior_dir = os.path.join(tmpdir, "obsvect_prior")
        posterior_dir = os.path.join(tmpdir, "obsvect_posterior")
      
    config["mode"] = mode
    config["platform"] = {"plugin": {"name": "LSCE", "version": "obelix"}}
    
    # Removing MCF to make computation quicker
    del config["model"]["chemistry"]["acspecies"]["MCF"]
    del config["datavect"]["components"]["fluxes"]["parameters"]["MCF"]
    del config["datavect"]["components"]["concs"]["parameters"]["MCF"]
    
    # Dump yml config file
    dummy_config_file = os.path.join(tmpdir, "dummy_config.yml")
    with open(dummy_config_file, "w") as outfile:
        ordered_dump(outfile, config)
    
    # Run as job
    setup = Setup.yaml_to_setup(dummy_config_file)
    setup.todo_init = ["platform"]
    setup = Setup.load_config(setup)
    platform = setup.platform

    job_file = os.path.join(tmpdir,
                            "job_pycif_{}".format(tmpdir[-5:]))

    exe = "{} -m pycif {}".format(platform.python, dummy_config_file)

    job_id = platform.submit_job(
        exe,
        job_file
    )

    # Wait for the end of the execution
    while not platform.check_jobs([job_id]):
        time.sleep(platform.sleep_time)

    # Get results and check that posterior closer to prior
    components = os.listdir(prior_dir)
    for comp in components:
        comp_dir_prior = os.path.join(prior_dir, comp)
        comp_dir_post = os.path.join(posterior_dir, comp)
        parameters = os.listdir(comp_dir_prior)
        for param in parameters:
            param_dir = os.path.join(comp_dir_prior, param)
            monitor_prior = \
                read_datastore(os.path.join(param_dir, "monitor.nc"))

            param_dir = os.path.join(comp_dir_post, param)
            monitor_post = \
                read_datastore(os.path.join(param_dir, "monitor.nc"))

            assert (
                    (monitor_prior.loc[:, "obs"]
                     - monitor_prior.loc[:, "sim"]).pow(2).sum()
                    - (monitor_post.loc[:, "obs"]
                       - monitor_post.loc[:, "sim"]).pow(2).sum()
                    > 0
            )

    # Dump configuration into CIF examples
    tag += "_{}_{}".format(settings["mode"],
                           "" if settings["mode"] != "4dvar"
                           else settings["minimizer"])

    current_dir = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
    example_dir = \
        os.path.abspath(os.path.join(current_dir, "../../examples/dummy/"))

    dummy_config_file = \
        os.path.join(example_dir, "config_4dvar_{}.yml".format(tag))
    with open(dummy_config_file, "w") as outfile:
        ordered_dump(outfile, config)
    
    # Compute the value of the cost function for a varying number of simulation
    if os.path.isdir("{}/varying_cost/".format(tmpdir)):
        shutil.rmtree("{}/varying_cost/".format(tmpdir))
    init_dir("{}/varying_cost/".format(tmpdir))

    # Loop with different number of simulations
    for nsim in range(10, nsimmax + 1, 10):
        file_config = "{}/dummy_config.yml".format(tmpdir)
        inv_setup = Setup.from_yaml(file_config)

        obs_root = "obsvect_posterior"
        if settings.get("minimizer", None) == "congrad":
            obs_root = "obsoperator/fwd_-002/obsvect"
            inv_setup["mode"]["minimizer"]["maxiter"] = int(nsim / 2)
            if os.path.isdir("{}/obsoperator/fwd_-002".format(tmpdir)):
                shutil.rmtree("{}/obsoperator/fwd_-002".format(tmpdir))
        elif settings.get("minimizer", None) == "M1QN3":
            obs_root = "obsoperator/fwd_-002/obsvect"
            inv_setup["mode"]["minimizer"]["maxiter"] = int(nsim / 2)
            inv_setup["mode"]["minimizer"]["nsim"] = int(nsim / 2)
            if os.path.isdir("{}/obsoperator/fwd_-002".format(tmpdir)):
                shutil.rmtree("{}/obsoperator/fwd_-002".format(tmpdir))
        elif settings["mode"] == "EnSRF":
            inv_setup["mode"]["nsample"] = nsim
    
        inv_setup = Setup.from_dict(inv_setup, convert_none=True)
        inv_setup = inv_setup.load_config(inv_setup)
        result = inv_setup.mode.execute()
    
        shutil.copytree("{}/{}".format(tmpdir, obs_root),
                        "{}/varying_cost/{:04d}".format(tmpdir, nsim))