core.py 65.9 KB
Newer Older
Sebastian Heimann's avatar
Sebastian Heimann committed
1001
    niter_uniform = Int.T(default=1000)
Sebastian Heimann's avatar
Sebastian Heimann committed
1002
    niter_transition = Int.T(default=0)
Sebastian Heimann's avatar
Sebastian Heimann committed
1003
1004
1005
1006
    niter_explorative = Int.T(default=10000)
    niter_non_explorative = Int.T(default=0)
    sampler_distribution = SamplerDistributionChoice.T(
        default='multivariate_normal')
1007
    scatter_scale_transition = Float.T(default=2.0)
1008
    scatter_scale = Float.T(default=1.0)
Sebastian Heimann's avatar
Sebastian Heimann committed
1009
1010
1011
1012

    def get_solver_kwargs(self):
        return dict(
            niter_uniform=self.niter_uniform,
Sebastian Heimann's avatar
Sebastian Heimann committed
1013
            niter_transition=self.niter_transition,
Sebastian Heimann's avatar
Sebastian Heimann committed
1014
1015
            niter_explorative=self.niter_explorative,
            niter_non_explorative=self.niter_non_explorative,
1016
            sampler_distribution=self.sampler_distribution,
1017
            scatter_scale_transition=self.scatter_scale_transition,
1018
            scatter_scale=self.scatter_scale)
Sebastian Heimann's avatar
Sebastian Heimann committed
1019
1020


Sebastian Heimann's avatar
Sebastian Heimann committed
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
class EngineConfig(HasPaths):
    gf_stores_from_pyrocko_config = Bool.T(default=True)
    gf_store_superdirs = List.T(Path.T())
    gf_store_dirs = List.T(Path.T())

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

    def get_engine(self):
        if self._engine is None:
            fp = self.expand_path
            self._engine = gf.LocalEngine(
                use_config=self.gf_stores_from_pyrocko_config,
                store_superdirs=fp(self.gf_store_superdirs),
                store_dirs=fp(self.gf_store_dirs))

        return self._engine


Sebastian Heimann's avatar
Sebastian Heimann committed
1041
1042
1043
1044
1045
1046
1047
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
1048
    engine_config = EngineConfig.T(default=EngineConfig.D())
Sebastian Heimann's avatar
Sebastian Heimann committed
1049
1050
1051
1052

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

Sebastian Heimann's avatar
Sebastian Heimann committed
1053
1054
1055
    def get_event_names(self):
        return self.dataset_config.get_event_names()

1056
1057
    def get_dataset(self, event_name):
        return self.dataset_config.get_dataset(event_name)
Sebastian Heimann's avatar
Sebastian Heimann committed
1058
1059

    def get_targets(self, event):
1060
        ds = self.get_dataset(event.name)
Sebastian Heimann's avatar
Sebastian Heimann committed
1061
1062
1063
1064
1065
1066
1067
1068

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

        return targets

1069
1070
1071
1072
1073
1074
1075
1076
    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
1077
1078
    def get_problem(self, event):
        targets = self.get_targets(event)
Sebastian Heimann's avatar
Sebastian Heimann committed
1079
        problem = self.problem_config.get_problem(event, targets)
1080
        self.setup_modelling_environment(problem)
Sebastian Heimann's avatar
Sebastian Heimann committed
1081
        return problem
Sebastian Heimann's avatar
Sebastian Heimann committed
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125


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
1126
1127
1128
1129
def get_mean_x(xs):
    return num.mean(xs, axis=0)


1130
1131
1132
1133
1134
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
1135
1136
1137
1138
1139
1140
def get_best_x(problem, xs, misfits):
    gms = problem.global_misfits(misfits)
    ibest = num.argmin(gms)
    return xs[ibest, :]


1141
1142
1143
1144
1145
1146
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
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
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
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
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
1178
1179
1180
    if not isinstance(config, Config):
        raise GrondError('invalid Grond configuration in file "%s"' % path)

Sebastian Heimann's avatar
Sebastian Heimann committed
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
    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)

1196
    groups, ngroups = problem.get_group_mask()
1197

