Example #1
0
def get_rbratios_tohoku(mc=5.0, todt=mhp.dtm.datetime.now(mhp.pytz.timezone('UTC')), winlen=None, avlen=None, targmag=9.0, ndithers=10, nContours=nContours1, bigmag=7.0, lons=[135., 148.5], lats=[30., 45.25], refreshcat=True, dt0=mhp.dtm.datetime(1990,1,1, tzinfo=mhp.pytz.timezone('UTC')), catname='cats/tohoku_rfits.cat', mt=7.6):
	#
	# fetch and return a standard rb-ratio set.
	#
	if refreshcat==True:
		#cl1=yp.catfromANSS(lon=[92.0, 106.0],lat=[-9.0, 10.0], minMag=3.5, dates0=[yp.dtm.datetime(1990,1,1, tzinfo=pytz.timezone('UTC')), yp.dtm.datetime(2012,6,19, tzinfo=pytz.timezone('UTC'))], fout=catname)
		cl1=atp.catfromANSS(lon=lons,lat=lats, minMag=mc, dates0=[dtm.datetime(1990,1,1, tzinfo=pytz.timezone('UTC')), dtm.datetime.now(pytz.timezone('UTC'))], fout=catname)
	#
	plt.figure(1)
	plt.clf()
	
	c1=eqp.eqcatalog([])
	c1.mt=mt
	c1.loadCatFromFile(catname)
	c1.cat.sort(key = lambda x:x[0])
	dlambda=1.76
	N_sequence = rfp.getNofm(targmag, mc)
	if avlen==None: avlen = max(1,int(N_sequence/10))
	tohokuEvent=c1.getMainEvent()
	print "n_seq: %d" % N_sequence
	tohokuLatLon = tohokuEvent[1], tohokuEvent[2]
	Lr = 10.0**(.5*targmag - 1.76)
	lfactor=.5
	#
	c1.subcats+=[['r1', rfp.circularcat(c1.getcat(0), latlon=[tohokuEvent[1], tohokuEvent[2]], Rkm=Lr*lfactor)]]
	#
	#rbratios = c1.plotIntervalRatiosAx(winlen=N_sequence, cat=c1.getcat(1), hitThreshold=1.0, bigmag=9.0, thisAx=myaxes[i], ratios=None, delta_t=1, avlen=rbavelen, mainEv=mainshock, logZ=None, rbLegLoc=0, reverse=False)
	rbratios = c1.plotIntervalRatiosAx(winlen=N_sequence, cat=c1.getcat(1), hitThreshold=1.0, bigmag=9.0, thisAx=None, ratios=None, delta_t=1, avlen=avlen, mainEv=tohokuEvent, logZ=None, rbLegLoc=0, reverse=False)
	plt.figure(1)
	log_fact = math.log10(N_sequence)
	#
	#plt.plot(map(operator.itemgetter(0), rbratios), map(operator.itemgetter(5), rbratios), '-')
	plt.semilogy(map(operator.itemgetter(1), rbratios), [x[4]*1.0 for x in rbratios], 'k-', alpha=.8, zorder=11)
	
	return rbratios
Example #2
0
def rtree_test1(lons=[-124., -114.], lats=[30., 41.5], mc=3.0):
	#
	# get an earthquake catalog from ANSS:
	# def catfromANSS(lon=[135., 150.], lat=[30., 41.5], minMag=4.0, dates0=[dtm.datetime(2005,01,01, tzinfo=tzutc), None], Nmax=None, fout=None, rec_array=True):
	anss_cat = atp.catfromANSS(lon=lons, lat=lats, minMag=mc, dates0=[dtm.datetime(2000,01,01, tzinfo=atp.tzutc), None], Nmax=None, fout=None, rec_array=True)
	#
	#return anss_cat
	# now, set up an index. do we need a bunch of indices, or is that the whole point of this?
	#
	idx = index.Index()
	# our bounding box:
	left,bottom,right,top = lons[0], lats[0], lons[1], lats[1]
	bounds = (left, bottom, right, top)
	#
	# now, insert all item indices from anss_cat into idx. nominally, we could insert the row as an object, or an index as an object... or we can synch the id with the
	# row index, and use the id as the index. note we insert elements as points, with left=right, top=bottom.
	[idx.insert(j, (rw['lon'], rw['lat'], rw['lon'], rw['lat'])) for j,rw in enumerate(anss_cat)]
	#
	# now, how 'bout find each point's NN:
	NN_1s=[list(idx.nearest((rw['lon'], rw['lat'], rw['lon'], rw['lat']),1)) for j,rw in enumerate(anss_cat)]
	NN_2s=[list(idx.nearest((rw['lon'], rw['lat'], rw['lon'], rw['lat']),2)) for j,rw in enumerate(anss_cat)]
	#
	idx2 = index.Index()
	idx2.insert(0, (0.,0.,1.,1.))
	idx2.insert(1, (1.5,.5,1.5,.5))		# point at 1.5,.5
	idx2.insert(2, (.5, 1.5, .5, 1.5))	# point at .5, 1.5
	#
	# note, if we are looking for NNs to an object in the database (index), it will find itself first. this is not "find the NNs of object X in the index";
	# the object/window is independent and external.
	print "indersections: ", list(idx2.intersection((0.,0.,1.,1.)))
	print "NNs:         : ", list(idx2.nearest((0.,0.,1.,1.),2))
	#
	return NN_1s, NN_2s
Example #3
0
def pull_region_history(lon_range,
                        lat_range,
                        mc=4.5,
                        date_range=['1990-1-1', None]):

    minlon = lon_range[0]
    maxlon = lon_range[1]
    minlat = lat_range[0]
    maxlat = lat_range[1]

    if date_range[1] == None:
        date_range[1] = dtm.datetime.now(pytz.timezone('UTC'))
    #
    for j, dt in enumerate(date_range):
        if isinstance(dt, str):
            date_range[j] = mpd.num2date(mpd.datestr2num(dt))
        #
    #
    start_date = date_range[0]
    end_date = date_range[1]

    incat = atp.catfromANSS(lon=[minlon, maxlon],
                            lat=[minlat, maxlat],
                            minMag=mc,
                            dates0=[start_date, end_date],
                            Nmax=None,
                            fout=None,
                            rec_array=True)

    return incat
Example #4
0
def nepal_bm_decorator(cm=None, prams = nepal_ETAS_prams, fnum=0, map_res='i', big_mag=6.28, hours_after=None, **kwargs):
	cm = (cm or nepal_basemap())
	prams.update(kwargs)
	#
	lons_nepal = [83., 87.]
	
	todt=prams.get('todt', None)
	catlen=prams.get('catlen', 5.*365.)
	lons=prams['lons']
	lats=prams['lats']
	mc = prams['mc']
	#
	if todt==None: todt = dtm.datetime.now(pytz.timezone('UTC'))
	dt0 = todt - dtm.timedelta(days=catlen)
	
	# get a catalog:
	cat_0 = atp.catfromANSS(lon=lons, lat=lats, minMag=mc, dates0=[dt0, todt], fout=None, rec_array=True)
	#print cat_0[0:5]
	#print list(cm(cat_0[0][2], cat_0[0][1]))
	quakes_map = [[rw[0]] + list(cm(rw[2], rw[1])) + [rw[3]] for rw in cat_0]
	
	max_mag = max([m for m in zip(*cat_0)[3]])
	print("max magnitude: ", max_mag)
	for rw in cat_0:
		if rw[3]==max_mag:
			mainshock = rw
			break
	# make a datetime type for mainshock:
	mainshock_dtm = numpy_date_to_datetime(mainshock[0])
	if hours_after!=None:
		time_after = dtm.timedelta(hours=hours_after)
	else:
		time_after = my_now()-mainshock_dtm
	#
	cat_big = [x for x in cat_0 if (x[3]>big_mag and x[0]>mainshock[0] and x!=mainshock)]		# just big aftershocks...
	#
	plt.plot([mainshock[2]], [mainshock[1]], 'r*', ms=17, zorder=6)
	plt.plot([mainshock[2]], [mainshock[1]], 'k*', ms=20, zorder=5)
	plt.plot(*list(zip(*[[rw[1], rw[2]] for rw in quakes_map if rw[0]<mainshock[0]])), marker='o', ms=5, ls='', color='r', zorder=5, label='befores')
	#
	plt.plot(*list(zip(*[[rw[1], rw[2]] for rw in quakes_map if (rw[0]>mainshock[0] and rw[0]<mainshock[0].tolist()+time_after)])), marker='o', ls='', ms=5, color='b', zorder=5, label='afters')
	#
	# ... and the big ones:
	for rw in cat_big:
		print(rw)
		dt=rw[0].tolist()
		#
		plt.plot([rw[2]], [rw[1]], 'o', ms=15.*(rw[3]/8.), label='m=%.2f, %d/%d' % (rw[3], dt.month, dt.day), zorder=6, alpha=.6)
	
	#
	plt.legend(loc=0, numpoints=1)
	
	return cm
