core.py 60.2 KB
Newer Older
Sebastian Heimann's avatar
Sebastian Heimann committed
1001
1002
1003
1004
1005
1006
1007
class Config(HasPaths):
    rundir_template = Path.T()
    dataset_config = DatasetConfig.T()
    target_configs = List.T(TargetConfig.T())
    problem_config = ProblemConfig.T()
    analyser_config = AnalyserConfig.T(default=AnalyserConfig.D())
    solver_config = SolverConfig.T(default=SolverConfig.D())
Sebastian Heimann's avatar
Sebastian Heimann committed
1008
    engine_config = EngineConfig.T(default=EngineConfig.D())
Sebastian Heimann's avatar
Sebastian Heimann committed
1009
1010
1011
1012

    def __init__(self, *args, **kwargs):
        HasPaths.__init__(self, *args, **kwargs)

Sebastian Heimann's avatar
Sebastian Heimann committed
1013
1014
1015
    def get_event_names(self):
        return self.dataset_config.get_event_names()

1016
1017
    def get_dataset(self, event_name):
        return self.dataset_config.get_dataset(event_name)
Sebastian Heimann's avatar
Sebastian Heimann committed
1018
1019

    def get_targets(self, event):
1020
        ds = self.get_dataset(event.name)
Sebastian Heimann's avatar
Sebastian Heimann committed
1021
1022
1023
1024
1025
1026
1027
1028

        targets = []
        for igroup, target_config in enumerate(self.target_configs):
            targets.extend(target_config.get_targets(
                ds, event, 'group_%i' % igroup))

        return targets

1029
1030
1031
1032
1033
1034
1035
1036
    def setup_modelling_environment(self, problem):
        problem.set_engine(self.engine_config.get_engine())
        ds = self.get_dataset(problem.base_source.name)
        synt = ds.synthetic_test
        if synt:
            synt.set_problem(problem)
            problem.base_source = problem.unpack(synt.get_x())

Sebastian Heimann's avatar
Sebastian Heimann committed
1037
1038
    def get_problem(self, event):
        targets = self.get_targets(event)
Sebastian Heimann's avatar
Sebastian Heimann committed
1039
        problem = self.problem_config.get_problem(event, targets)
1040
        self.setup_modelling_environment(problem)
Sebastian Heimann's avatar
Sebastian Heimann committed
1041
        return problem
Sebastian Heimann's avatar
Sebastian Heimann committed
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085


def sarr(a):
    return ' '.join('%15g' % x for x in a)


def load_problem_info_and_data(dirname, subset=None):
    problem = load_problem_info(dirname)
    xs, misfits = load_problem_data(xjoin(dirname, subset), problem)
    return problem, xs, misfits


def load_problem_info(dirname):
    fn = op.join(dirname, 'problem.yaml')
    return guts.load(filename=fn)


def load_problem_data(dirname, problem):
    fn = op.join(dirname, 'x')
    with open(fn, 'r') as f:
        nmodels = os.fstat(f.fileno()).st_size / (problem.nparameters * 8)
        data = num.fromfile(
            f, dtype='<f8',
            count=nmodels*problem.nparameters).astype(num.float)

    nmodels = data.size/problem.nparameters
    xs = data.reshape((nmodels, problem.nparameters))

    fn = op.join(dirname, 'misfits')
    with open(fn, 'r') as f:
        data = num.fromfile(
            f, dtype='<f8', count=nmodels*problem.ntargets*2).astype(num.float)

    data = data.reshape((nmodels, problem.ntargets*2))

    combi = num.empty_like(data)
    combi[:, 0::2] = data[:, :problem.ntargets]
    combi[:, 1::2] = data[:, problem.ntargets:]

    misfits = combi.reshape((nmodels, problem.ntargets, 2))

    return xs, misfits


Sebastian Heimann's avatar
Sebastian Heimann committed
1086
1087
1088
1089
def get_mean_x(xs):
    return num.mean(xs, axis=0)


1090
1091
1092
1093
1094
def get_mean_x_and_gm(problem, xs, misfits):
    gms = problem.global_misfits(misfits)
    return num.mean(xs, axis=0), num.mean(gms)


Sebastian Heimann's avatar
Sebastian Heimann committed
1095
1096
1097
1098
1099
1100
def get_best_x(problem, xs, misfits):
    gms = problem.global_misfits(misfits)
    ibest = num.argmin(gms)
    return xs[ibest, :]


1101
1102
1103
1104
1105
1106
def get_best_x_and_gm(problem, xs, misfits):
    gms = problem.global_misfits(misfits)
    ibest = num.argmin(gms)
    return xs[ibest, :], gms[ibest]


Sebastian Heimann's avatar
Sebastian Heimann committed
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
def get_mean_source(problem, xs):
    x_mean = get_mean_x(xs)
    source = problem.unpack(x_mean)
    return source


def get_best_source(problem, xs, misfits):
    x_best = get_best_x(problem, xs, misfits)
    source = problem.unpack(x_best)
    return source