Sebastian Heimann's avatar
Sebastian Heimann committed
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
    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)

1210
    isbad_mask = None
Sebastian Heimann's avatar
Sebastian Heimann committed
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
    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

1225
1226
1227
1228
1229
1230
        if isbad_mask is not None and num.any(isbad_mask):
            isok_mask = num.logical_not(isbad_mask)
        else:
            isok_mask = None

        _, ms = wproblem.evaluate(x, mask=isok_mask)
Sebastian Heimann's avatar
Sebastian Heimann committed
1231
1232
        mss[iiter, :] = ms

1233
1234
        isbad_mask = num.isnan(ms)

Sebastian Heimann's avatar
Sebastian Heimann committed
1235
1236
1237
1238
1239
1240
1241
1242
1243
        if show_progress:
            pbar.update(iiter)

    if show_progress:
        pbar.finish()

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

    weights = 1.0 / mean_ms
1244
1245
1246
1247
    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
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259

    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,
1260
          scatter_scale_transition=2.0,
1261
          scatter_scale=1.0,
Sebastian Heimann's avatar
Sebastian Heimann committed
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
          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
1273
    mbx = None
Sebastian Heimann's avatar
Sebastian Heimann committed
1274
1275
1276
1277
1278
1279

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

1280
    niter = niter_inject + niter_uniform + niter_transition + \
1281
        niter_explorative + niter_non_explorative
Sebastian Heimann's avatar
Sebastian Heimann committed
1282
1283

    iiter = 0
Sebastian Heimann's avatar
Sebastian Heimann committed
1284
1285
    sbx = None
    mxs = None
Sebastian Heimann's avatar
Sebastian Heimann committed
1286
1287
1288
1289
    covs = None
    xhist = num.zeros((niter, npar))
    isbad_mask = None
    accept_sum = num.zeros(1 + problem.nbootstrap, dtype=num.int)
1290
    accept_hist = num.zeros(niter, dtype=num.int)
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1291
    pnames = [p.name for p in problem.parameters]
Sebastian Heimann's avatar
Sebastian Heimann committed
1292
1293
1294

    while iiter < niter:

1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
        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'

1307
        factor = 0.0
1308
        if phase == 'transition':
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
            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
1319
1320
1321
1322

        ntries_preconstrain = 0
        ntries_sample = 0

1323
        if phase == 'inject':
Sebastian Heimann's avatar
Sebastian Heimann committed
1324
1325
1326
1327
1328
            x = xs_inject[iiter, :]
        else:
            while True:
                ntries_preconstrain += 1

1329
                if mbx is None or phase == 'uniform':
1330
                    x = problem.random_uniform(xbounds)
Sebastian Heimann's avatar
Sebastian Heimann committed
1331
1332
1333
1334
                else:
                    # jchoice = num.random.randint(0, 1 + problem.nbootstrap)
                    jchoice = num.argmin(accept_sum)

1335
                    if phase in ('transition', 'explorative'):
Sebastian Heimann's avatar
Sebastian Heimann committed
1336
1337
1338
                        ichoice = num.random.randint(0, nlinks)
                        xb = xhist[chains_i[jchoice, ichoice]]
                    else:
Sebastian Heimann's avatar
Sebastian Heimann committed
1339
                        xb = mxs[jchoice]
Sebastian Heimann's avatar
Sebastian Heimann committed
1340
1341
1342
1343

                    if sampler_distribution == 'multivariate_normal':
                        ntries_sample = 0

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1344
1345
                        ntry = 0
                        ok_mask_sum = num.zeros(npar, dtype=num.int)
Sebastian Heimann's avatar
Sebastian Heimann committed
1346
1347
1348
                        while True:
                            ntries_sample += 1
                            vs = num.random.multivariate_normal(
1349
                                xb, factor**2 * covs[jchoice])
Sebastian Heimann's avatar
Sebastian Heimann committed
1350

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1351
1352
1353
1354
                            ok_mask = num.logical_and(
                                xbounds[:, 0] <= vs, vs <= xbounds[:, 1])

                            if num.all(ok_mask):
Sebastian Heimann's avatar
Sebastian Heimann committed
1355
1356
                                break

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
                            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