Example #5
0
def mpi_cat(lons=[-123., -114.], lats=[31.5, 43.], mc=2.5, date_range=None, cat_len=10.*365.25):
	#
	date_range = (date_range or [None, None])
	date_range[0] = (date_range[0] or dtm.datetime.now(pytz.timezone('UTC'))-dtm.timedelta(days=cat_len))
	date_range[1] = (date_range[1] or dtm.datetime.now(pytz.timezone('UTC')))
	#
	#
	cat0 = atp.catfromANSS(lon=lons, lat=lats, minMag=mc, dates0=date_range, Nmax=None, fout=None, rec_array=True)
	#
	# but for now, something simpler...
	n_cpu = mpp.cpu_count()
	ary = mpp.Array(list(range(10*n_cpu)))
	
	#
	return cat0
Example #6
0
def rtree_test2(lons=[-124., -114.], lats=[30., 41.5], anss_cat=None, mc=3.0):
	#
	# get an earthquake catalog from ANSS:
	# def catfromANSS(lon=[135., 150.], lat=[30., 41.5], minMag=4.0, dates0=[dtm.datetime(2005,01,01, tzinfo=tzutc), None], Nmax=None, fout=None, rec_array=True):
	# use rtree index to select objects (earthquakes) from a geo-spatial region.
	# note also nearest-neighbor test script(s).
	if anss_cat==None: anss_cat = atp.catfromANSS(lon=lons, lat=lats, minMag=mc, dates0=[dtm.datetime(2000,01,01, tzinfo=atp.tzutc), None], Nmax=None, fout=None, rec_array=True)
	cols, formats = [list(x) for x in zip(*anss_cat.dtype.descr)]
	#
	print "catalog fetched. now set up index..."
	#
	#return anss_cat
	# now, set up an index. do we need a bunch of indices, or is that the whole point of this?
	#
	idx = index.Index()
	# our bounding box:
	left,bottom,right,top = lons[0], lats[0], lons[1], lats[1]
	bounds = (left, bottom, right, top)
	#print "bounds: ", bounds
	#return anss_cat
	#
	# now, insert all item indices from anss_cat into idx. nominally, we could insert the row as an object, or an index as an object... or we can synch the id with the
	# row index, and use the id as the index. note we insert elements as points, with left=right, top=bottom.
	[idx.insert(j, (rw['lon'], rw['lat'], rw['lon'], rw['lat'])) for j,rw in enumerate(anss_cat)]
	# 
	# now, we can use idx to get the index (row number) of elements inside some bounding rectangle like (i think):
	# note: height, width, etc. have to be defined. this is basically pseudo-code at this point.
	ev_x = numpy.mean(lons)
	ev_y = numpy.mean(lats)
	zone_width = .3*abs(lons[1]-lons[0])
	zone_height =  .3*abs(lats[1]-lats[0])
	print "mean position: ", ev_x, ev_y, zone_width, zone_height
	#
	event_neighbor_indices = list(idx.intersection((ev_x-zone_width, ev_y-zone_height, ev_x + zone_width, ev_y+zone_height)))
	event_neighbors = [anss_cat[j] for j in event_neighbor_indices]
	lat_index = cols.index('lat')
	lon_index = cols.index('lon')
	#
	zone_box = [[ev_x-zone_width, ev_y-zone_height],[ev_x+zone_width, ev_y-zone_height], [ev_x+zone_width, ev_y+zone_height], [ev_x-zone_width, ev_y+zone_height], [ev_x-zone_width, ev_y-zone_height]]
	#
	plt.figure(0)
	plt.clf()
	plt.plot(anss_cat['lon'], anss_cat['lat'], '.', color='b')
	plt.plot(*zip(*zone_box), color='g',  ls='--', lw=1.5, alpha=.8)
	plt.plot(*zip(*[[anss_cat[k][lon_index], anss_cat[k][lat_index]] for k in event_neighbor_indices]), marker = '+', ls='', color='g', alpha=.7)
	plt.plot([ev_x], [ev_y], '*', ms=15, color='r')
	#
	return anss_cat, idx
Example #7
0
	def __init__(self, lat_min=31., lat_max=42., lon_min=-125., lon_max=-115., mc=3.0, grid_dx=10., grid_dy=10., grid_units='km', date_min=dtm.datetime(1990,1,1, tzinfo=pytz.timezone('UTC')), date_max=None, N_max=None, cat_out_file=None):
		# make a lattice of grid sites (really points with some spacing; for now, assume rectalinearly equal spacing).
		# get a catalog of earthquakes; create an auxilary catalog as well.
		#
		self.lat_min=lat_min
		self.lat_max=lat_max
		self.lon_min=lon_min
		self.lon_max=lon_max
		self.mc=mc
		self.grid_dx = grid_dx
		self.grid_dy = grid_dy
		self.grid_units=grid_units
		self.date_min=date_min
		self.date_max=date_max		# note: these may differ from the values in the catalog, so we might want to write some code/commentary to be specific.
		self.N_max=N_max
		self.cat_out_file=cat_out_file
		#
		self.catalog = atp.catfromANSS(lon=[lon_min, lon_max], lat=[lat_min, lat_max], minMag=mc, dates0=[date_min, date_max], Nmax=N_max, fout=cat_out_file, rec_array=True)
Example #8
0
def pull_region_history(lon_range, lat_range, mc=4.5, date_range=['1990-1-1', None]):

	minlon = lon_range[0]
	maxlon = lon_range[1]
	minlat = lat_range[0]
	maxlat = lat_range[1]
	
	if date_range[1]==None: date_range[1] = dtm.datetime.now(pytz.timezone('UTC'))
	#
	for j,dt in enumerate(date_range):
		if isinstance(dt, str):
			date_range[j] = mpd.num2date(mpd.datestr2num(dt))
		#
	#
	start_date = date_range[0]
	end_date = date_range[1]
	
	incat = atp.catfromANSS(lon=[minlon, maxlon], lat=[minlat, maxlat], minMag=mc, dates0=[start_date, end_date], Nmax=None, fout=None, rec_array=True)
	
	return incat
Example #9
0
 def __init__(self,
              lat_min=31.,
              lat_max=42.,
              lon_min=-125.,
              lon_max=-115.,
              mc=3.0,
              grid_dx=10.,
              grid_dy=10.,
              grid_units='km',
              date_min=dtm.datetime(1990, 1, 1,
                                    tzinfo=pytz.timezone('UTC')),
              date_max=None,
              N_max=None,
              cat_out_file=None):
     # make a lattice of grid sites (really points with some spacing; for now, assume rectalinearly equal spacing).
     # get a catalog of earthquakes; create an auxilary catalog as well.
     #
     self.lat_min = lat_min
     self.lat_max = lat_max
     self.lon_min = lon_min
     self.lon_max = lon_max
     self.mc = mc
     self.grid_dx = grid_dx
     self.grid_dy = grid_dy
     self.grid_units = grid_units
     self.date_min = date_min
     self.date_max = date_max  # note: these may differ from the values in the catalog, so we might want to write some code/commentary to be specific.
     self.N_max = N_max
     self.cat_out_file = cat_out_file
     #
     self.catalog = atp.catfromANSS(lon=[lon_min, lon_max],
                                    lat=[lat_min, lat_max],
                                    minMag=mc,
                                    dates0=[date_min, date_max],
                                    Nmax=N_max,
                                    fout=cat_out_file,
                                    rec_array=True)