Sebastian Heimann's avatar
Sebastian Heimann committed
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
def mean_latlondist(lats, lons):
    if len(lats) == 0:
        return 0., 0., 1000.
    else:
        ns, es = od.latlon_to_ne_numpy(lats[0], lons[0], lats, lons)
        n, e = num.mean(ns), num.mean(es)
        dists = num.sqrt((ns-n)**2 + (es-e)**2)
        lat, lon = od.ne_to_latlon(lats[0], lons[0], n, e)
        return float(lat), float(lon), float(num.max(dists))


def stations_mean_latlondist(stations):
    lats = num.array([s.lat for s in stations])
    lons = num.array([s.lon for s in stations])
    return mean_latlondist(lats, lons)


def read_config(path):
    config = load(filename=path)
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1138
1139
1140
    if not isinstance(config, Config):
        raise GrondError('invalid Grond configuration in file "%s"' % path)

Sebastian Heimann's avatar
Sebastian Heimann committed
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
    config.set_basepath(op.dirname(path) or '.')
    return config


def analyse(problem, niter=1000, show_progress=False):
    if niter == 0:
        return

    wtargets = []
    for target in problem.targets:
        wtarget = copy.copy(target)
        wtarget.flip_norm = True
        wtarget.weight = 1.0
        wtargets.append(wtarget)

1156
    groups, ngroups = problem.get_group_mask()
1157

Sebastian Heimann's avatar
Sebastian Heimann committed
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
    wproblem = problem.copy()
    wproblem.targets = wtargets

    xbounds = num.array(wproblem.bounds(), dtype=num.float)
    npar = xbounds.shape[0]

    mss = num.zeros((niter, problem.ntargets))
    rstate = num.random.RandomState(123)

    if show_progress:
        pbar = util.progressbar('analysing problem', niter)

    for iiter in xrange(niter):
        while True:
            x = []
            for i in xrange(npar):
                v = rstate.uniform(xbounds[i, 0], xbounds[i, 1])
                x.append(v)

            try:
                x = wproblem.preconstrain(x)
                break

            except Forbidden:
                pass

        _, ms = wproblem.evaluate(x)
        mss[iiter, :] = ms

        if show_progress:
            pbar.update(iiter)

    if show_progress:
        pbar.finish()

    mean_ms = num.mean(mss, axis=0)

    weights = 1.0 / mean_ms
1196
1197
1198
1199
    for igroup in xrange(ngroups):
        weights[groups == igroup] /= (
            num.nansum(weights[groups == igroup]) /
            num.nansum(num.isfinite(weights[groups == igroup])))
Sebastian Heimann's avatar
Sebastian Heimann committed
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211

    for weight, target in zip(weights, problem.targets):
        target.analysis_result = TargetAnalysisResult(
            balancing_weight=float(weight))


def solve(problem,
          rundir=None,
          niter_uniform=1000,
          niter_transition=1000,
          niter_explorative=10000,
          niter_non_explorative=0,
1212
          scatter_scale_transition=2.0,
1213
          scatter_scale=1.0,
Sebastian Heimann's avatar
Sebastian Heimann committed
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
          xs_inject=None,
          sampler_distribution='multivariate_normal',
          status=()):

    xbounds = num.array(problem.bounds(), dtype=num.float)
    npar = xbounds.shape[0]

    nlinks_cap = 8 * npar + 1
    chains_m = num.zeros((1 + problem.nbootstrap, nlinks_cap), num.float)
    chains_i = num.zeros((1 + problem.nbootstrap, nlinks_cap), num.int)
    nlinks = 0
Sebastian Heimann's avatar
Sebastian Heimann committed
1225
    mbx = None
Sebastian Heimann's avatar
Sebastian Heimann committed
1226
1227
1228
1229
1230
1231

    if xs_inject is not None and xs_inject.size != 0:
        niter_inject = xs_inject.shape[0]
    else:
        niter_inject = 0

1232
    niter = niter_inject + niter_uniform + niter_transition + \
1233
        niter_explorative + niter_non_explorative
Sebastian Heimann's avatar
Sebastian Heimann committed
1234
1235

    iiter = 0
Sebastian Heimann's avatar
Sebastian Heimann committed
1236
1237
    sbx = None
    mxs = None
Sebastian Heimann's avatar
Sebastian Heimann committed
1238
1239
1240
1241
    covs = None
    xhist = num.zeros((niter, npar))
    isbad_mask = None
    accept_sum = num.zeros(1 + problem.nbootstrap, dtype=num.int)
1242
    accept_hist = num.zeros(niter, dtype=num.int)
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1243
    pnames = [p.name for p in problem.parameters]
Sebastian Heimann's avatar
Sebastian Heimann committed
1244
1245
1246

    while iiter < niter:

1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
        if iiter < niter_inject:
            phase = 'inject'
        elif iiter < niter_inject + niter_uniform:
            phase = 'uniform'
        elif iiter < niter_inject + niter_uniform + niter_transition:
            phase = 'transition'
        elif iiter < niter_inject + niter_uniform + niter_transition + \
                niter_explorative:
            phase = 'explorative'
        else:
            phase = 'non_explorative'

1259
        factor = 0.0
1260
        if phase == 'transition':
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
            T = float(niter_transition)
            A = scatter_scale_transition
            B = scatter_scale
            tau = T/(math.log(A) - math.log(B))
            t0 = math.log(A) * T / (math.log(A) - math.log(B))
            t = float(iiter - niter_uniform - niter_inject)
            factor = num.exp(-(t-t0) / tau)

        elif phase in ('explorative', 'non_explorative'):
            factor = scatter_scale
