plot.py 43.1 KB
Newer Older
1001
1002
                    (result.processed_syn.get_ydata() -
                     result.processed_obs.get_ydata())**2))
Sebastian Heimann's avatar
Sebastian Heimann committed
1003
1004
1005

        target_to_result[target] = result

1006
        dtrace.meta = dict(super_group=target.super_group, group=target.group)
Sebastian Heimann's avatar
Sebastian Heimann committed
1007
        dtraces.append(dtrace)
1008

1009
1010
1011
        result.processed_syn.meta = dict(
            super_group=target.super_group, group=target.group)

Sebastian Heimann's avatar
Sebastian Heimann committed
1012
1013
        all_syn_trs.append(result.processed_syn)

1014
        if result.spectrum_syn:
1015
1016
1017
            result.spectrum_syn.meta = dict(
                super_group=target.super_group, group=target.group)

1018
1019
            all_syn_specs.append(result.spectrum_syn)

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1020
1021
    if not all_syn_trs:
        logger.warn('no traces to show')
1022
        return []
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1023

1024
1025
1026
    skey = lambda tr: (tr.meta['super_group'], tr.meta['group'])

    trace_minmaxs = trace.minmax(all_syn_trs, skey)
Sebastian Heimann's avatar
Sebastian Heimann committed
1027

1028
    amp_spec_maxs = amp_spec_max(all_syn_specs, skey)
1029

1030
    dminmaxs = trace.minmax([x for x in dtraces if x is not None], skey)
Sebastian Heimann's avatar
Sebastian Heimann committed
1031
1032
1033

    for tr in dtraces:
        if tr:
1034
            dmin, dmax = dminmaxs[skey(tr)]
1035
            tr.ydata /= max(abs(dmin), abs(dmax))
Sebastian Heimann's avatar
Sebastian Heimann committed
1036
1037

    cg_to_targets = gather(
1038
1039
1040
        problem.targets,
        lambda t: (t.super_group, t.group, t.codes[3]),
        filter=lambda t: t in target_to_result)
Sebastian Heimann's avatar
Sebastian Heimann committed
1041
1042
1043

    cgs = sorted(cg_to_targets.keys())

1044
    figs = []
Sebastian Heimann's avatar
Sebastian Heimann committed
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
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
    for cg in cgs:
        targets = cg_to_targets[cg]
        nframes = len(targets)

        nx = int(math.ceil(math.sqrt(nframes)))
        ny = (nframes-1)/nx+1

        nxmax = 4
        nymax = 4

        nxx = (nx-1) / nxmax + 1
        nyy = (ny-1) / nymax + 1

        # nz = nxx * nyy

        xs = num.arange(nx) / ((max(2, nx) - 1.0) / 2.)
        ys = num.arange(ny) / ((max(2, ny) - 1.0) / 2.)

        xs -= num.mean(xs)
        ys -= num.mean(ys)

        fxs = num.tile(xs, ny)
        fys = num.repeat(ys, nx)

        data = []

        for target in targets:
            azi = source.azibazi_to(target)[0]
            dist = source.distance_to(target)
            x = dist*num.sin(num.deg2rad(azi))
            y = dist*num.cos(num.deg2rad(azi))
            data.append((x, y, dist))

        gxs, gys, dists = num.array(data, dtype=num.float).T

        iorder = num.argsort(dists)

        gxs = gxs[iorder]
        gys = gys[iorder]
        targets_sorted = [targets[ii] for ii in iorder]

        gxs -= num.mean(gxs)
        gys -= num.mean(gys)

        gmax = max(num.max(num.abs(gys)), num.max(num.abs(gxs)))
        if gmax == 0.:
            gmax = 1.

        gxs /= gmax
        gys /= gmax

        dists = num.sqrt(
            (fxs[num.newaxis, :] - gxs[:, num.newaxis])**2 +
            (fys[num.newaxis, :] - gys[:, num.newaxis])**2)

        distmax = num.max(dists)

        availmask = num.ones(dists.shape[1], dtype=num.bool)
        frame_to_target = {}
        for itarget, target in enumerate(targets_sorted):
            iframe = num.argmin(
                num.where(availmask, dists[itarget], distmax + 1.))
            availmask[iframe] = False
            iy, ix = num.unravel_index(iframe, (ny, nx))
            frame_to_target[iy, ix] = target

        figures = {}
        for iy in xrange(ny):
            for ix in xrange(nx):
                if (iy, ix) not in frame_to_target:
                    continue

                ixx = ix/nxmax
                iyy = iy/nymax
                if (iyy, ixx) not in figures:
1120
                    figures[iyy, ixx] = plt.figure(figsize=(16, 9))
1121
                    figs.append(figures[iyy, ixx])