Example #10
0
def gr_thing(lats=[31., 43.], lons=[-126., -114.], mc=3.0, t0=dtm.datetime(1990,1,1, tzinfo=pytz.timezone('UTC')), t1=dtm.datetime.now(pytz.timezone('UTC')), m0=6.0, b0=1.0):
	N0=1000.
	cat = ANSStools.catfromANSS(lon=lons, lat=lats, minMag=mc, dates0=[t0, t1], Nmax=None, fout=None, rec_array=True)
	#
	# nominally, we'd get some sort of spatial subcats, but we won't bother just yet.
	# now, get subcats between each of the m>m_0 events; plot, fit, etc.
	#
	my_axes = []
	for fnum in range(4):
		plt.figure(fnum)
		plt.clf()
		my_axes += [plt.gca()]
		if fnum<2: my_axes[-1].set_yscale('log')
	b=b0		# though later, we might fit this
	
	#
	#for best speed and memory performance, we should just walk through this, but this will be easier to code:
	#
	m_index = [[j,m] for j,m in enumerate(cat['mag']) if m>=m0]
	abmag = []
	#
	for j,rw in enumerate(m_index[1:]):
		# color for plotting (optinal):
		this_color = colors_[j%len(colors_)]
		#
		these_mags = sorted(cat['mag'][m_index[j][0]+1:rw[0]].copy())
		#
		if len(these_mags)<2:
			print("insufficient sequence length: %d" % len(these_mags))
			continue
		#
		these_mags.reverse()
		Ns = numpy.arange(1., len(these_mags)+1, 1.)
		my_axes[0].plot(these_mags, Ns, 'o-')
		#
		# now, scale these for stacking. scale counts to m0.
		m_start = cat['mag'][m_index[j][0]]
		m_stop  = cat['mag'][rw[0]]
		m_mean = .5*(m_start+m_stop)
		#
		#Ns_prime = [n*(10.**(b*(m0-m))) for n,m in zip(Ns, these_mags)]
		#Ns_prime = [n*(10.**(b*(m0-m_mean))) for n,m in zip(Ns, these_mags)]
		Ns_prime = [n*Ns[0]/Ns[-1] for n in Ns]
		delta_log_ratio = abs(math.log10(Ns_prime[0]/Ns_prime[-1]))/math.log10(Ns[-1])
		ms_prime = [m*delta_log_ratio for m in these_mags]
		#my_axes[1].plot(these_mags, Ns_prime, '.-')
		my_axes[1].plot(ms_prime, Ns_prime, '.-')
		#
		# fit for b values:
		#print "len[%d]: (%d/%d:%f): %d " % (j, m_index[j][0], rw[0], rw[1], len(these_mags))
		#
		fits = numpy.linalg.lstsq(numpy.array([[m,1.0] for m in these_mags]), numpy.log10(Ns))[0]
		print("fits: ", fits[0])
		abmag += [[fits[1], fits[0], m_index[j][1], rw[1]]]
		#
		my_axes[2].plot([m_index[j][1], rw[1]], [fits[1], fits[1]], 'o-', color=this_color)
		#my_axes[2].plot([fits[1]], [rw[1]], 'o', color=this_color)
		#
		my_axes[3].plot([m_index[j][1], rw[1]], [fits[0], fits[0]], 'o-', color=this_color)
		#my_axes[3].plot([fits[0]], [rw[1]], 'o', color=this_color)
		
	#
	print("b-values:\n median: %f, mean: %f \\pm %f" % (numpy.median([rw[1] for rw in abmag]), numpy.mean([rw[1] for rw in abmag]), numpy.std([rw[1] for rw in abmag])))
	#
	plt.figure(2)
	#plt.clf()
	#plt.plot(*zip(*[[rw[0], rw[2]] for rw in abmag]), marker='o', ls='')
	#plt.plot(*zip(*[[rw[0], rw[3]] for rw in abmag]), marker='o', ls='')
	plt.ylabel('a-val')
	plt.xlabel('magnitude $m$')
	plt.figure(3)
	#plt.clf()
	#plt.plot(*zip(*[[rw[1], rw[2]] for rw in abmag]), marker='o', ls='')
	#plt.plot(*zip(*[[rw[1], rw[3]] for rw in abmag]), marker='o', ls='')
	plt.ylabel('b-val')
	plt.xlabel('magnitude $m$')
	ax_bcdf = my_axes[3].twiny()
	bs = [rw[1] for rw in abmag]
	bs.sort()
	ax_bcdf.plot(range(1,len(bs)+1), bs, 's-', lw=2, alpha=.7)
	ax_bcdf.set_ylabel('$N<b$')
Example #11
0
def parkfield_pca(L_r_factor=3.0):
    # a test example using the parkfield earthquake. let's throw in some rtree as well.
    # catfromANSS(lon=[135., 150.], lat=[30., 41.5], minMag=4.0, dates0=[dtm.datetime(2005,01,01, tzinfo=tzutc), None], Nmax=None, fout=None, rec_array=True):
    #
    d_lambda = 1.76
    #
    parkfield = {
        'dt': dtm.datetime(2004,
                           9,
                           28,
                           17,
                           15,
                           24,
                           tzinfo=pytz.timezone('UTC')),
        'lat': 35.815,
        'lon': -120.374,
        'mag': 5.96
    }
    L_r = 10.**(parkfield['mag'] / 2. - d_lambda)
    d_lat = L_r_factor * L_r / 111.1
    d_lon = L_r_factor * L_r * math.cos(deg2rad * parkfield['lat']) / 111.1

    print "d_lat, d_lon: ", d_lat, d_lon
    #
    x = parkfield['lon']
    y = parkfield['lat']
    parkfield_cat_prams = {
        'lon': [x - d_lon, x + d_lon],
        'lat': [y - d_lat, y + d_lon],
        'minMag':
        1.5,
        'dates0': [
            dtm.datetime(2004, 9, 28, tzinfo=pytz.timezone('UTC')),
            dtm.datetime(2010, 9, 28, tzinfo=pytz.timezone('UTC'))
        ],
        'Nmax':
        None,
        'fout':
        None,
        'rec_array':
        True
    }
    #
    cat = atp.catfromANSS(**parkfield_cat_prams)
    #
    # i still don't get what this does...
    #my_pca = PCA(numpy.array(zip(cat['lon'], cat['lat'])))
    my_pca = ptp.yoda_pca(zip(cat['lon'],
                              cat['lat']))  # returns (eig_vals, eig_vecs)
    e_vals = my_pca[0]
    e_vecs = numpy.array(my_pca[1])
    #
    e_vals_n = e_vals / min(e_vals)
    #
    print "e_vecs:", e_vecs[0][0], e_vecs[0][1], e_vecs[1][0], e_vecs[1][1]
    circle_xy = simple_circle(x=x, y=y, r=L_r * L_r_factor / 111.1)
    #
    # a rotational transformation:
    #  elliptical distribution; a = r, b = {something < a}. this is distinct from the equal-area transform, in which a>r.
    #  note that for this transform, the initial rate-density is adjusted to the new (surface projection) area.
    mu_x, mu_y = [numpy.mean(col) for col in zip(*circle_xy)]
    #print "means: ", mu_x, mu_y
    #circle_xy_prime = numpy.dot([[rw[0]-mu_x, rw[1]-mu_y] for rw in circle_xy], e_vecs_prime)
    circle_xy_prime = [[rw[0] - mu_x, rw[1] - mu_y] for rw in circle_xy]
    #
    circle_xy_prime = [[
        numpy.dot(rw, e_vecs[0]) * e_vals_n[0],
        numpy.dot(rw, e_vecs[1]) * e_vals_n[1]
    ] for rw in circle_xy_prime]
    #circle_xy_prime = numpy.dot([[rw[0] + mu_x, rw[1]+mu_y] for rw in circle_xy_prime], zip(*e_vecs))
    #circle_xy_prime = numpy.dot(circle_xy_prime, e_vecs.transpose())
    circle_xy_prime = numpy.dot(circle_xy_prime, e_vecs)
    circle_xy_prime = [[j + mu_x, k + mu_y] for j, k in circle_xy_prime]

    #circle_xy_prime = numpy.dot(circle_xy_prime, zip(*e_vecs))
    #
    plt.figure(0)
    plt.clf()
    plt.plot(cat['lon'], cat['lat'], '.')
    plt.plot([x], [y], 'r*', ms=15)
    Lry = abs(L_r_factor * L_r / 111.1)
    Lrx = abs(Lry * math.cos(y * deg2rad))
    #
    Wts = [xx / max(e_vals) for xx in e_vals]
    print "Wts: ", Wts
    #e_vecs = e_vecs.transpose()

    #plt.plot([x, x + Lrx*e_vecs[0][0]], [y, y + Lry*e_vecs[0][1]], ls='-', marker='o', color='r')
    #plt.plot([x, x + Lrx*e_vecs[1][0]], [y, y + Lry*e_vecs[1][1]], ls='-', marker='^', color='m')

    plt.plot([x, x + Wts[0] * Lry * e_vecs[0][0]],
             [y, y + Wts[0] * Lry * e_vecs[0][1]],
             ls='-',
             marker='o',
             color='r')
    plt.plot([x, x + Wts[1] * Lry * e_vecs[1][0]],
             [y, y + Wts[1] * Lry * e_vecs[1][1]],
             ls='-',
             marker='^',
             color='m')
    plt.plot(*zip(*circle_xy), ls='-', marker='', lw=2.)
    plt.plot(*zip(*circle_xy_prime),
             ls='--',
             color='r',
             marker='',
             lw=1.5,
             alpha=.7,
             zorder=11)

    #plt.plot([x, x+Lrx*e_vecs[0][0]], [y, y + Lry*e_vecs[1][0]], ls='-', marker='o', color='r')
    #plt.plot([x, x+Lrx*e_vecs[0][1]], [y, y + Lry*e_vecs[1][1]], ls='-', marker='^', color='m')

    plt.figure(1)
    plt.clf()
    #plt.plot([0., Lrx*e_vecs[0][0]], [0., Lry*e_vecs[0][1]], '.-')
    #plt.plot([0., Lrx*e_vecs[1][0]], [0., Lry*e_vecs[1][1]], '.--')
    plt.plot([0., e_vecs[0][0]], [0., e_vecs[0][1]], '.-')
    plt.plot([0., e_vecs[1][0]], [0., e_vecs[1][1]], '.--')

    #
    return my_pca