Sebastian Heimann's avatar
Sebastian Heimann committed
1271
1272
1273
1274

        ntries_preconstrain = 0
        ntries_sample = 0

1275
        if phase == 'inject':
Sebastian Heimann's avatar
Sebastian Heimann committed
1276
1277
1278
1279
1280
            x = xs_inject[iiter, :]
        else:
            while True:
                ntries_preconstrain += 1

1281
                if mbx is None or phase == 'uniform':
1282
                    x = problem.random_uniform(xbounds)
Sebastian Heimann's avatar
Sebastian Heimann committed
1283
1284
1285
1286
                else:
                    # jchoice = num.random.randint(0, 1 + problem.nbootstrap)
                    jchoice = num.argmin(accept_sum)

1287
                    if phase in ('transition', 'explorative'):
Sebastian Heimann's avatar
Sebastian Heimann committed
1288
1289
1290
                        ichoice = num.random.randint(0, nlinks)
                        xb = xhist[chains_i[jchoice, ichoice]]
                    else:
Sebastian Heimann's avatar
Sebastian Heimann committed
1291
                        xb = mxs[jchoice]
Sebastian Heimann's avatar
Sebastian Heimann committed
1292
1293
1294
1295

                    if sampler_distribution == 'multivariate_normal':
                        ntries_sample = 0

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1296
1297
                        ntry = 0
                        ok_mask_sum = num.zeros(npar, dtype=num.int)
Sebastian Heimann's avatar
Sebastian Heimann committed
1298
1299
1300
                        while True:
                            ntries_sample += 1
                            vs = num.random.multivariate_normal(
1301
                                xb, factor**2 * covs[jchoice])
Sebastian Heimann's avatar
Sebastian Heimann committed
1302

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1303
1304
1305
1306
                            ok_mask = num.logical_and(
                                xbounds[:, 0] <= vs, vs <= xbounds[:, 1])

                            if num.all(ok_mask):
Sebastian Heimann's avatar
Sebastian Heimann committed
1307
1308
                                break

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
                            ok_mask_sum += ok_mask

                            if ntry > 1000:
                                raise GrondError(
                                    'failed to produce a suitable candidate '
                                    'sample from multivariate normal '
                                    'distribution, (%s)' %
                                    ', '.join('%s:%i' % xx for xx in
                                              zip(pnames, ok_mask_sum)))

                            ntry += 1

Sebastian Heimann's avatar
Sebastian Heimann committed
1321
1322
1323
                        x = vs.tolist()

                    if sampler_distribution == 'normal':
1324
                        x = []
Sebastian Heimann's avatar
Sebastian Heimann committed
1325
                        for i in xrange(npar):
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1326
                            ntry = 0
Sebastian Heimann's avatar
Sebastian Heimann committed
1327
                            while True:
1328
1329
                                if sbx[i] > 0.:
                                    v = num.random.normal(
1330
                                        xb[i], factor*sbx[i])
1331
1332
1333
                                else:
                                    v = xb[i]

Sebastian Heimann's avatar
Sebastian Heimann committed
1334
1335
1336
                                if xbounds[i, 0] <= v and v <= xbounds[i, 1]:
                                    break

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1337
1338
1339
1340
1341
1342
1343
1344
                                if ntry > 1000:
                                    raise GrondError(
                                        'failed to produce a suitable '
                                        'candidate sample from normal '
                                        'distribution')

                                ntry += 1

Sebastian Heimann's avatar
Sebastian Heimann committed
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
                            x.append(v)

                try:
                    x = problem.preconstrain(x)
                    break

                except Forbidden:
                    pass

        ms, ns = problem.evaluate(x)

        isbad_mask_new = num.isnan(ms)
        if isbad_mask is not None and num.any(isbad_mask != isbad_mask_new):
            logger.error(
                'skipping problem %s: inconsistency in data availability' %
                problem.name)
Sebastian Heimann's avatar
Sebastian Heimann committed
1361

Sebastian Heimann's avatar
flake8    
Sebastian Heimann committed
1362
1363
1364
            for target, isbad_new, isbad in zip(
                    problem.targets, isbad_mask_new, isbad_mask):

Sebastian Heimann's avatar
Sebastian Heimann committed
1365
1366
1367
1368
                if isbad_new != isbad:
                    logger.error('%s, %s -> %s' % (
                        target.string_id(), isbad, isbad_new))

Sebastian Heimann's avatar
Sebastian Heimann committed
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
            return

        isbad_mask = isbad_mask_new

        if num.all(isbad_mask):
            logger.error(
                'skipping problem %s: all target misfit values are NaN' %
                problem.name)
            return

        if rundir:
            problem.dump_problem_data(rundir, x, ms, ns)

        m = problem.global_misfit(ms, ns)
        ms = problem.bootstrap_misfit(ms, ns)

        chains_m[0, nlinks] = m
        chains_m[1:, nlinks] = ms
        chains_i[:, nlinks] = iiter

        nlinks += 1

        for ichain in xrange(chains_m.shape[0]):
            isort = num.argsort(chains_m[ichain, :nlinks])
            chains_m[ichain, :nlinks] = chains_m[ichain, isort]
            chains_i[ichain, :nlinks] = chains_i[ichain, isort]

        if nlinks == nlinks_cap:
            accept = (chains_i[:, nlinks_cap-1] != iiter).astype(num.int)
            nlinks -= 1
        else:
            accept = num.ones(1 + problem.nbootstrap, dtype=num.int)

        accept_sum += accept