1369
1370
1371
                        x = vs.tolist()

                    if sampler_distribution == 'normal':
1372
                        x = []
Sebastian Heimann's avatar
Sebastian Heimann committed
1373
                        for i in xrange(npar):
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1374
                            ntry = 0
Sebastian Heimann's avatar
Sebastian Heimann committed
1375
                            while True:
1376
1377
                                if sbx[i] > 0.:
                                    v = num.random.normal(
1378
                                        xb[i], factor*sbx[i])
1379
1380
1381
                                else:
                                    v = xb[i]

Sebastian Heimann's avatar
Sebastian Heimann committed
1382
1383
1384
                                if xbounds[i, 0] <= v and v <= xbounds[i, 1]:
                                    break

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1385
1386
1387
1388
1389
1390
1391
1392
                                if ntry > 1000:
                                    raise GrondError(
                                        'failed to produce a suitable '
                                        'candidate sample from normal '
                                        'distribution')

                                ntry += 1

Sebastian Heimann's avatar
Sebastian Heimann committed
1393
1394
1395
1396
1397
1398
1399
1400
1401
                            x.append(v)

                try:
                    x = problem.preconstrain(x)
                    break

                except Forbidden:
                    pass

1402
1403
1404
1405
1406
1407
        if isbad_mask is not None and num.any(isbad_mask):
            isok_mask = num.logical_not(isbad_mask)
        else:
            isok_mask = None

        ms, ns = problem.evaluate(x, mask=isok_mask)
Sebastian Heimann's avatar
Sebastian Heimann committed
1408
1409
1410
1411
1412
1413

        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
1414

Sebastian Heimann's avatar
flake8    
Sebastian Heimann committed
1415
1416
1417
            for target, isbad_new, isbad in zip(
                    problem.targets, isbad_mask_new, isbad_mask):

Sebastian Heimann's avatar
Sebastian Heimann committed
1418
1419
1420
1421
                if isbad_new != isbad:
                    logger.error('%s, %s -> %s' % (
                        target.string_id(), isbad, isbad_new))

Sebastian Heimann's avatar
Sebastian Heimann committed
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
            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
1456
        accept_hist[iiter] = num.sum(accept)
Sebastian Heimann's avatar
Sebastian Heimann committed
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469

        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
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
            # 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
1481
            covs = []
Sebastian Heimann's avatar
Sebastian Heimann committed
1482
            mxs = []
Sebastian Heimann's avatar
Sebastian Heimann committed
1483
1484
            for i in xrange(1 + problem.nbootstrap):
                xs = xhist[chains_i[i, :nlinks], :]
Sebastian Heimann's avatar
Sebastian Heimann committed
1485
1486
1487
1488
1489
                mx = num.mean(xs, axis=0)
                cov = num.cov(xs.T)

                mxs.append(mx)
                covs.append(cov)
Sebastian Heimann's avatar
Sebastian Heimann committed
1490
1491
1492
1493
1494
1495
1496

            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
1497
                for (pname, mbv, sbv, mgv, sgv, bgv) in zip(
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1498
                        pnames, mbx, sbx, mgx, sgx, bgx):
Sebastian Heimann's avatar
Sebastian Heimann committed
1499
1500
1501

                    lines.append(
                        '%-15s %15.4g %15.4g %15.4g %15.4g %15.4g' %
Sebastian Heimann's avatar
Sebastian Heimann committed
1502
                        (pname, mbv, sbv, mgv, sgv, bgv))
Sebastian Heimann's avatar
Sebastian Heimann committed
1503
1504
1505
1506
1507
1508
1509
1510

                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' % (
1511
                    'iteration', iiter+1, '(%s, %g)' % (phase, factor),
Sebastian Heimann's avatar
Sebastian Heimann committed
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
                    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
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
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
1545
def forward(rundir_or_config_path, event_names=None):
Sebastian Heimann's avatar
Sebastian Heimann committed
1546

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1547
    if os.path.isdir(rundir_or_config_path):
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1548
1549
1550
1551
        rundir = rundir_or_config_path
        config = guts.load(
            filename=op.join(rundir, 'config.yaml'))

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1552
        config.set_basepath(rundir)
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1553
1554
        problem, xs, misfits = load_problem_info_and_data(
            rundir, subset='harvest')