Example #12
0
def etas_auto(lon_center=None, lat_center=None, d_lat_0=.25, d_lon_0=.5, dt_0=10, Lr_map_factor=5.0, mc=2.5, mc_0=None, dm_cat=2.0, gridsize=.1, to_dt=None, mainshock_dt=None, fnameroot='etas_auto', catlen=5.0*365.0, d_lambda=1.76, doplot=False, show_legend=True):
	'''
	# , Lr_as_factor=.5
	# a version of this exists also in ETASscripts.py, but for now let's just develop separately.
	#	
	# a starter script to auto-select some parameters for an ETAS run. in practice, give this script a center location (probably a mainshock epicenter).
	# the script will find the largest earthquake in that region and scale up an ETAS parameter set accordingly.
		# d_lat_0, d_lon_0, dt_0 are the starting catalog parameters (largest earthquake in d_lat_0 x d_lon_0 x dt_0 cube).
	#
	# i think this is an earlier version of a similar (nearly identical?) script in ETASscripts
	'''
	#
	lw=2.5
	# catch some default value exceptions:
	if dt_0==None: dt_0=10
	#
	_colors =  mpl.rcParams['axes.color_cycle']
	Lr_as_factor=.5
	#
	#if to_dt == None: to_dt = dtm.datetime.now(pytz.timezone('UTC'))
	to_dt = (to_dt or dtm.datetime.now(pytz.timezone('UTC')))
	mc_0  = (mc_0 or mc)
	mainshock_dt = (mainshock_dt or to_dt)
	#
	if lon_center==None and lat_center==None:
		# let's look for any large earthquake in the world. assume for this, mc
		mc_0=6.0
		lat_center = 0.
		lon_center = 0.
		d_lat_0 = 88.
		d_lon_0 = -180.
	#
	# get a preliminary catalog:
	#cat_0 = atp.catfromANSS(lon=[lon_center-d_lon_0, lon_center+d_lon_0], lat=[lat_center - d_lat_0, lat_center+d_lat_0], minMag=mc_0, dates0=[to_dt-dtm.timedelta(days=dt_0), to_dt], fout=None, rec_array=True)
	cat_0 = atp.catfromANSS(lon=[lon_center-d_lon_0, lon_center+d_lon_0], lat=[lat_center - d_lat_0, lat_center+d_lat_0], minMag=mc_0, dates0=[to_dt-dtm.timedelta(days=dt_0), mainshock_dt], fout=None, rec_array=True)
	# diagnostic: output catalog length
	print("catalog length: %d" % len(cat_0))
	#
	# if there are no events, we probably are looking for a long range ETAS, so let's look for ALL events in the full catlen interval:
	if len(cat_0)==1:
		print("empty catalog. search over the whole catalog length...")
		# note: when we return as a recarray, an empty array has length 1 (pull up an empty array and figure out the details some time).
		cat_0 = atp.catfromANSS(lon=[lon_center-d_lon_0, lon_center+d_lon_0], lat=[lat_center - d_lat_0, lat_center+d_lat_0], minMag=mc_0, dates0=[to_dt-dtm.timedelta(days=catlen), to_dt], fout=None, rec_array=True)
	#
	#biggest_earthquake = filter(lambda x: x['mag']==max(cat_0['mag']), cat_0)[0]
	print("fetch preliminary catalog; find *mainshock*")
	mainshock = {cat_0.dtype.names[j]:x for j,x in enumerate(filter(lambda x: x['mag']==max(cat_0['mag']), cat_0)[0])}
	#print "biggest event(s): ", mainshock
	#
	# now, get new map domain based on rupture length, etc.
	#L_r = .5*10.0**(.5*mainshock['mag'] - 1.76)
	L_r = Lr(mainshock['mag'], fact=Lr_as_factor, d_lambda=d_lambda)
	d_lat = Lr_map_factor*L_r/lon2km
	d_lon = Lr_map_factor*L_r/(lon2km*math.cos(deg2rad*mainshock['lat']))
	lats = [mainshock['lat']-d_lat, mainshock['lat']+d_lat]
	lons = [mainshock['lon']-d_lon, mainshock['lon']+d_lon]
	print("lats, lons: ", lats, lons, L_r)
	print("mainshock found: ", mainshock, ".\nNow, find aftershocks...")
	#
	#working_cat = atp.catfromANSS(lon=[mainshock['lon']-d_lon, mainshock['lon']+d_lon], lat=[mainshock['lat']-d_lat, mainshock['lat']+d_lat], minMag=mc, dates0=[to_dt-dtm.timedelta(days=catlen), to_dt], fout=None, rec_array=True)
	primary_cat = atp.catfromANSS(lon=lons, lat=lats, minMag=mc, dates0=[to_dt-dtm.timedelta(days=catlen), to_dt], fout=None, rec_array=True)
	#
	if not doplot: return primary_cat
	aftershock_cat = numpy.core.records.fromarrays(list(zip(*[rw for rw in primary_cat if rw['mag']>=(mainshock['mag']-dm_cat)])),dtype=primary_cat.dtype)
	
	#
	#cat_map = get_catalog_map(lats=lats, lons=lons, eq_cat = aftershock_cat)
	cat_map = get_catalog_map(lats=lats, lons=lons)
	#
	# now, let's draw circles around (some of) these events. this will be a bit sloppy, since we need to convert coordinates from dist -> lat/lon -> map.
	#
	for k,ev in enumerate(aftershock_cat):
		print("event: %d: " % k, ev)
		for j,lr_fact in enumerate([.5, 1.0]):
			lr = Lr(ev['mag'], fact=lr_fact, d_lambda=d_lambda)
			#as_circle = circle_geo(lon0=ev['lon'], lat0=ev['lat'], R=lr*1000., d_theta=None, N=250, units_theta='deg', R_units='m')
			#Xa, Ya = cat_map(*zip(*as_circle))
			#
			if j==0:
				line_style = '--'
			else:
				line_style='-'
			#
			Xa, Ya = cat_map(*list(zip(*circle_geo(lon0=ev['lon'], lat0=ev['lat'], R=lr*1000., d_theta=None, N=250, units_theta='deg', R_units='m'))))
			plt.plot(Xa, Ya, '%s' % line_style, zorder=7, color=_colors[k%len(_colors)], lw=lw)
		x,y = cat_map(ev['lon'], ev['lat'])
		ev_dtm = ev['event_date'].tolist()
		lbl_str = 'm=%.2f, %d-%d-%d %d:%d:%d' % (ev['mag'], ev_dtm.year, ev_dtm.month, ev_dtm.day, ev_dtm.hour,ev_dtm.minute,ev_dtm.second)
		#
		# plot pre-mainshock events as squares, post-mainshock events as circles:
		if ev['event_date']<mainshock['event_date']: marker_str = 's'
		if ev['event_date']==mainshock['event_date']: marker_str = '*'
		if ev['event_date']>mainshock['event_date']: marker_str = 'o'
		#
		plt.plot([x], [y], marker_str, ms=15.*ev['mag']/8.0, color=_colors[k%len(_colors)], label=lbl_str, zorder=7)
	if show_legend: plt.legend(loc=0, numpoints=1)
	plt.plot(*cat_map(primary_cat['lon'], primary_cat['lat']), marker='.', ls='', ms=3., zorder=5, alpha=.6)
	#
	# and for now, let's plot time-links (lines betwen sequential events):
	for k, ev in enumerate(aftershock_cat[1:]):
		X,Y = cat_map([aftershock_cat[k]['lon'], ev['lon']], [aftershock_cat[k]['lat'], ev['lat']])
		plt.plot(X,Y, '.-', ms=8, color=_colors[k%len(_colors)])
	#
	f=plt.figure(1)
	plt.clf()
	ax3d = f.add_axes([.1, .1, .8, .8], projection='3d')
	ax3d.plot(aftershock_cat['lon'], aftershock_cat['lat'], aftershock_cat['event_date_float'], 'o-')
	#z = [mpd.date2num(dt.tolist()) for dt in aftershock_cat['event_date']]
	#ax3d.plot(aftershock_cat['lat'][1:], aftershock_cat['lon'][1:], [x for x in (aftershock_cat['event_date_float'][1:]-mainshock['event_date_float'])], 'o-')
	#ax3d.plot(aftershock_cat['lat'][1:], aftershock_cat['lon'][1:], [math.log10(x-z[0]) for x in z[1:]], 'o-')
	ax3d.set_ylabel('latitude')
	ax3d.set_xlabel('longitude')
	ax3d.set_zlabel('time')
	#print "times: ", [x-z[0] for x in z[1:]]
	#
	f=plt.figure(2)
	plt.clf()
	ax3d2 = f.add_axes([.1, .1, .8, .8], projection='3d')
	ax3d2.plot(aftershock_cat['lon'][1:], aftershock_cat['lat'][1:], numpy.log10(aftershock_cat['event_date_float'][1:]-aftershock_cat['event_date_float'][0]), 'o-')
	#
	ax3d2.set_ylabel('latitude')
	ax3d2.set_xlabel('longitude')
	ax3d2.set_zlabel('$log(\\Delta t)$')
	#
	print("log(dt): ", numpy.log10(aftershock_cat['event_date_float'][1:]-aftershock_cat['event_date_float'][0]))
	#
	f=plt.figure(3)
	plt.clf()
	ax3d3 = f.add_axes([.1, .1, .8, .8], projection='3d')
	ax3d3.plot(aftershock_cat['lon'][0:], aftershock_cat['lat'][0:], aftershock_cat['depth'][0:], 'o-')
	ax3d3.set_ylabel('latitude')
	ax3d3.set_xlabel('longitude')
	ax3d3.set_zlabel('depth $z$')
	#
	#print "mainshock: ", mainshock, mainshock['event_date']
	cat = atp.catfromANSS(lon=lons, lat=lats, minMag=mc, dates0=[mpd.num2date(mainshock['event_date_float']-1.0), to_dt], fout=None, rec_array=True)
	f=plt.figure(4)
	plt.clf()
	ax3d = f.add_axes([.1, .1, .8, .8], projection='3d')
	ax3d.plot(cat['lon'], cat['lat'], cat['event_date_float'], 'o')
	#
	#
	ax3d.set_title('All quakes, lat, lon, time')
	ax3d.set_ylabel('latitude')
	ax3d.set_xlabel('longitude')
	ax3d.set_zlabel('time')
	
	#return aftershock_cat
	return primary_cat