1403
        accept_hist[iiter] = num.sum(accept)
Sebastian Heimann's avatar
Sebastian Heimann committed
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416

        lines = []
        if 'state' in status:
            lines.append('%i' % iiter)
            lines.append(''.join('-X'[int(acc)] for acc in accept))

        xhist[iiter, :] = x

        bxs = xhist[chains_i[:, :nlinks].ravel(), :]
        gxs = xhist[chains_i[0, :nlinks], :]
        gms = chains_m[0, :nlinks]

        if nlinks > (nlinks_cap-1)/2:
Sebastian Heimann's avatar
Sebastian Heimann committed
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
            # mean and std of all bootstrap ensembles together
            mbx = num.mean(bxs, axis=0)
            sbx = num.std(bxs, axis=0)

            # mean and std of global configuration
            mgx = num.mean(gxs, axis=0)
            sgx = num.std(gxs, axis=0)

            # best in global configuration
            bgx = xhist[chains_i[0, 0], :]

Sebastian Heimann's avatar
Sebastian Heimann committed
1428
            covs = []
Sebastian Heimann's avatar
Sebastian Heimann committed
1429
            mxs = []
Sebastian Heimann's avatar
Sebastian Heimann committed
1430
1431
            for i in xrange(1 + problem.nbootstrap):
                xs = xhist[chains_i[i, :nlinks], :]
Sebastian Heimann's avatar
Sebastian Heimann committed
1432
1433
1434
1435
1436
                mx = num.mean(xs, axis=0)
                cov = num.cov(xs.T)

                mxs.append(mx)
                covs.append(cov)
Sebastian Heimann's avatar
Sebastian Heimann committed
1437
1438
1439
1440
1441
1442
1443

            if 'state' in status:
                lines.append(
                    '%-15s %15s %15s %15s %15s %15s' %
                    ('parameter', 'B mean', 'B std', 'G mean', 'G std',
                     'G best'))

Sebastian Heimann's avatar
Sebastian Heimann committed
1444
                for (pname, mbv, sbv, mgv, sgv, bgv) in zip(
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1445
                        pnames, mbx, sbx, mgx, sgx, bgx):
Sebastian Heimann's avatar
Sebastian Heimann committed
1446
1447
1448

                    lines.append(
                        '%-15s %15.4g %15.4g %15.4g %15.4g %15.4g' %
Sebastian Heimann's avatar
Sebastian Heimann committed
1449
                        (pname, mbv, sbv, mgv, sgv, bgv))
Sebastian Heimann's avatar
Sebastian Heimann committed
1450
1451
1452
1453
1454
1455
1456
1457

                lines.append('%-15s %15s %15s %15.4g %15.4g %15.4g' % (
                    'misfit', '', '',
                    num.mean(gms), num.std(gms), num.min(gms)))

        if 'state' in status:
            lines.append(
                '%-15s %15i %-15s %15i %15i' % (
1458
                    'iteration', iiter+1, '(%s, %g)' % (phase, factor),
Sebastian Heimann's avatar
Sebastian Heimann committed
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
                    ntries_sample, ntries_preconstrain))

        if 'matrix' in status:
            matrix = (chains_i[:, :30] % 94 + 32).T
            for row in matrix[::-1]:
                lines.append(''.join(chr(xxx) for xxx in row))

        if status:
            lines[0:0] = ['\033[2J']
            lines.append('')
            print '\n'.join(lines)

        iiter += 1


Sebastian Heimann's avatar
Sebastian Heimann committed
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
def bootstrap_outliers(problem, misfits, std_factor=1.0):
    '''
    Identify bootstrap configurations performing bad in global configuration
    '''

    gms = problem.global_misfits(misfits)

    ibests = []
    for ibootstrap in xrange(problem.nbootstrap):
        bms = problem.bootstrap_misfits(misfits, ibootstrap)
        ibests.append(num.argmin(bms))

    m = num.median(gms[ibests])
    s = num.std(gms[ibests])

    return num.where(gms > m+s)[0]


Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1492
def forward(rundir_or_config_path, event_names=None):
Sebastian Heimann's avatar
Sebastian Heimann committed
1493

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1494
    if os.path.isdir(rundir_or_config_path):
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1495
1496
1497
1498
        rundir = rundir_or_config_path
        config = guts.load(
            filename=op.join(rundir, 'config.yaml'))

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1499
        config.set_basepath(rundir)
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1500
1501
        problem, xs, misfits = load_problem_info_and_data(
            rundir, subset='harvest')
Sebastian Heimann's avatar
Sebastian Heimann committed
1502

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1503
1504
1505
        gms = problem.global_misfits(misfits)
        ibest = num.argmin(gms)
        xbest = xs[ibest, :]
Sebastian Heimann's avatar
Sebastian Heimann committed
1506

1507
        ds = config.get_dataset(problem.base_source.name)
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1508
        problem.set_engine(config.engine_config.get_engine())