Sebastian Heimann's avatar
Sebastian Heimann committed
1555

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1556
1557
1558
        gms = problem.global_misfits(misfits)
        ibest = num.argmin(gms)
        xbest = xs[ibest, :]
Sebastian Heimann's avatar
Sebastian Heimann committed
1559

1560
        ds = config.get_dataset(problem.base_source.name)
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1561
        problem.set_engine(config.engine_config.get_engine())
Sebastian Heimann's avatar
Sebastian Heimann committed
1562

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1563
1564
1565
1566
1567
1568
1569
1570
1571
        for target in problem.targets:
            target.set_dataset(ds)

        payload = [(problem, xbest)]

    else:
        config = read_config(rundir_or_config_path)

        payload = []
1572
1573
1574
        for event_name in event_names:
            ds = config.get_dataset(event_name)
            event = ds.get_event()
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1575
1576
1577
1578
            problem = config.get_problem(event)
            xref = problem.preconstrain(
                problem.pack(problem.base_source))
            payload.append((problem, xref))
Sebastian Heimann's avatar
Sebastian Heimann committed
1579
1580

    all_trs = []
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1581
1582
1583
    events = []
    for (problem, x) in payload:
        ds.empty_cache()
1584
        ms, ns, results = problem.evaluate(x, result_mode='full')
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1585
1586
1587

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

        for result in results:
1590
            if not isinstance(result, gf.SeismosizerError):
Sebastian Heimann's avatar
Sebastian Heimann committed
1591
1592
1593
1594
1595
                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
1596
1597
    markers = []
    for ev in events:
1598
        markers.append(pmarker.EventMarker(ev))
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1599
1600

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


Sebastian Heimann's avatar
Sebastian Heimann committed
1603
def harvest(rundir, problem=None, nbest=10, force=False, weed=0):
Sebastian Heimann's avatar
Sebastian Heimann committed
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618

    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
1619
1620
    ibests_list = []
    ibests = []
Sebastian Heimann's avatar
Sebastian Heimann committed
1621
1622
1623
    gms = problem.global_misfits(misfits)
    isort = num.argsort(gms)

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

1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
    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
1645

1646
    ibests = num.concatenate(ibests_list)
Sebastian Heimann's avatar
Sebastian Heimann committed
1647
1648
1649
1650
1651
1652
1653
1654

    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
1655
1656
1657
        problem.dump_problem_data(dumpdir, x, ms, ns)


Sebastian Heimann's avatar
Sebastian Heimann committed
1658
1659
1660
1661
def get_event_names(config):
    return config.get_event_names()


Sebastian Heimann's avatar
Sebastian Heimann committed
1662
def check_problem(problem):
Sebastian Heimann's avatar
Sebastian Heimann committed
1663
1664
1665
1666
    if len(problem.targets) == 0:
        raise GrondError('no targets available')


1667
1668
1669
1670
1671
def check(
        config,
        event_names=None,
        target_string_ids=None,
        show_plot=False,
1672
        show_waveforms=False,
1673
1674
        n_random_synthetics=10):

1675
1676
1677
    if show_plot:
        from matplotlib import pyplot as plt
        from grond.plot import colors
Sebastian Heimann's avatar
Sebastian Heimann committed
1678

1679
    markers = []
1680
1681
1682
    for ievent, event_name in enumerate(event_names):
        ds = config.get_dataset(event_name)
        event = ds.get_event()
1683
        trs_all = []
Sebastian Heimann's avatar
Sebastian Heimann committed
1684
1685
        try:
            problem = config.get_problem(event)
1686

Sebastian Heimann's avatar
Sebastian Heimann committed
1687
1688
1689
1690
            _, ngroups = problem.get_group_mask()
            logger.info('number of target supergroups: %i' % ngroups)
            logger.info('number of targets (total): %i' % len(problem.targets))