Example #13
0
def doSumatra(mc=5.0, targmag=9.1, rbavelen=None, bigmag=9.5, intlist=None, catname='cats/sumatra.cat', refreshcat=False, plotevents=False, mt=7.55, lons=[92.0, 106.0],lats=[-9.0, 10.0], lfactor=.5):
	# get a bunch of sumatra fits from rbTectoFigs. we'll want analysis on 0, 2, 3
	#sumatra_catalog = rfp.sumatraQuad()
	
	cl1=atp.catfromANSS(lon=lons,lat=lats, minMag=mc, dates0=[dtm.datetime(1990,1,1, tzinfo=pytz.timezone('UTC')), dtm.datetime.now(pytz.timezone('UTC'))], fout=None)
	catalogs=[]
	#
	c1=eqp.eqcatalog(cl1)
	c1.mc=mc
	c1.mt=mt
	c1.targmag = targmag
	#
	c1.cat.sort(key = lambda x:x[0])
	dlambda=1.76
	Lr=10.0**(targmag/2.0 - dlambda)
	latlonMS=[3.316, 95.854]	#mainshock
	#mainshock = [dtm.datetime(2004, 12, 26, 0, 58, 53, 449995, tzinfo=pytz.timezone('UTC')),  3.295,  95.982,  9.0,  30.0]
	mainshock=c1.getMainEvent()
	mainshock[3]=9.1		#ANSS seems to be listing sumatra as 9.0 lately.
	mevIndex = mainshock[-1]
	#
	foreshocks = []
	foreshocks+=[mainshock[:]]
	foreshocks+=[mainshock[:]]
	#foreshocks+=[[dtm.datetime(2000, 6, 4, 16, 28, 26, 170001, tzinfo=pytz.timezone('UTC')), -4.721, 102.087, 7.9, 33.0]]
	#foreshocks+=[[dtm.datetime(2001, 2, 13, 19, 28, 30, 260001, tzinfo=pytz.timezone('UTC')), -4.68, 102.562, 7.4, 36.0]]
	#foreshocks+=[[dtm.datetime(2002, 11, 2, 1, 26, 10, 699996, tzinfo=pytz.timezone('UTC')), 2.824, 96.085, 7.4, 30.0]]
	#
	# adjust mainshock:
	foreshocks[0][1]+=0.
	foreshocks[0][2]-=0.
	#
	for i in xrange(mevIndex+1,len(c1.getcat(0))):
		if c1.getcat(0)[i][3]>=8.0:
			foreshocks+=[c1.getcat(0)[i]]
			print "large aftershock: ", c1.getcat(0)[i]
		
	#
	interesting_quads = [0,2,3]		# we know these are interesting...
	interesting_quads = range(len(foreshocks))
	for i in interesting_quads:
		#thiscatnum=i
		#thisfignum=i
		thismag=foreshocks[i][3]
		thisLr = 10.0**(thismag/2.0 - dlambda)
		#
		#if i>0:
		fsLatLon=[foreshocks[i][1], foreshocks[i][2]]
		#if i>0: c1.subcats+=[['r%d' %i, circularcat(c1.getcat(0), latlon=fsLatLon, Rkm=Lr*lfactor)]]
		catalogs+=[eqp.eqcatalog(rfp.circularcat(c1.getcat(0), latlon=fsLatLon, Rkm=Lr*lfactor))]
		catalogs[-1].mainshock = catalogs[-1].getMainEvent()
	#
	# some stuff we know:
	catalogs[0].mainshock[3] = targmag		# or 9.1... but anss sometimes reports this differently in think.
	#
	#
	fignum0=11
	current_fig = plt.figure(fignum0)
	#
	for i_catalog, catalog in enumerate(catalogs):
		#
		#mev = catalog.getMainEvent()
		mev = catalog.mainshock		# which we've added in this script. otherwise, use catalog.getMainEvent()
		print "mev: ", mev
		interval_len = rfp.winlen(m=mev[3], mc=mc, mt=mt, doInt=True)
		avlen = max(1,int(interval_len/10))
		#
		current_fig = plt.figure()
		plt.clf()
		catalog.rbomoriQuadPlot(targmag=mev[3], mc=mc, weighted=False, fignum=current_fig.number)
		#
		current_fig = plt.figure()
		plt.clf()
		catalog.rbomoriQuadPlot(targmag=mev[3], mc=mc, weighted=True, fignum=current_fig.number)
		#
		# poisson ratio limits:
		these_axes = current_fig.axes
		if len(these_axes)>=3:
			ax_rb = these_axes[2]		
			# poisson ratio bit:
			# this doesn't vary much, so for now just do a regular gr guess:
			n_rb_poisson = 10**(mev[3]-mc-2.0)
			poisson_ratio_0 = list(ratio_sigma(n_rb_poisson, 1.0))
			poisson_ratio_1 = list(ratio_sigma(n_rb_poisson, .5))
			print 'sigma_ratios: ', poisson_ratio_0, poisson_ratio_1
			#plt.figure(fignum0-1)
			for y in poisson_ratio_0 + poisson_ratio_1:
				#print catalog.getcat(0)[0]
				ax_rb.plot([catalog.getcat(0)[0][0], catalog.getcat(0)[-1][0]], [y, y], 'm-', lw=2)
		#
		#rbratios = catalog.getNRBratios(intervals=None, winlen=interval_len, delta_t=1, reverse=False)
		#rb_values = map(operator.itemgetter(4), rbratios)
		#mean_rbs = [numpy.mean(rb_values[max(i-interval_len, 0):i+1]) for i, x in enumerate(rb_values)]
		#for i,x in enumerate(mean_rbs): rbratios[i]+=[x]
		#
		#return rbratios
		#
		#fits = get_ratio_fits(ratios=rbratios, Nfits=[interval_len])
		#plotses = plot_ratio_fits(fits, new_figs=False, fignum0=fignum0)
		#fignum0+=4
	#
	#return (rbratios, rbratio_fits, rbf_plot)
	return None