Sebastian Heimann's avatar
Sebastian Heimann committed
1509

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1510
1511
1512
1513
1514
1515
1516
1517
1518
        for target in problem.targets:
            target.set_dataset(ds)

        payload = [(problem, xbest)]

    else:
        config = read_config(rundir_or_config_path)

        payload = []
1519
1520
1521
        for event_name in event_names:
            ds = config.get_dataset(event_name)
            event = ds.get_event()
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1522
1523
1524
1525
            problem = config.get_problem(event)
            xref = problem.preconstrain(
                problem.pack(problem.base_source))
            payload.append((problem, xref))
Sebastian Heimann's avatar
Sebastian Heimann committed
1526
1527

    all_trs = []
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1528
1529
1530
    events = []
    for (problem, x) in payload:
        ds.empty_cache()
1531
        ms, ns, results = problem.evaluate(x, result_mode='full')
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1532
1533
1534

        event = problem.unpack(x).pyrocko_event()
        events.append(event)
Sebastian Heimann's avatar
Sebastian Heimann committed
1535
1536

        for result in results:
1537
            if not isinstance(result, gf.SeismosizerError):
Sebastian Heimann's avatar
Sebastian Heimann committed
1538
1539
1540
1541
1542
                result.filtered_obs.set_codes(location='ob')
                result.filtered_syn.set_codes(location='sy')
                all_trs.append(result.filtered_obs)
                all_trs.append(result.filtered_syn)

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1543
1544
1545
1546
1547
    markers = []
    for ev in events:
        markers.append(gui_util.EventMarker(ev))

    trace.snuffle(all_trs, markers=markers, stations=ds.get_stations())
Sebastian Heimann's avatar
Sebastian Heimann committed
1548
1549


Sebastian Heimann's avatar
Sebastian Heimann committed
1550
def harvest(rundir, problem=None, nbest=10, force=False, weed=0):
Sebastian Heimann's avatar
Sebastian Heimann committed
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565

    if problem is None:
        problem, xs, misfits = load_problem_info_and_data(rundir)
    else:
        xs, misfits = load_problem_data(rundir, problem)

    dumpdir = op.join(rundir, 'harvest')
    if op.exists(dumpdir):
        if force:
            shutil.rmtree(dumpdir)
        else:
            raise DirectoryAlreadyExists(dumpdir)

    util.ensuredir(dumpdir)

Sebastian Heimann's avatar
Sebastian Heimann committed
1566
1567
    ibests_list = []
    ibests = []
Sebastian Heimann's avatar
Sebastian Heimann committed
1568
1569
1570
    gms = problem.global_misfits(misfits)
    isort = num.argsort(gms)

Sebastian Heimann's avatar
Sebastian Heimann committed
1571
1572
    ibests_list.append(isort[:nbest])

1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
    if weed != 3:
        for ibootstrap in xrange(problem.nbootstrap):
            bms = problem.bootstrap_misfits(misfits, ibootstrap)
            isort = num.argsort(bms)
            ibests_list.append(isort[:nbest])
            ibests.append(isort[0])

        if weed:
            mean_gm_best = num.median(gms[ibests])
            std_gm_best = num.std(gms[ibests])
            ibad = set()

            for ibootstrap, ibest in enumerate(ibests):
                if gms[ibest] > mean_gm_best + std_gm_best:
                    ibad.add(ibootstrap)

            ibests_list = [
                ibests_ for (ibootstrap, ibests_) in enumerate(ibests_list)
                if ibootstrap not in ibad]
Sebastian Heimann's avatar
Sebastian Heimann committed
1592

1593
    ibests = num.concatenate(ibests_list)
Sebastian Heimann's avatar
Sebastian Heimann committed
1594
1595
1596
1597
1598
1599
1600
1601

    if weed == 2:
        ibests = ibests[gms[ibests] < mean_gm_best]

    for i in ibests:
        x = xs[i]
        ms = misfits[i, :, 0]
        ns = misfits[i, :, 1]
Sebastian Heimann's avatar
Sebastian Heimann committed
1602
1603
1604
        problem.dump_problem_data(dumpdir, x, ms, ns)


Sebastian Heimann's avatar
Sebastian Heimann committed
1605
1606
1607
1608
def get_event_names(config):
    return config.get_event_names()


Sebastian Heimann's avatar
Sebastian Heimann committed
1609
def check_problem(problem):
Sebastian Heimann's avatar
Sebastian Heimann committed
1610
1611
1612
1613
    if len(problem.targets) == 0:
        raise GrondError('no targets available')


1614
1615
1616
1617
1618
1619
1620
def check(
        config,
        event_names=None,
        target_string_ids=None,
        show_plot=False,
        n_random_synthetics=10):

Sebastian Heimann's avatar
Sebastian Heimann committed
1621
    from matplotlib import pyplot as plt
Sebastian Heimann's avatar
Sebastian Heimann committed
1622
    from grond.plot import colors
Sebastian Heimann's avatar
Sebastian Heimann committed
1623

1624
1625
1626
    for ievent, event_name in enumerate(event_names):
        ds = config.get_dataset(event_name)
        event = ds.get_event()
Sebastian Heimann's avatar
Sebastian Heimann committed
1627
1628
        try:
            problem = config.get_problem(event)