Sebastian Heimann's avatar
Sebastian Heimann committed
1122
1123
1124
1125

                fig = figures[iyy, ixx]

                target = frame_to_target[iy, ix]
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1126

1127
                amin, amax = trace_minmaxs[target.super_group, target.group]
1128
                absmax = max(abs(amin), abs(amax))
Sebastian Heimann's avatar
Sebastian Heimann committed
1129
1130
1131
1132
1133
1134
1135

                ny_this = min(ny, nymax)
                nx_this = min(nx, nxmax)
                i_this = (iy % ny_this) * nx_this + (ix % nx_this) + 1

                axes2 = fig.add_subplot(ny_this, nx_this, i_this)

1136
1137
                space = 0.5
                space_factor = 1.0 + space
Sebastian Heimann's avatar
Sebastian Heimann committed
1138
                axes2.set_axis_off()
1139
                axes2.set_ylim(-1.05 * space_factor, 1.05)
Sebastian Heimann's avatar
Sebastian Heimann committed
1140
1141
1142

                axes = axes2.twinx()
                axes.set_axis_off()
1143
1144
1145
1146
1147

                if target.misfit_config.domain == 'cc_max_norm':
                    axes.set_ylim(-10. * space_factor, 10.)
                else:
                    axes.set_ylim(-absmax*1.33 * space_factor, absmax*1.33)
Sebastian Heimann's avatar
Sebastian Heimann committed
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158

                itarget = target_index[target]
                result = target_to_result[target]

                dtrace = dtraces[itarget]

                tap_color_annot = (0.35, 0.35, 0.25)
                tap_color_edge = (0.85, 0.85, 0.80)
                tap_color_fill = (0.95, 0.95, 0.90)

                plot_taper(
1159
                    axes2, result.processed_obs.get_xdata(), result.taper,
Sebastian Heimann's avatar
Sebastian Heimann committed
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
                    fc=tap_color_fill, ec=tap_color_edge)

                obs_color = scolor('aluminium5')
                obs_color_light = light(obs_color, 0.5)

                syn_color = scolor('scarletred2')
                syn_color_light = light(syn_color, 0.5)

                misfit_color = scolor('scarletred2')
                weight_color = scolor('chocolate2')

1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
                cc_color = scolor('aluminium5')

                if target.misfit_config.domain == 'cc_max_norm':
                    tref = (result.filtered_obs.tmin +
                            result.filtered_obs.tmax) * 0.5

                    plot_dtrace(
                        axes2, dtrace, space, -1., 1.,
                        fc=light(cc_color, 0.5),
                        ec=cc_color)

                    plot_dtrace_vline(
                        axes2, tref, space, color=tap_color_annot)

1185
1186
                elif target.misfit_config.domain == 'frequency_domain':

1187
                    asmax = amp_spec_maxs[target.super_group, target.group]
1188
1189
                    fmin, fmax = \
                        target.misfit_config.get_full_frequency_range()
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203

                    plot_spectrum(
                        axes2,
                        result.spectrum_syn,
                        result.spectrum_obs,
                        fmin, fmax,
                        space, 0., asmax,
                        syn_color=syn_color,
                        obs_color=obs_color,
                        syn_lw=1.5,
                        obs_lw=1.0,
                        color_vline=tap_color_annot,
                        fontsize=fontsize)

1204
1205
1206
                else:
                    plot_dtrace(
                        axes2, dtrace, space, 0., 1.,
1207
                        fc=light(misfit_color, 0.3),
1208
                        ec=misfit_color)
Sebastian Heimann's avatar
Sebastian Heimann committed
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234

                plot_trace(
                    axes, result.filtered_syn,
                    color=syn_color_light, lw=1.5)

                plot_trace(
                    axes, result.filtered_obs,
                    color=obs_color_light)

                plot_trace(
                    axes, result.processed_syn,
                    color=syn_color, lw=1.5)

                plot_trace(
                    axes, result.processed_obs,
                    color=obs_color)

                tmarks = [
                    result.processed_obs.tmin,
                    result.processed_obs.tmax]

                for tmark in tmarks:
                    axes2.plot(
                        [tmark, tmark], [-0.9, 0.1], color=tap_color_annot)

                for tmark, text, ha in [
1235
1236
                        (tmarks[0],
                         '$\,$ ' + str_duration(tmarks[0] - source.time),
Sebastian Heimann's avatar
Sebastian Heimann committed
1237
                         'right'),
1238
1239
                        (tmarks[1],
                         '$\Delta$ ' + str_duration(tmarks[1] - tmarks[0]),
Sebastian Heimann's avatar
Sebastian Heimann committed
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
                         'left')]:

                    axes2.annotate(
                        text,
                        xy=(tmark, -0.9),
                        xycoords='data',
                        xytext=(
                            fontsize*0.4 * [-1, 1][ha == 'left'],
                            fontsize*0.2),
                        textcoords='offset points',
                        ha=ha,
                        va='bottom',
                        color=tap_color_annot,
                        fontsize=fontsize)

                rel_w = ws[itarget] / w_max
                rel_c = gcms[itarget] / gcm_max

                sw = 0.25
                sh = 0.1
                ph = 0.01

                for (ih, rw, facecolor, edgecolor) in [
                        (0, rel_w,  light(weight_color, 0.5), weight_color),
                        (1, rel_c,  light(misfit_color, 0.5), misfit_color)]:

                    bar = patches.Rectangle(
                        (1.0-rw*sw, 1.0-(ih+1)*sh+ph), rw*sw, sh-2*ph,
                        facecolor=facecolor, edgecolor=edgecolor,
                        zorder=10,
                        transform=axes.transAxes, clip_on=False)

                    axes.add_patch(bar)