Example #14
0
def parkfield_pca(L_r_factor=3.0):
	# a test example using the parkfield earthquake. let's throw in some rtree as well.
	# catfromANSS(lon=[135., 150.], lat=[30., 41.5], minMag=4.0, dates0=[dtm.datetime(2005,01,01, tzinfo=tzutc), None], Nmax=None, fout=None, rec_array=True):
	#
	d_lambda   = 1.76
	#
	parkfield={'dt':dtm.datetime(2004,9,28,17,15,24, tzinfo=pytz.timezone('UTC')), 'lat':35.815, 'lon':-120.374, 'mag':5.96}
	L_r = 10.**(parkfield['mag']/2. - d_lambda)
	d_lat = L_r_factor * L_r/111.1
	d_lon = L_r_factor * L_r*math.cos(deg2rad*parkfield['lat'])/111.1
	
	print "d_lat, d_lon: ", d_lat, d_lon
	#
	x=parkfield['lon']
	y=parkfield['lat']
	parkfield_cat_prams = {'lon':[x-d_lon, x+d_lon], 'lat':[y-d_lat, y+d_lon], 'minMag':1.5, 'dates0':[dtm.datetime(2004,9,28, tzinfo=pytz.timezone('UTC')), dtm.datetime(2010,9,28, tzinfo=pytz.timezone('UTC'))], 'Nmax':None, 'fout':None, 'rec_array':True}
	#
	cat = atp.catfromANSS(**parkfield_cat_prams)
	#
	# i still don't get what this does...
	#my_pca = PCA(numpy.array(zip(cat['lon'], cat['lat'])))
	my_pca = ptp.yoda_pca(zip(cat['lon'], cat['lat']))		# returns (eig_vals, eig_vecs)
	e_vals = my_pca[0]
	e_vecs = numpy.array(my_pca[1])
	#
	e_vals_n = e_vals/min(e_vals)
	#
	print "e_vecs:", e_vecs[0][0], e_vecs[0][1], e_vecs[1][0], e_vecs[1][1]
	circle_xy = simple_circle(x=x, y=y, r=L_r*L_r_factor/111.1)
	#
	# a rotational transformation:
	#  elliptical distribution; a = r, b = {something < a}. this is distinct from the equal-area transform, in which a>r.
	#  note that for this transform, the initial rate-density is adjusted to the new (surface projection) area.
	mu_x, mu_y = [numpy.mean(col) for col in zip(*circle_xy)]
	#print "means: ", mu_x, mu_y
	#circle_xy_prime = numpy.dot([[rw[0]-mu_x, rw[1]-mu_y] for rw in circle_xy], e_vecs_prime)
	circle_xy_prime = [[rw[0]-mu_x, rw[1]-mu_y] for rw in circle_xy]
	#
	circle_xy_prime = [[numpy.dot(rw,e_vecs[0])*e_vals_n[0], numpy.dot(rw, e_vecs[1])*e_vals_n[1]] for rw in circle_xy_prime]
	#circle_xy_prime = numpy.dot([[rw[0] + mu_x, rw[1]+mu_y] for rw in circle_xy_prime], zip(*e_vecs))
	#circle_xy_prime = numpy.dot(circle_xy_prime, e_vecs.transpose())
	circle_xy_prime = numpy.dot(circle_xy_prime, e_vecs)
	circle_xy_prime = [[j+mu_x, k+mu_y] for j,k in circle_xy_prime]

	#circle_xy_prime = numpy.dot(circle_xy_prime, zip(*e_vecs))
	#
	plt.figure(0)
	plt.clf()
	plt.plot(cat['lon'], cat['lat'], '.')
	plt.plot([x], [y], 'r*', ms=15)
	Lry = abs(L_r_factor * L_r/111.1)
	Lrx = abs(Lry*math.cos(y*deg2rad))
	#
	Wts = [xx/max(e_vals) for xx in e_vals]
	print "Wts: ", Wts
	#e_vecs = e_vecs.transpose()
	
	
	#plt.plot([x, x + Lrx*e_vecs[0][0]], [y, y + Lry*e_vecs[0][1]], ls='-', marker='o', color='r')
	#plt.plot([x, x + Lrx*e_vecs[1][0]], [y, y + Lry*e_vecs[1][1]], ls='-', marker='^', color='m')
	
	plt.plot([x, x + Wts[0]*Lry*e_vecs[0][0]], [y, y + Wts[0]*Lry*e_vecs[0][1]], ls='-', marker='o', color='r')
	plt.plot([x, x + Wts[1]*Lry*e_vecs[1][0]], [y, y + Wts[1]*Lry*e_vecs[1][1]], ls='-', marker='^', color='m')
	plt.plot(*zip(*circle_xy), ls='-', marker='', lw=2.)
	plt.plot(*zip(*circle_xy_prime), ls='--', color='r', marker='', lw=1.5, alpha=.7, zorder=11)
	
	
	#plt.plot([x, x+Lrx*e_vecs[0][0]], [y, y + Lry*e_vecs[1][0]], ls='-', marker='o', color='r')
	#plt.plot([x, x+Lrx*e_vecs[0][1]], [y, y + Lry*e_vecs[1][1]], ls='-', marker='^', color='m')
	
	plt.figure(1)
	plt.clf()
	#plt.plot([0., Lrx*e_vecs[0][0]], [0., Lry*e_vecs[0][1]], '.-')
	#plt.plot([0., Lrx*e_vecs[1][0]], [0., Lry*e_vecs[1][1]], '.--')
	plt.plot([0., e_vecs[0][0]], [0., e_vecs[0][1]], '.-')
	plt.plot([0., e_vecs[1][0]], [0., e_vecs[1][1]], '.--')
	
	
	#
	return my_pca