1629

Sebastian Heimann's avatar
Sebastian Heimann committed
1630
1631
1632
1633
            _, ngroups = problem.get_group_mask()
            logger.info('number of target supergroups: %i' % ngroups)
            logger.info('number of targets (total): %i' % len(problem.targets))

1634
1635
1636
            if target_string_ids:
                problem.targets = [
                    target for target in problem.targets
Sebastian Heimann's avatar
Sebastian Heimann committed
1637
1638
                    if util.match_nslc(target_string_ids, target.string_id())]

1639
1640
            logger.info(
                'number of targets (selected): %i' % len(problem.targets))
1641

Sebastian Heimann's avatar
Sebastian Heimann committed
1642
1643
1644
1645
1646
            check_problem(problem)

            xbounds = num.array(problem.bounds(), dtype=num.float)

            results_list = []
1647
1648
1649

            if n_random_synthetics == 0:
                x = problem.pack(problem.base_source)
1650
                ms, ns, results = problem.evaluate(x, result_mode='full')
Sebastian Heimann's avatar
Sebastian Heimann committed
1651
1652
                results_list.append(results)

1653
1654
1655
1656
1657
1658
            else:
                for i in xrange(n_random_synthetics):
                    x = problem.random_uniform(xbounds)
                    ms, ns, results = problem.evaluate(x, result_mode='full')
                    results_list.append(results)

Sebastian Heimann's avatar
Sebastian Heimann committed
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
            if show_plot:
                for itarget, target in enumerate(problem.targets):
                    yabsmaxs = []
                    for results in results_list:
                        result = results[itarget]
                        if not isinstance(result, gf.SeismosizerError):
                            yabsmaxs.append(
                                num.max(num.abs(
                                    result.filtered_obs.get_ydata())))

                    if yabsmaxs:
                        yabsmax = max(yabsmaxs) or 1.0
                    else:
                        yabsmax = None

                    fig = None
                    ii = 0
                    for results in results_list:
                        result = results[itarget]
                        if not isinstance(result, gf.SeismosizerError):
                            if fig is None:
                                fig = plt.figure()
                                axes = fig.add_subplot(1, 1, 1)
                                axes.set_ylim(0., 4.)
                                axes.set_title('%s' % target.string_id())

                            xdata = result.filtered_obs.get_xdata()
                            ydata = result.filtered_obs.get_ydata() / yabsmax
                            axes.plot(xdata, ydata*0.5 + 3.5, color='black')

                            color = colors[ii % len(colors)]

                            xdata = result.filtered_syn.get_xdata()
                            ydata = result.filtered_syn.get_ydata()
                            ydata = ydata / (num.max(num.abs(ydata)) or 1.0)

                            axes.plot(xdata, ydata*0.5 + 2.5, color=color)

                            xdata = result.processed_syn.get_xdata()
                            ydata = result.processed_syn.get_ydata()
                            ydata = ydata / (num.max(num.abs(ydata)) or 1.0)

                            axes.plot(xdata, ydata*0.5 + 1.5, color=color)
                            if result.tsyn_pick:
                                axes.axvline(
                                    result.tsyn_pick,
                                    color=(0.7, 0.7, 0.7),
                                    zorder=2)

                            t = result.processed_syn.get_xdata()
                            taper = result.taper

                            y = num.ones(t.size) * 0.9
                            taper(y, t[0], t[1] - t[0])
                            y2 = num.concatenate((y, -y[::-1]))
                            t2 = num.concatenate((t, t[::-1]))
                            axes.plot(t2, y2 * 0.5 + 0.5, color='gray')
                            ii += 1
                        else:
                            logger.info(str(result))

                    if fig:
                        plt.show()
Sebastian Heimann's avatar
Sebastian Heimann committed
1722

Sebastian Heimann's avatar
Sebastian Heimann committed
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
            else:
                for itarget, target in enumerate(problem.targets):

                    nok = 0
                    for results in results_list:
                        result = results[itarget]
                        if not isinstance(result, gf.SeismosizerError):
                            nok += 1

                    if nok == 0:
                        sok = 'not used'
                    elif nok == len(results_list):
                        sok = 'ok'
1736
                    else:
Sebastian Heimann's avatar
Sebastian Heimann committed
1737
                        sok = 'not used (%i/%i ok)' % (nok, len(results_list))
Sebastian Heimann's avatar
Sebastian Heimann committed
1738

Sebastian Heimann's avatar
Sebastian Heimann committed
1739
1740
                    logger.info('%-40s %s' % (
                        (target.string_id() + ':', sok)))
Sebastian Heimann's avatar
Sebastian Heimann committed
1741
1742
1743
1744
1745
1746
1747

        except GrondError, e:
            logger.error('event %i, %s: %s' % (
                ievent,
                event.name or util.time_to_str(event.time),
                str(e)))

Sebastian Heimann's avatar
Sebastian Heimann committed
1748
1749
g_state = {}

Sebastian Heimann's avatar
Sebastian Heimann committed
1750

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1751
def go(config, event_names=None, force=False, nparallel=1, status=('state',)):
Sebastian Heimann's avatar
Sebastian Heimann committed
1752
1753
1754

    status = tuple(status)

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1755
    g_data = (config, force, status, nparallel, event_names)