Sebastian Heimann's avatar
Sebastian Heimann committed
1274
1275
1276
1277
1278
                scale_string = None

                if target.misfit_config.domain == 'cc_max_norm':
                    scale_string = 'Syn/obs scales differ!'

Sebastian Heimann's avatar
Sebastian Heimann committed
1279
                infos = []
Sebastian Heimann's avatar
Sebastian Heimann committed
1280
1281
1282
                if scale_string:
                    infos.append(scale_string)

Sebastian Heimann's avatar
Sebastian Heimann committed
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
                infos.append('.'.join(x for x in target.codes if x))
                dist = source.distance_to(target)
                azi = source.azibazi_to(target)[0]
                infos.append(str_dist(dist))
                infos.append(u'%.0f\u00B0' % azi)
                infos.append('%.3g' % ws[itarget])
                infos.append('%.3g' % gcms[itarget])
                axes2.annotate(
                    '\n'.join(infos),
                    xy=(0., 1.),
                    xycoords='axes fraction',
                    xytext=(2., 2.),
                    textcoords='offset points',
                    ha='left',
                    va='top',
                    fontsize=fontsize,
                    fontstyle='normal')

        for (iyy, ixx), fig in figures.iteritems():
            title = '.'.join(x for x in cg if x)
            if len(figures) > 1:
                title += ' (%i/%i, %i/%i)' % (iyy+1, nyy, ixx+1, nxx)

            fig.suptitle(title, fontsize=fontsize)

1308
    return figs
Sebastian Heimann's avatar
Sebastian Heimann committed
1309
1310


1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
def draw_hudson_figure(model, plt):

    color = 'black'
    fontsize = 12.
    markersize = fontsize * 1.5
    markersize_small = markersize * 0.2
    beachballsize = markersize
    beachballsize_small = beachballsize * 0.5
    width = 7.
    figsize = (width, width / (4./3.))

    problem = model.problem
Sebastian Heimann's avatar
Sebastian Heimann committed
1323
1324
    mean_source = core.get_mean_source(problem, model.xs)
    best_source = core.get_best_source(problem, model.xs, model.misfits)
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373

    fig = plt.figure(figsize=figsize)
    axes = fig.add_subplot(1, 1, 1)

    data = []
    for ix, x in enumerate(model.xs):
        source = problem.unpack(x)
        mt = source.pyrocko_moment_tensor()
        u, v = hudson.project(mt)

        if random.random() < 0.1:
            try:
                beachball.plot_beachball_mpl(
                    mt, axes,
                    beachball_type='dc',
                    position=(u, v),
                    size=beachballsize_small,
                    color_t=color,
                    alpha=0.5,
                    zorder=1,
                    linewidth=0.25)
            except beachball.BeachballError, e:
                logger.warn(str(e))

        else:
            data.append((u, v))

    if data:
        u, v = num.array(data).T
        axes.plot(
            u, v, 'o',
            color=color,
            ms=markersize_small,
            mec='none',
            mew=0,
            alpha=0.25,
            zorder=0)

    hudson.draw_axes(axes)

    mt = mean_source.pyrocko_moment_tensor()
    u, v = hudson.project(mt)

    beachball.plot_beachball_mpl(
        mt, axes,
        beachball_type='dc',
        position=(u, v),
        size=beachballsize,
        color_t=color,
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1374
        zorder=2,
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
        linewidth=0.5)

    mt = best_source.pyrocko_moment_tensor()
    u, v = hudson.project(mt)

    axes.plot(
        u, v, 's',
        markersize=markersize,
        mew=1,
        mec='black',
        color='none',
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
        zorder=-2)

    mt = problem.base_source.pyrocko_moment_tensor()
    u, v = hudson.project(mt)

    beachball.plot_beachball_mpl(
        mt, axes,
        beachball_type='dc',
        position=(u, v),
        size=beachballsize,
        color_t='red',
        zorder=2,
        linewidth=0.5)