1691
1692
1693
            if target_string_ids:
                problem.targets = [
                    target for target in problem.targets
Sebastian Heimann's avatar
Sebastian Heimann committed
1694
1695
                    if util.match_nslc(target_string_ids, target.string_id())]

1696
1697
            logger.info(
                'number of targets (selected): %i' % len(problem.targets))
1698

Sebastian Heimann's avatar
Sebastian Heimann committed
1699
1700
1701
1702
1703
            check_problem(problem)

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

            results_list = []
1704

1705
            sources = []
1706
1707
            if n_random_synthetics == 0:
                x = problem.pack(problem.base_source)
1708
                sources.append(problem.base_source)
1709
                ms, ns, results = problem.evaluate(x, result_mode='full')
Sebastian Heimann's avatar
Sebastian Heimann committed
1710
1711
                results_list.append(results)

1712
1713
1714
            else:
                for i in xrange(n_random_synthetics):
                    x = problem.random_uniform(xbounds)
1715
                    sources.append(problem.unpack(x))
1716
1717
1718
                    ms, ns, results = problem.evaluate(x, result_mode='full')
                    results_list.append(results)

1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
            if show_waveforms:
                engine = config.engine_config.get_engine()
                times = []
                tdata = []
                for target in problem.targets:
                    tobs_shift_group = []
                    tcuts = []
                    for source in sources:
                        tmin_fit, tmax_fit, tfade, tfade_taper = \
                            target.get_taper_params(engine, source)

                        times.extend((tmin_fit-tfade*2., tmax_fit+tfade*2.))

                        tobs, tsyn = target.get_pick_shift(engine, source)
                        if None not in (tobs, tsyn):
                            tobs_shift = tobs - tsyn
                        else:
                            tobs_shift = 0.0

                        tcuts.append(target.get_cutout_timespan(
                            tmin_fit+tobs_shift, tmax_fit+tobs_shift, tfade))

                        tobs_shift_group.append(tobs_shift)

                    tcuts = num.array(tcuts, dtype=num.float)

                    tdata.append((
                        tfade,
                        num.mean(tobs_shift_group),
                        (num.min(tcuts[:, 0]), num.max(tcuts[:, 1]))))

                tmin = min(times)
                tmax = max(times)

                tmax += (tmax-tmin)*2

                for (tfade, tobs_shift, tcut), target in zip(
                        tdata, problem.targets):

                    store = engine.get_store(target.store_id)

                    deltat = store.config.deltat

                    freqlimits = list(target.get_freqlimits())
                    freqlimits[2] = 0.45/deltat
                    freqlimits[3] = 0.5/deltat
                    freqlimits = tuple(freqlimits)

                    trs_projected, trs_restituted, trs_raw = \
                        ds.get_waveform(
                            target.codes,
                            tmin=tmin+tobs_shift,
                            tmax=tmax+tobs_shift,
                            tfade=tfade,
                            freqlimits=freqlimits,
                            deltat=deltat,
                            backazimuth=target.get_backazimuth_for_waveform(),
                            debug=True)

                    trs_projected = copy.deepcopy(trs_projected)
                    trs_restituted = copy.deepcopy(trs_restituted)
                    trs_raw = copy.deepcopy(trs_raw)

                    for trx in trs_projected + trs_restituted + trs_raw:
                        trx.shift(-tobs_shift)
                        trx.set_codes(
                            network='',
                            station=target.string_id(),
                            location='')

                    for trx in trs_projected:
                        trx.set_codes(location=trx.location + '2_proj')

                    for trx in trs_restituted:
                        trx.set_codes(location=trx.location + '1_rest')

                    for trx in trs_raw:
                        trx.set_codes(location=trx.location + '0_raw')

                    trs_all.extend(trs_projected)
                    trs_all.extend(trs_restituted)
                    trs_all.extend(trs_raw)

                    for source in sources:
                        tmin_fit, tmax_fit, tfade, tfade_taper = \
                            target.get_taper_params(engine, source)

                        markers.append(pmarker.Marker(
                            nslc_ids=[('', target.string_id(), '*', '*')],
                            tmin=tmin_fit, tmax=tmax_fit))

                    markers.append(pmarker.Marker(
                        nslc_ids=[('', target.string_id(), '*', '*')],
                        tmin=tcut[0]-tobs_shift, tmax=tcut[1]-tobs_shift,
                        kind=1))