Sebastian Heimann's avatar
Sebastian Heimann committed
1756

Sebastian Heimann's avatar
Sebastian Heimann committed
1757
    g_state[id(g_data)] = g_data
Sebastian Heimann's avatar
Sebastian Heimann committed
1758

1759
1760
    nevents = len(event_names)

Sebastian Heimann's avatar
Sebastian Heimann committed
1761
    for x in parimap.parimap(
1762
            process_event,
Sebastian Heimann's avatar
Sebastian Heimann committed
1763
1764
1765
            xrange(nevents),
            [id(g_data)] * nevents,
            nprocs=nparallel):
Sebastian Heimann's avatar
Sebastian Heimann committed
1766

Sebastian Heimann's avatar
Sebastian Heimann committed
1767
        pass
Sebastian Heimann's avatar
Sebastian Heimann committed
1768
1769


1770
def expand_template(template, d):
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
    try:
        return Template(template).substitute(d)
    except KeyError as e:
        raise GrondError(
            'invalid placeholder "%s" in template: "%s"' % (str(e), template))
    except ValueError:
        raise GrondError(
            'malformed placeholder in template: "%s"' % template)


Sebastian Heimann's avatar
Sebastian Heimann committed
1781
1782
def process_event(ievent, g_data_id):

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1783
    config, force, status, nparallel, event_names = g_state[g_data_id]
Sebastian Heimann's avatar
Sebastian Heimann committed
1784
1785
1786
1787

    if nparallel > 1:
        status = ()

1788
    event_name = event_names[ievent]
Sebastian Heimann's avatar
Sebastian Heimann committed
1789

1790
    ds = config.get_dataset(event_name)
Sebastian Heimann's avatar
Sebastian Heimann committed
1791

1792
    nevents = len(event_names)
Sebastian Heimann's avatar
Sebastian Heimann committed
1793
1794
1795

    tstart = time.time()

1796
1797
    event = ds.get_event()

Sebastian Heimann's avatar
Sebastian Heimann committed
1798
1799
    problem = config.get_problem(event)

1800
    synt = ds.synthetic_test
1801
    if synt:
1802
1803
        problem.base_source = problem.unpack(synt.get_x())

Sebastian Heimann's avatar
Sebastian Heimann committed
1804
    check_problem(problem)
Sebastian Heimann's avatar
Sebastian Heimann committed
1805

1806
    rundir = expand_template(
1807
1808
        config.rundir_template,
        dict(problem_name=problem.name))
Sebastian Heimann's avatar
Sebastian Heimann committed
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825

    if op.exists(rundir):
        if force:
            shutil.rmtree(rundir)
        else:
            logger.warn('skipping problem %s: rundir already exists: %s' %
                        (problem.name, rundir))
            return

    util.ensuredir(rundir)

    logger.info(
        'start %i / %i' % (ievent+1, nevents))

    analyse(
        problem,
        niter=config.analyser_config.niter,
Sebastian Heimann's avatar
Sebastian Heimann committed
1826
        show_progress=nparallel == 1)
Sebastian Heimann's avatar
Sebastian Heimann committed
1827

Sebastian Heimann's avatar
Sebastian Heimann committed
1828
1829
1830
1831
    basepath = config.get_basepath()
    config.change_basepath(rundir)
    guts.dump(config, filename=op.join(rundir, 'config.yaml'))
    config.change_basepath(basepath)
Sebastian Heimann's avatar
Sebastian Heimann committed
1832

Sebastian Heimann's avatar
Sebastian Heimann committed
1833
    problem.dump_problem_info(rundir)
Sebastian Heimann's avatar
Sebastian Heimann committed
1834

Sebastian Heimann's avatar
Sebastian Heimann committed
1835
1836
1837
1838
    xs_inject = None
    synt = ds.synthetic_test
    if synt and synt.inject_solution:
        xs_inject = synt.get_x()[num.newaxis, :]
Sebastian Heimann's avatar
Sebastian Heimann committed
1839

Sebastian Heimann's avatar
Sebastian Heimann committed
1840
1841
1842
1843
1844
    solve(problem,
          rundir=rundir,
          status=status,
          xs_inject=xs_inject,
          **config.solver_config.get_solver_kwargs())
Sebastian Heimann's avatar
Sebastian Heimann committed
1845

Sebastian Heimann's avatar
Sebastian Heimann committed
1846
    harvest(rundir, problem)
Sebastian Heimann's avatar
Sebastian Heimann committed
1847

Sebastian Heimann's avatar
Sebastian Heimann committed
1848
1849
1850
    tstop = time.time()
    logger.info(
        'stop %i / %i (%g min)' % (ievent, nevents, (tstop - tstart)/60.))
Sebastian Heimann's avatar
Sebastian Heimann committed
1851

1852
1853
1854
    logger.info(
        'done with problem %s, rundir is %s' % (problem.name, rundir))

Sebastian Heimann's avatar
Sebastian Heimann committed
1855

Sebastian Heimann's avatar
Sebastian Heimann committed
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
class ParameterStats(Object):
    name = String.T()
    mean = Float.T()
    std = Float.T()
    best = Float.T()
    minimum = Float.T()
    percentile5 = Float.T()
    percentile16 = Float.T()
    median = Float.T()
    percentile84 = Float.T()
    percentile95 = Float.T()
    maximum = Float.T()