1399

1400
1401
    return [fig]

1402

Sebastian Heimann's avatar
Sebastian Heimann committed
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
def xpop(s, k):
    try:
        s.remove(k)
        return k

    except KeyError:
        return None


plot_dispatch = {
    'bootstrap': draw_bootstrap_figure,
    'sequence': draw_sequence_figures,
    'contributions': draw_contributions_figure,
    'jointpar': draw_jointpar_figures,
1417
    'hudson': draw_hudson_figure,
Sebastian Heimann's avatar
Sebastian Heimann committed
1418
1419
1420
1421
    'fits': draw_fits_figures,
    'solution': draw_solution_figure}


1422
def save_figs(figs, plot_dirname, plotname, formats, dpi):
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
    for fmt in formats:
        if fmt not in ['pdf', 'png']:
            raise core.GrondError('unavailable output format: %s' % fmt)

    assert re.match(r'^[a-z_]+$', plotname)

    # remove files from previous runs
    pat = re.compile(r'^%s-[0-9]+\.(%s)$' % (plotname, '|'.join(formats)))
    if op.exists(plot_dirname):
        for entry in os.listdir(plot_dirname):
            if pat.match(entry):
                os.unlink(op.join(plot_dirname, entry))

1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
    fns = []
    for ifig, fig in enumerate(figs):
        for format in formats:
            fn = op.join(plot_dirname, '%s-%02i.%s' % (plotname, ifig, format))
            util.ensuredirs(fn)

            fig.savefig(fn, format=format, dpi=dpi)
            logger.info('figure saved: %s' % fn)
            fns.append(fn)

    return fns


def available_plotnames():
    return list(plot_dispatch.keys())


def plot_result(dirname, plotnames_want,
                save=False, formats=('pdf',), dpi=None):

    if isinstance(formats, basestring):
        formats = formats.split(',')

Sebastian Heimann's avatar
Sebastian Heimann committed
1459
1460
1461
    plotnames_want = set(plotnames_want)
    plotnames_avail = set(plot_dispatch.keys())

1462
1463
    plot_dirname = op.join(dirname, 'plots')

Sebastian Heimann's avatar
Sebastian Heimann committed
1464
1465
1466
1467
1468
1469
    unavailable = plotnames_want - plotnames_avail
    if unavailable:
        raise core.GrondError(
            'unavailable plotname: %s' % ', '.join(unavailable))

    mpl_init()
1470
    fns = []
Sebastian Heimann's avatar
Sebastian Heimann committed
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481

    if 3 != len({'bootstrap', 'sequence', 'contributions'} - plotnames_want):
        problem, xs, misfits = core.load_problem_info_and_data(
            dirname, subset=None)

        model = GrondModel()
        model.set_problem(problem)
        model.append(xs, misfits)

        for plotname in ['bootstrap', 'sequence', 'contributions']:
            if plotname in plotnames_want:
1482
1483
1484
1485
                figs = plot_dispatch[plotname](model, plt)
                if save:
                    fns.extend(
                        save_figs(figs, plot_dirname, plotname, formats, dpi))
Sebastian Heimann's avatar
Sebastian Heimann committed
1486

1487
    if 4 != len({'fits', 'jointpar', 'hudson', 'solution'} - plotnames_want):
Sebastian Heimann's avatar
Sebastian Heimann committed
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
        problem, xs, misfits = core.load_problem_info_and_data(
            dirname, subset='harvest')

        model = GrondModel()
        model.set_problem(problem)
        model.append(xs, misfits)

        for plotname in ['fits']:
            if plotname in plotnames_want:
                config = guts.load(filename=op.join(dirname, 'config.yaml'))
                config.set_basepath(dirname)
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1499
                problem.set_engine(config.engine_config.get_engine())
Sebastian Heimann's avatar
Sebastian Heimann committed
1500
                ds = config.get_dataset()
1501
1502
1503
1504
                figs = plot_dispatch[plotname](ds, model, plt)
                if save:
                    fns.extend(
                        save_figs(figs, plot_dirname, plotname, formats, dpi))
Sebastian Heimann's avatar
Sebastian Heimann committed
1505

1506
        for plotname in ['jointpar', 'hudson', 'solution']:
Sebastian Heimann's avatar
Sebastian Heimann committed
1507
            if plotname in plotnames_want:
1508
1509
1510
1511
                figs = plot_dispatch[plotname](model, plt)
                if save:
                    fns.extend(
                        save_figs(figs, plot_dirname, plotname, formats, dpi))
Sebastian Heimann's avatar
Sebastian Heimann committed
1512

1513
1514
    if not save:
        plt.show()