ref_source.rake = 0

sources = du.test_event_generator(ref_source, depths)

channels = 'Z'
targets = [Target(lat=ref_source.lat, 
                  lon=ref_source.lon,
                  north_shift=north_shift,
                  store_id=store_id,
                  codes=('','','',channel)) for channel in channels for north_shift in
                                                      distances] 
resp = e.process(sources=sources, targets=targets)
tracs = du.response_to_dict(resp)

stf = [[0.,0.15],[0.,1.]]
du.apply_stf(tracs, stf)

tmin_arrivals = defaultdict()
tmax = 5
dt = e.get_store(store_id).config.sample_rate
tmax_samples = tmax*dt
ymaxs = defaultdict(list)


phase_ids = ['p', 'pP', 'P', 'sP']
all_ars = defaultdict()
for d in distances:
    for z in depths:
        print d,z
        ts = []
        key = (d, z)
def doit(sdr=None):
    azimutti = num.linspace(0,360, 31)
    tmax = 2.
    f = plt.figure(figsize=(2.,2.1))
    ax = f.add_subplot(111, polar=True)
    AZIMS = []
    DS=[]
    VALS=[]
    STATIONAZIMS= []
    STATIONDISTS = []

    ref_source = DCSource.from_pyrocko_event(ref_event)
    channels = 'Z'
    targets = [Target(lat=ref_source.lat, 
                      lon=ref_source.lon,
                      north_shift=north_shift,
                      store_id=store_id,
                      codes=('','','',channel)) for channel in channels for north_shift in
                                                          distances] 

    stations = model.load_stations(pjoin(derec_home, 'mseeds', 'doctar',
                                'doctar_2011-11-01', 'stations.txt'))
    doctar_targets = du.stations2targets(stations, store_id)

    for t in doctar_targets:
        az = t.azibazi_to(ref_source)
        d = t.distance_to(ref_source)
        STATIONAZIMS.append(az[1]*(num.pi/180))
        STATIONDISTS.append(d/1000.)

    if sdr is not None:
        ref_source.strike = sdr[0]
        ref_source.dip = sdr[1]
        ref_source.rake = sdr[2]

    st = ref_source.strike
    di = ref_source.dip
    ra = ref_source.rake

    for azim in azimutti:
        print azim
        z_intmin = defaultdict()
        ymin_int = defaultdict()
        ref_source.strike = azim
        sources = du.test_event_generator(ref_source, depths)

        resp = e.process(sources=sources, targets=targets)
        tracs = du.response_to_dict(resp)

        stf = [[0.,0.15],[0.,1.]]
        du.apply_stf(tracs, stf)

        tmin_arrivals = defaultdict()
        dt = e.get_store(store_id).config.sample_rate
        tmax_samples = tmax*dt
        ymaxs = defaultdict(list)

        phase_ids = ['p', 'pP', 'P']
        all_ars = defaultdict()
        for d in distances:
            for z in depths:
                ts = []
                key = (d, z)
                phases = map(cake.PhaseDef, phase_ids)

                for a in m.arrivals(phases=phases, distances=[d*cake.m2d], zstart=z):
                    ts.append(a)
                all_ars[(key)] = ts

                #tmin_arrivals[key] = min([tr.t for tr in ts])
                tmin_arrivals[key] = pc.cake_first_arrival(d, z, m, phase_ids)

        sources_dict = defaultdict()

        axes_dict = defaultdict(dict)
        #for t in targets:
        #    fig, axs = plt.subplots(len(sources), 1, sharey=True, figsize=(4,3), dpi=160)
        #    fig.myadjustment = False
        #    ad = dict(zip(sources, axs))
        #    axes_dict[t] = ad

        for s, tt in tracs.items():
            # das muss vor die loop fuer stacking
            for t, tr in tt.items():
                #ax = axes_dict[t][s]
                d = s.distance_to(t)
                z = s.depth

                tr.lowpass(2, 4)
                tr.highpass(4, 0.5)
                x = tr.get_xdata()-ref_source.time-tmin_arrivals[(d,z)]
                y = tr.get_ydata()
                x0_i = num.where(abs(x)==min(abs(x)))
                #/prinprint 'has to be single value: ', x0_i
                if len(x0_i)!=1:
                    print "WAAAARNING"

                x0_i = x0_i[0][0]
                y_plot = y[x0_i:x0_i+tmax_samples]

                y_int = num.sum((y_plot**2))/tmax_samples

                try:
                    if y_int<ymin_int[d]:
                        ymin_int[d] = y_int
                        z_intmin[d] = s.depth
                except KeyError: 
                    ymin_int[d] = y_int
                    z_intmin[d] = s.depth

        #for d, minz in z_intmin.items():
        azim = azim/180*num.pi
        azims = [azim]*len(z_intmin.keys())
        d = z_intmin.keys()
        vals = z_intmin.values()
        DS.extend(d)
        AZIMS.extend(azims)
        VALS.extend(vals)
    

    #VALS = 5.-num.array(VALS)/1000.
    #VALS = correct_depth-num.array(VALS)/1000.
    VALS = num.array(VALS)/1000.
    #DS = [d-ref_source.depth for d in DS]
    AZIMS = num.array(AZIMS)
    DS = num.array(DS)/1000.
    fn = 'polar_%s_%s_%s_%s.txt'%(test_type, st, di, ra) 
    num.savetxt(fn, num.array((AZIMS, DS, VALS)))