Sebastian Heimann's avatar
Sebastian Heimann committed
1868

Sebastian Heimann's avatar
Sebastian Heimann committed
1869
1870
1871
    def __init__(self, *args, **kwargs):
        kwargs.update(zip(self.T.propnames, args))
        Object.__init__(self, **kwargs)
Sebastian Heimann's avatar
Sebastian Heimann committed
1872
1873


Sebastian Heimann's avatar
Sebastian Heimann committed
1874
1875
1876
1877
1878
1879
class ResultStats(Object):
    problem = Problem.T()
    parameter_stats_list = List.T(ParameterStats.T())


def make_stats(problem, xs, misfits, pnames=None):
Sebastian Heimann's avatar
Sebastian Heimann committed
1880
    gms = problem.global_misfits(misfits)
Sebastian Heimann's avatar
Sebastian Heimann committed
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
    ibest = num.argmin(gms)
    rs = ResultStats(problem=problem)
    if pnames is None:
        pnames = problem.parameter_names

    for pname in pnames:
        iparam = problem.name_to_index(pname)
        vs = problem.extract(xs, iparam)
        mi, p5, p16, median, p84, p95, ma = map(float, num.percentile(
            vs, [0., 5., 16., 50., 84., 95., 100.]))

        mean = float(num.mean(vs))
        std = float(num.std(vs))
        best = float(vs[ibest])
        s = ParameterStats(
            pname, mean, std, best, mi, p5, p16, median, p84, p95, ma)

        rs.parameter_stats_list.append(s)

    return rs
Sebastian Heimann's avatar
Sebastian Heimann committed
1901
1902


Sebastian Heimann's avatar
Sebastian Heimann committed
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
def format_stats(rs, fmt):
    pname_to_pindex = dict(
        (p.name, i) for (i, p) in enumerate(rs.parameter_stats_list))

    values = []
    headers = []
    for x in fmt:
        pname, qname = x.split('.')
        pindex = pname_to_pindex[pname]
        values.append(getattr(rs.parameter_stats_list[pindex], qname))
        headers.append(x)

    return ' '.join('%16.7g' % v for v in values)


def export(what, rundirs, type=None, pnames=None, filename=None):
    if pnames is not None:
        pnames_clean = [pname.split('.')[0] for pname in pnames]
        shortform = all(len(pname.split('.')) == 2 for pname in pnames)
    else:
        pnames_clean = None
        shortform = False

    if what == 'stats' and type is not None:
        raise GrondError('invalid argument combination: what=%s, type=%s' % (
            repr(what), repr(type)))

    if what != 'stats' and shortform:
        raise GrondError('invalid argument combination: what=%s, pnames=%s' % (
            repr(what), repr(pnames)))

    if what != 'stats' and type != 'vector' and pnames is not None:
        raise GrondError(
            'invalid argument combination: what=%s, type=%s, pnames=%s' % (
                repr(what), repr(type), repr(pnames)))

    if filename is None:
        out = sys.stdout
    else:
        out = open(filename, 'w')

    if type is None:
        type = 'event'

    if shortform:
        print >>out, '#', ' '.join('%16s' % x for x in pnames)

1950
    def dump(x, gm, indices):
Sebastian Heimann's avatar
Sebastian Heimann committed
1951
        if type == 'vector':
1952
1953
            print >>out, ' ', ' '.join('%16.7g' % v for v in x[indices]), \
                '%16.7g' % gm
Sebastian Heimann's avatar
Sebastian Heimann committed
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977

        elif type == 'source':
            source = problem.unpack(x)
            guts.dump(source, stream=out)

        elif type == 'event':
            ev = problem.unpack(x).pyrocko_event()
            model.dump_events([ev], stream=out)

        else:
            raise GrondError('invalid argument: type=%s' % repr(type))

    header = None
    for rundir in rundirs:
        problem, xs, misfits = load_problem_info_and_data(
            rundir, subset='harvest')

        if type == 'vector':
            pnames_take = pnames_clean or \
                problem.parameter_names[:problem.nparameters]

            indices = num.array(
                [problem.name_to_index(pname) for pname in pnames_take])

1978
1979
1980
1981
1982
1983
1984
1985
            if type == 'vector' and what in ('best', 'mean', 'ensemble'):
                extra = ['global_misfit']
            else:
                extra = []

            new_header = '# ' + ' '.join(
                '%16s' % x for x in pnames_take + extra)

Sebastian Heimann's avatar
Sebastian Heimann committed
1986
1987
1988
1989
1990
1991
1992
1993
            if type == 'vector' and header != new_header:
                print >>out, new_header

            header = new_header
        else:
            indices = None

        if what == 'best':
1994
1995
            x_best, gm_best = get_best_x_and_gm(problem, xs, misfits)
            dump(x_best, gm_best, indices)
Sebastian Heimann's avatar
Sebastian Heimann committed
1996
1997

        elif what == 'mean':
1998
1999
            x_mean, gm_mean = get_mean_x_and_gm(problem, xs, misfits)
            dump(x_mean, gm_mean, indices)
Sebastian Heimann's avatar
Sebastian Heimann committed
2000