Example #15
0
def parkfield_pca(L_r_factor=3.0):
    # a test example using the parkfield earthquake. let's throw in some rtree as well.
    # catfromANSS(lon=[135., 150.], lat=[30., 41.5], minMag=4.0, dates0=[dtm.datetime(2005,01,01, tzinfo=tzutc), None], Nmax=None, fout=None, rec_array=True):
    #
    d_lambda = 1.76
    #
    parkfield = {
        'dt': dtm.datetime(2004,
                           9,
                           28,
                           17,
                           15,
                           24,
                           tzinfo=pytz.timezone('UTC')),
        'lat': 35.815,
        'lon': -120.374,
        'mag': 5.96
    }
    L_r = 10.**(parkfield['mag'] / 2. - d_lambda)
    d_lat = L_r_factor * L_r / 111.1
    d_lon = L_r_factor * L_r * math.cos(deg2rad * parkfield['lat']) / 111.1

    print("d_lat, d_lon: ", d_lat, d_lon)
    #
    x_pf = parkfield['lon']
    y_pf = parkfield['lat']
    parkfield_cat_prams = {
        'lon': [x_pf - d_lon, x_pf + d_lon],
        'lat': [y_pf - d_lat, y_pf + d_lon],
        'minMag':
        1.5,
        'dates0': [
            dtm.datetime(2004, 9, 28, tzinfo=pytz.timezone('UTC')),
            dtm.datetime(2010, 9, 28, tzinfo=pytz.timezone('UTC'))
        ],
        'Nmax':
        None,
        'fout':
        None,
        'rec_array':
        True
    }
    #
    cat = atp.catfromANSS(**parkfield_cat_prams)
    #
    # i still don't get what this does...
    #my_pca = PCA(numpy.array(zip(cat['lon'], cat['lat'])))
    my_pca = ptp.yoda_pca(list(zip(
        cat['lon'], cat['lat'])))  # returns (eig_vals, eig_vecs)
    e_vals = my_pca[0]
    e_vecs = numpy.array(my_pca[1])
    #
    #e_vals_n = e_vals/min(e_vals)
    e_vals_n = numpy.array([min(4.0, x / min(e_vals)) for x in e_vals])
    #
    print("e_vecs:", e_vecs[0][0], e_vecs[0][1], e_vecs[1][0], e_vecs[1][1])
    circle_xy = simple_circle(x=x, y=y, r=L_r * L_r_factor / 111.1)

    #T = numpy.array([[e_vals_n[j]*x for x in rw] for j,rw in enumerate(e_vecs)])
    #circle_xy_prime = numpy.dot(circle_xy,T.transpose())	# note: this syntax will add [x,y] to all members of circle_xy_prime like [[a+x,b+y], [a+x,b+y],...]

    T = numpy.dot([[e_vals_n[0], 0.], [0., e_vals_n[1]]], e_vecs)
    circle_xy_prime = numpy.dot(circle_xy, T)

    #circle_xy_prime = numpy.dot(circle_xy, [[e_vals_n[0],0.],[0., e_vals_n[1]]])
    #circle_xy_prime = numpy.dot(circle_xy_prime, e_vecs)

    #circle_xy = numpy.array(circle_xy)+numpy.array([x,y])
    circle_xy_prime = [[j + x_pf, k + y_pf] for j, k in circle_xy_prime]
    circle_xy = [[j + x_pf, k + y_pf] for j, k in circle_xy]
    #print "T: ", T
    #
    # a rotational transformation:
    #  elliptical distribution; a = r, b = {something < a}. this is distinct from the equal-area transform, in which a>r.
    #  note that for this transform, the initial rate-density is adjusted to the new (surface projection) area.
    #mu_x, mu_y = [numpy.mean(col) for col in zip(*circle_xy)]
    #print "means: ", mu_x, mu_y
    #circle_xy_prime = [[rw[0]-mu_x, rw[1]-mu_y] for rw in circle_xy]
    #
    #circle_xy_prime = [[numpy.dot(rw,e_vecs[0])*e_vals_n[0], numpy.dot(rw, e_vecs[1])*e_vals_n[1]] for rw in circle_xy_prime]
    #circle_xy_prime = numpy.dot([[rw[0] + mu_x, rw[1]+mu_y] for rw in circle_xy_prime], zip(*e_vecs))
    #circle_xy_prime = numpy.dot(circle_xy_prime, e_vecs.transpose())
    #circle_xy_prime = numpy.dot(circle_xy_prime, e_vecs)
    #circle_xy_prime = [[j+mu_x, k+mu_y] for j,k in circle_xy_prime]

    #circle_xy_prime = numpy.dot(circle_xy_prime, zip(*e_vecs))
    #
    plt.figure(0)
    plt.clf()
    plt.plot(cat['lon'], cat['lat'], '.', label='parkfield cat')
    plt.plot([x_pf], [y_pf], 'r*', ms=15)
    plt.legend(loc=0, numpoints=1)
    #
    plot_axes = (L_r / 111.2) * numpy.array([e_vecs[0], [0., 0.], e_vecs[1]
                                             ]) + numpy.array([x_pf, y_pf])
    plt.plot(*zip(*plot_axes), ls='-', marker='o')
    #
    Lry = abs(L_r_factor * L_r / 111.1)
    Lrx = abs(Lry * math.cos(y_pf * deg2rad))

    #
    Wts = [xx / max(e_vals) for xx in e_vals]
    print("Wts: ", Wts)
    #e_vecs = e_vecs.transpose()

    #plt.plot([x, x + Lrx*e_vecs[0][0]], [y, y + Lry*e_vecs[0][1]], ls='-', marker='o', color='r')
    #plt.plot([x, x + Lrx*e_vecs[1][0]], [y, y + Lry*e_vecs[1][1]], ls='-', marker='^', color='m')
    '''
	#<<<<<<< HEAD
	plt.plot([x, x + Wts[0]*Lry*e_vecs[0][0]], [y, y + Wts[0]*Lry*e_vecs[0][1]], ls='-', marker='o', color='r')
	plt.plot([x, x + Wts[1]*Lry*e_vecs[1][0]], [y, y + Wts[1]*Lry*e_vecs[1][1]], ls='-', marker='^', color='m')
	plt.plot(*list(zip(*circle_xy)), ls='-', marker='', lw=2.)
	plt.plot(*list(zip(*circle_xy_prime)), ls='--', color='r', marker='', lw=1.5, alpha=.7, zorder=11)
	#=======
	'''
    #ax1 = numpy.dot(

    plt.plot([x_pf, x_pf + Wts[0] * Lry * e_vecs[0][0]],
             [y_pf, y_pf + Wts[0] * Lry * e_vecs[0][1]],
             ls='-',
             marker='o',
             color='r')
    plt.plot([x_pf, x_pf + Wts[1] * Lry * e_vecs[1][0]],
             [y_pf, y_pf + Wts[1] * Lry * e_vecs[1][1]],
             ls='-',
             marker='^',
             color='m')

    plt.plot(*zip(*circle_xy), ls='-', marker='', lw=2.)
    plt.plot(*zip(*circle_xy_prime),
             ls='--',
             color='r',
             marker='',
             lw=1.5,
             alpha=.7,
             zorder=11)

    #plt.plot([x, x+Lrx*e_vecs[0][0]], [y, y + Lry*e_vecs[1][0]], ls='-', marker='o', color='r')
    #plt.plot([x, x+Lrx*e_vecs[0][1]], [y, y + Lry*e_vecs[1][1]], ls='-', marker='^', color='m')

    plt.figure(1)
    plt.clf()
    #plt.plot([0., Lrx*e_vecs[0][0]], [0., Lry*e_vecs[0][1]], '.-')
    #plt.plot([0., Lrx*e_vecs[1][0]], [0., Lry*e_vecs[1][1]], '.--')
    #plt.plot([0., e_vecs[0][0]], [0., e_vecs[0][1]], '.-')
    #plt.plot([0., e_vecs[1][0]], [0., e_vecs[1][1]], '.--')
    plt.plot(*zip([0., 0.], e_vecs[0]), marker='.', ls='--')
    plt.plot(*zip([0., 0.], e_vecs[1]), marker='^', ls='-')

    plt.plot(*zip([0., 0.], T[0]), marker='.', ls='--')
    plt.plot(*zip([0., 0.], T[1]), marker='^', ls='-')

    #
    return my_pca