Sebastian Heimann's avatar
Sebastian Heimann committed
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
            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
1878

Sebastian Heimann's avatar
Sebastian Heimann committed
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
            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'
1892
                    else:
Sebastian Heimann's avatar
Sebastian Heimann committed
1893
                        sok = 'not used (%i/%i ok)' % (nok, len(results_list))
Sebastian Heimann's avatar
Sebastian Heimann committed
1894

Sebastian Heimann's avatar
Sebastian Heimann committed
1895
1896
                    logger.info('%-40s %s' % (
                        (target.string_id() + ':', sok)))
Sebastian Heimann's avatar
Sebastian Heimann committed
1897
1898
1899
1900
1901
1902
1903

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

1904
1905
1906
1907
    if show_waveforms:
        trace.snuffle(trs_all, stations=ds.get_stations(), markers=markers)


Sebastian Heimann's avatar
Sebastian Heimann committed
1908
1909
g_state = {}

Sebastian Heimann's avatar
Sebastian Heimann committed
1910

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1911
def go(config, event_names=None, force=False, nparallel=1, status=('state',)):
Sebastian Heimann's avatar
Sebastian Heimann committed
1912
1913
1914

    status = tuple(status)

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

Sebastian Heimann's avatar
Sebastian Heimann committed
1917
    g_state[id(g_data)] = g_data
Sebastian Heimann's avatar
Sebastian Heimann committed
1918

1919
1920
    nevents = len(event_names)

Sebastian Heimann's avatar
Sebastian Heimann committed
1921
    for x in parimap.parimap(
1922
            process_event,
Sebastian Heimann's avatar
Sebastian Heimann committed
1923
1924
1925
            xrange(nevents),
            [id(g_data)] * nevents,
            nprocs=nparallel):
Sebastian Heimann's avatar
Sebastian Heimann committed
1926

Sebastian Heimann's avatar
Sebastian Heimann committed
1927
        pass
Sebastian Heimann's avatar
Sebastian Heimann committed
1928
1929


1930
def expand_template(template, d):
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
    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
1941
1942
def process_event(ievent, g_data_id):

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1943
    config, force, status, nparallel, event_names = g_state[g_data_id]
Sebastian Heimann's avatar
Sebastian Heimann committed
1944
1945
1946
1947

    if nparallel > 1:
        status = ()

1948
    event_name = event_names[ievent]
Sebastian Heimann's avatar
Sebastian Heimann committed
1949

1950
    ds = config.get_dataset(event_name)
Sebastian Heimann's avatar
Sebastian Heimann committed
1951

1952
    nevents = len(event_names)
Sebastian Heimann's avatar
Sebastian Heimann committed
1953
1954
1955

    tstart = time.time()

1956
1957
    event = ds.get_event()

Sebastian Heimann's avatar
Sebastian Heimann committed
1958
1959
    problem = config.get_problem(event)

1960
    synt = ds.synthetic_test
1961
    if synt:
1962
1963
        problem.base_source = problem.unpack(synt.get_x())

Sebastian Heimann's avatar
Sebastian Heimann committed
1964
    check_problem(problem)
Sebastian Heimann's avatar
Sebastian Heimann committed
1965

1966
    rundir = expand_template(
1967
1968
        config.rundir_template,
        dict(problem_name=problem.name))
Sebastian Heimann's avatar
Sebastian Heimann committed
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985

    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
1986
        show_progress=nparallel == 1)
Sebastian Heimann's avatar
Sebastian Heimann committed
1987

Sebastian Heimann's avatar
Sebastian Heimann committed
1988
1989
1990
1991
    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
1992

Sebastian Heimann's avatar
Sebastian Heimann committed
1993
    problem.dump_problem_info(rundir)
Sebastian Heimann's avatar
Sebastian Heimann committed
1994

Sebastian Heimann's avatar
Sebastian Heimann committed
1995
1996
1997
1998
    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
1999

Sebastian Heimann's avatar
Sebastian Heimann committed
2000
    solve(problem,