Example #16
0
def parkfield_pca(L_r_factor=3.0):
	# a test example using the parkfield earthquake. let's throw in some rtree as well.
	# catfromANSS(lon=[135., 150.], lat=[30., 41.5], minMag=4.0, dates0=[dtm.datetime(2005,01,01, tzinfo=tzutc), None], Nmax=None, fout=None, rec_array=True):
	#
	d_lambda   = 1.76
	#
	parkfield={'dt':dtm.datetime(2004,9,28,17,15,24, tzinfo=pytz.timezone('UTC')), 'lat':35.815, 'lon':-120.374, 'mag':5.96}
	L_r = 10.**(parkfield['mag']/2. - d_lambda)
	d_lat = L_r_factor * L_r/111.1
	d_lon = L_r_factor * L_r*math.cos(deg2rad*parkfield['lat'])/111.1
	
	print("d_lat, d_lon: ", d_lat, d_lon)
	#
	x_pf=parkfield['lon']
	y_pf=parkfield['lat']
	parkfield_cat_prams = {'lon':[x_pf-d_lon, x_pf+d_lon], 'lat':[y_pf-d_lat, y_pf+d_lon], 'minMag':1.5, 'dates0':[dtm.datetime(2004,9,28, tzinfo=pytz.timezone('UTC')), dtm.datetime(2010,9,28, tzinfo=pytz.timezone('UTC'))], 'Nmax':None, 'fout':None, 'rec_array':True}
	#
	cat = atp.catfromANSS(**parkfield_cat_prams)
	#
	# i still don't get what this does...
	#my_pca = PCA(numpy.array(zip(cat['lon'], cat['lat'])))
	my_pca = ptp.yoda_pca(list(zip(cat['lon'], cat['lat'])))		# returns (eig_vals, eig_vecs)
	e_vals = my_pca[0]
	e_vecs = numpy.array(my_pca[1])
	#
	#e_vals_n = e_vals/min(e_vals)
	e_vals_n = numpy.array([min(4.0, x/min(e_vals)) for x in e_vals])
	#
	print("e_vecs:", e_vecs[0][0], e_vecs[0][1], e_vecs[1][0], e_vecs[1][1])
	circle_xy = simple_circle(x=x, y=y, r=L_r*L_r_factor/111.1)

	#T = numpy.array([[e_vals_n[j]*x for x in rw] for j,rw in enumerate(e_vecs)])
	#circle_xy_prime = numpy.dot(circle_xy,T.transpose())	# note: this syntax will add [x,y] to all members of circle_xy_prime like [[a+x,b+y], [a+x,b+y],...]
	
	T = numpy.dot([[e_vals_n[0],0.],[0., e_vals_n[1]]], e_vecs)
	circle_xy_prime = numpy.dot(circle_xy, T)
	
	#circle_xy_prime = numpy.dot(circle_xy, [[e_vals_n[0],0.],[0., e_vals_n[1]]])
	#circle_xy_prime = numpy.dot(circle_xy_prime, e_vecs)
	
	#circle_xy = numpy.array(circle_xy)+numpy.array([x,y])
	circle_xy_prime = [[j+x_pf, k+y_pf] for j,k in circle_xy_prime]
	circle_xy = [[j+x_pf, k+y_pf] for j,k in circle_xy]
	#print "T: ", T
	#
	# a rotational transformation:
	#  elliptical distribution; a = r, b = {something < a}. this is distinct from the equal-area transform, in which a>r.
	#  note that for this transform, the initial rate-density is adjusted to the new (surface projection) area.
	#mu_x, mu_y = [numpy.mean(col) for col in zip(*circle_xy)]
	#print "means: ", mu_x, mu_y
	#circle_xy_prime = [[rw[0]-mu_x, rw[1]-mu_y] for rw in circle_xy]
	#
	#circle_xy_prime = [[numpy.dot(rw,e_vecs[0])*e_vals_n[0], numpy.dot(rw, e_vecs[1])*e_vals_n[1]] for rw in circle_xy_prime]
	#circle_xy_prime = numpy.dot([[rw[0] + mu_x, rw[1]+mu_y] for rw in circle_xy_prime], zip(*e_vecs))
	#circle_xy_prime = numpy.dot(circle_xy_prime, e_vecs.transpose())
	#circle_xy_prime = numpy.dot(circle_xy_prime, e_vecs)
	#circle_xy_prime = [[j+mu_x, k+mu_y] for j,k in circle_xy_prime]

	#circle_xy_prime = numpy.dot(circle_xy_prime, zip(*e_vecs))
	#
	plt.figure(0)
	plt.clf()
	plt.plot(cat['lon'], cat['lat'], '.', label='parkfield cat')
	plt.plot([x_pf], [y_pf], 'r*', ms=15)
	plt.legend(loc=0, numpoints=1)
	#
	plot_axes = (L_r/111.2)*numpy.array([e_vecs[0], [0.,0.], e_vecs[1]]) + numpy.array([x_pf, y_pf])
	plt.plot(*zip(*plot_axes), ls='-', marker='o')
	#
	Lry = abs(L_r_factor * L_r/111.1)
	Lrx = abs(Lry*math.cos(y_pf*deg2rad))
	
	#
	Wts = [xx/max(e_vals) for xx in e_vals]
	print("Wts: ", Wts)
	#e_vecs = e_vecs.transpose()
	
	
	#plt.plot([x, x + Lrx*e_vecs[0][0]], [y, y + Lry*e_vecs[0][1]], ls='-', marker='o', color='r')
	#plt.plot([x, x + Lrx*e_vecs[1][0]], [y, y + Lry*e_vecs[1][1]], ls='-', marker='^', color='m')
	
	'''
	#<<<<<<< HEAD
	plt.plot([x, x + Wts[0]*Lry*e_vecs[0][0]], [y, y + Wts[0]*Lry*e_vecs[0][1]], ls='-', marker='o', color='r')
	plt.plot([x, x + Wts[1]*Lry*e_vecs[1][0]], [y, y + Wts[1]*Lry*e_vecs[1][1]], ls='-', marker='^', color='m')
	plt.plot(*list(zip(*circle_xy)), ls='-', marker='', lw=2.)
	plt.plot(*list(zip(*circle_xy_prime)), ls='--', color='r', marker='', lw=1.5, alpha=.7, zorder=11)
	#=======
	'''
	#ax1 = numpy.dot(
	
	plt.plot([x_pf, x_pf + Wts[0]*Lry*e_vecs[0][0]], [y_pf, y_pf + Wts[0]*Lry*e_vecs[0][1]], ls='-', marker='o', color='r')
	plt.plot([x_pf, x_pf + Wts[1]*Lry*e_vecs[1][0]], [y_pf, y_pf + Wts[1]*Lry*e_vecs[1][1]], ls='-', marker='^', color='m')
	
	plt.plot(*zip(*circle_xy), ls='-', marker='', lw=2.)
	plt.plot(*zip(*circle_xy_prime), ls='--', color='r', marker='', lw=1.5, alpha=.7, zorder=11)	
	
	#plt.plot([x, x+Lrx*e_vecs[0][0]], [y, y + Lry*e_vecs[1][0]], ls='-', marker='o', color='r')
	#plt.plot([x, x+Lrx*e_vecs[0][1]], [y, y + Lry*e_vecs[1][1]], ls='-', marker='^', color='m')
	
	plt.figure(1)
	plt.clf()
	#plt.plot([0., Lrx*e_vecs[0][0]], [0., Lry*e_vecs[0][1]], '.-')
	#plt.plot([0., Lrx*e_vecs[1][0]], [0., Lry*e_vecs[1][1]], '.--')
	#plt.plot([0., e_vecs[0][0]], [0., e_vecs[0][1]], '.-')
	#plt.plot([0., e_vecs[1][0]], [0., e_vecs[1][1]], '.--')
	plt.plot(*zip([0.,0.],e_vecs[0]), marker='.', ls='--')
	plt.plot(*zip([0.,0.],e_vecs[1]),marker='^', ls='-')
	
	plt.plot(*zip([0.,0.],T[0]), marker='.', ls='--')
	plt.plot(*zip([0.,0.],T[1]),marker='^', ls='-')
	
	
	#
	return my_pca