def getClosest(elat, elon, etime, eventlist): dmin = 9999999 tmin = 9999999 azmin = 9999999 imin = -1 for i in range(0, len(eventlist)): event = eventlist[i] lon, lat, depth = event['geometry']['coordinates'] time = datetime.utcfromtimestamp(event['properties']['time'] / 1000) dd = distance.sdist(elat, elon, lat, lon) / 1000.0 azim = distance.getAzimuth(elat, elon, lat, lon) if time > etime: dt = (time - etime).seconds else: dt = (etime - time).seconds if dd < dmin and dt < dmin: dmin = dd tmin = dt azmin = azim imin = i event = eventlist[imin] idlist = event['properties']['ids'].split(',')[1:-1] eurl = event['properties']['url'] authid = event['id'] idlist.remove(authid) idlist.append(authid) idlist = idlist[::-1] return (idlist, eurl, dmin, tmin, azmin)
def getClosest(elat,elon,etime,eventlist): dmin = 9999999 tmin = 9999999 azmin = 9999999 imin = -1 for i in range(0,len(eventlist)): event = eventlist[i] lon,lat,depth = event['geometry']['coordinates'] time = datetime.utcfromtimestamp(event['properties']['time']/1000) dd = distance.sdist(elat,elon,lat,lon)/1000.0 azim = distance.getAzimuth(elat,elon,lat,lon) if time > etime: dt = (time - etime).seconds else: dt = (etime - time).seconds if dd < dmin and dt < dmin: dmin = dd tmin = dt azmin = azim imin = i event = eventlist[imin] idlist = event['properties']['ids'].split(',')[1:-1] eurl = event['properties']['url'] authid = event['id'] idlist.remove(authid) idlist.append(authid) idlist = idlist[::-1] return (idlist,eurl,dmin,tmin,azmin)
def getEventsInCircle(lat, lon, radius, eventlist): """ Select earthquakes from a list of events using a lat/lon center and a radius in km. @param lat: Latitude at center of circle. @param lon: Longitude at center of circle. @param radius: Radius of search in km. @param eventlist: List of event dictionaries, each containing (at least) keys lat,lon,depth,mag. @return: Filtered list of earthquake dictionaries. """ elat = np.array([ e['lat'] for e in eventlist ]) #extract the latitudes from each dictionary in the list elon = np.array([ e['lon'] for e in eventlist ]) #extract the longitudes from each dictionary in the list d = sdist( lat, lon, elat, elon ) / 1000.0 #do vectorized distance calculation from center point to all lat/lon pairs az = [] for i in range(0, len(elat)): az.append(getAzimuth(lat, lon, elat[i], elon[i])) #vectorize the azimuth function someday for i in range(0, len(eventlist)): eventlist[i]['distance'] = d[ i] #add distance field to each dictionary in the list eventlist[i]['azimuth'] = az[ i] #add azimuth field to each dictionary in the list idx = (d <= radius).nonzero()[ 0] #array of indices where distance is less than input threshold newlist = (np.array(eventlist)[idx]).tolist() #return a shortened list return newlist
def getAmps(lat, lon, etime, radius, timewindow): starttime = datetime(etime.year, etime.month, etime.day - 1) endtime = datetime(etime.year, etime.month, etime.day + 1) url = BASEURL.replace('[START]', starttime.strftime(DATEFMT)) url = url.replace('[END]', endtime.strftime(DATEFMT)) eventlist = getEventList(url) eventid = None for event in eventlist: elat = event['lat'] elon = event['lon'] if etime >= event['time']: dtime = etime - event['time'] else: dtime = event['time'] - etime dt = dtime.days * 86400 + dtime.seconds dd = sdist(lat, lon, elat, elon) / 1000.0 if dt < timewindow / 2 and dd < radius: eventid = event['id'] break if eventid is None: print 'No events found matching your criteria.' return [] eurl = EVENTURL.replace('[EVENTID]', eventid) stationlist = getStationList(eurl, eventid) return stationlist
def getAmps(lat,lon,etime,radius,timewindow): starttime = datetime(etime.year,etime.month,etime.day-1) endtime = datetime(etime.year,etime.month,etime.day+1) url = BASEURL.replace('[START]',starttime.strftime(DATEFMT)) url = url.replace('[END]',endtime.strftime(DATEFMT)) eventlist = getEventList(url) eventid = None for event in eventlist: elat = event['lat'] elon = event['lon'] if etime >= event['time']: dtime = etime - event['time'] else: dtime = event['time'] - etime dt = dtime.days*86400 + dtime.seconds dd = sdist(lat,lon,elat,elon)/1000.0 if dt < timewindow/2 and dd < radius: eventid = event['id'] break if eventid is None: print('No events found matching your criteria.') return [] eurl = EVENTURL.replace('[EVENTID]',eventid) stationlist = getStationList(eurl,eventid) return stationlist
def updateCloseEvents(self): thiseq = self.EventList[-1] time = float(thiseq['time'].strftime('%s')) lat = thiseq['lat'] lon = thiseq['lon'] if not len(self.Lat): self.Lat.append(lat) self.Lon.append(lon) self.Time.append(time) return nplat = numpy.array(self.Lat) nplon = numpy.array(self.Lon) nptime = numpy.array(self.Time) normdist = (distance.sdist(lat,lon,nplat,nplon)/1000)/self.DistanceWindow normtdelta = (numpy.abs(time - nptime))/self.TimeWindow eucdistance = numpy.sqrt(normdist**2+normtdelta**2) iclose = numpy.where(eucdistance <= numpy.sqrt(2)) thisidx = len(self.Lat) near = [] for idx in iclose[0]: self.NearEventIndices.append((idx,thisidx)) self.Lat.append(lat) self.Lon.append(lon) self.Time.append(time) return
def getEventsInEllipse(lat, lon, str, aval, bval, eventlist): """ Select earthquakes from a list of events using dist/az from a predefined lat/lon, and axes of an ellipse getEventsInCircle must already have been used @param str: Strike of slab at center of circle. @param aval: Long axis of ellipse in km. @param bval: Short axis of ellipse in km. @param eventlist: List of event dictionaries, each containing (at least) keys lat,lon,depth,mag. @return: Filtered list of earthquake dictionaries. """ elat = np.array([ e['lat'] for e in eventlist ]) #extract the latitudes from each dictionary in the list elon = np.array([ e['lon'] for e in eventlist ]) #extract the longitudes from each dictionary in the list d = sdist( lat, lon, elat, elon ) / 1000.0 #do vectorized distance calculation from center point to all lat/lon pairs az = [] for i in range(0, len(elat)): az.append(getAzimuth(lat, lon, elat[i], elon[i])) #vectorize the azimuth function someday for i in range(0, len(eventlist)): eventlist[i]['distance'] = d[ i] #add distance field to each dictionary in the list eventlist[i]['azimuth'] = az[ i] #add azimuth field to each dictionary in the list # print 'Eventlist[1] = %.4f, %.4f, %.4f, %.4f' % (elat[1],elon[1],d[1],az[1]) mdist = [] erta = math.sqrt(1 - ((math.pow(bval, 2)) / (math.pow(aval, 2)))) # print 'ERTA = %.4f' % (erta) for i in range(0, len(elat)): mdist.append(getEllipseRad(aval, erta, az[i], str)) # print 'Lon:', (elon[1:-1]) # print 'Lat:', (elat[1:-1]) # print 'Dist:', (d[1:-1]) # print 'Azi:', (az[1:-1]) # print 'Edist:', (mdist[1:-1]) idx = (d <= mdist).nonzero()[ 0] #array of indices where distance is less than input threshold # print 'Indexes:' # print (idx)[1:-1] newerlist = (np.array(eventlist)[idx]).tolist() #return a shortened list return newerlist
def __getEuclidean(lat1,lon1,time1,lat2,lon2,time2,dwindow=DISTWINDOW,twindow=TIMEWINDOW): dd = distance.sdist(lat1,lon1,lat2,lon2)/1000.0 normd = dd/dwindow if time2 > time1: dt = time2-time1 else: dt = time1-time2 nsecs = dt.days*86400 + dt.seconds normt = nsecs/twindow euclid = numpy.sqrt(normd**2 + normt**2) return (euclid,dd,nsecs)
def getEventsInEllipse(lat,lon,str,aval,bval,eventlist): """ Select earthquakes from a list of events using dist/az from a predefined lat/lon, and axes of an ellipse getEventsInCircle must already have been used @param str: Strike of slab at center of circle. @param aval: Long axis of ellipse in km. @param bval: Short axis of ellipse in km. @param eventlist: List of event dictionaries, each containing (at least) keys lat,lon,depth,mag. @return: Filtered list of earthquake dictionaries. """ elat = np.array([e['lat'] for e in eventlist]) #extract the latitudes from each dictionary in the list elon = np.array([e['lon'] for e in eventlist]) #extract the longitudes from each dictionary in the list d = sdist(lat,lon,elat,elon)/1000.0 #do vectorized distance calculation from center point to all lat/lon pairs az = [] for i in range(0,len(elat)): az.append(getAzimuth(lat,lon,elat[i],elon[i])) #vectorize the azimuth function someday for i in range(0,len(eventlist)): eventlist[i]['distance'] = d[i] #add distance field to each dictionary in the list eventlist[i]['azimuth'] = az[i] #add azimuth field to each dictionary in the list # print 'Eventlist[1] = %.4f, %.4f, %.4f, %.4f' % (elat[1],elon[1],d[1],az[1]) mdist = [] erta = math.sqrt(1-((math.pow(bval,2))/(math.pow(aval,2)))) # print 'ERTA = %.4f' % (erta) for i in range(0,len(elat)): mdist.append(getEllipseRad(aval,erta,az[i],str)) # print 'Lon:', (elon[1:-1]) # print 'Lat:', (elat[1:-1]) # print 'Dist:', (d[1:-1]) # print 'Azi:', (az[1:-1]) # print 'Edist:', (mdist[1:-1]) idx = (d <= mdist).nonzero()[0] #array of indices where distance is less than input threshold # print 'Indexes:' # print (idx)[1:-1] newerlist = (np.array(eventlist)[idx]).tolist() #return a shortened list return newerlist
def main(args): oldtrenchfile = args.newtrenchlist oldtrench = pd.read_csv(oldtrenchfile) oldtrench = zerothreesixty(oldtrench) slabs = oldtrench['slab'].values slablist = mylist = list(set(list(slabs))) print ('generating trenches for this list of slab models:', slablist) allslabs = pd.DataFrame() # sort points for each slab in slablist, sort direction changes for each region. for slab in slablist: thistrench = oldtrench[oldtrench.slab == slab] print ('making trench for:',slab) bound = thistrench['bound'].values[0] firstlon = thistrench['lon'].values[-1] firstlat = thistrench['lat'].values[-1] slons,slats = [],[] slons.append(firstlon) slats.append(firstlat) thistrench = thistrench[(thistrench.lon != firstlon)|(thistrench.lat != firstlat)] while (len(thistrench))>0: thistrench['dist'] = sdist(firstlat, firstlon, thistrench['lat'], thistrench['lon'])/1000.0 closest = thistrench[thistrench.dist == thistrench['dist'].min()] firstlon = closest['lon'].values[0] firstlat = closest['lat'].values[0] thistrench = thistrench[(thistrench.lon != firstlon)|(thistrench.lat != firstlat)] slons.append(firstlon) slats.append(firstlat) thistrench = pd.DataFrame({'lon':slons,'lat':slats,'slab':slab,'bound':bound}) thisnew = newaz(thistrench) thisnew['number'] = range(len(thisnew)) thisnew = thisnew.sort_values(by=['number'],ascending=False) allslabs = pd.concat([allslabs,thisnew],sort=True) allslabs = oneeighty(allslabs) allslabs = allslabs[['lon','lat','az','bound','slab','number']] allslabs.to_csv(args.trenchfile,header=True,index=False,na_rep=np.nan)
def findCitiesByRadius(self,lat,lon,radius,citylist=None): """ Find cities inside a given search radius. @param lat: Latitude of center of search radius. @param lon: Longitude of center of search radius. @param radius: Radius (in km) within which search should be conducted. @keyword citylist: List of city dictionaries to search from: - name City name - ccode Two-letter country code. - lat Latitude of city center. - lon Longitude of city center. - iscap Boolean indicating if city is a capital of a region or country. - pop Population of city. @return: List of city dictionaries (same fields as input citylist). """ subcities = [] if citylist == None: citylist = self.cities for city in citylist: if sdist(lat,lon,city['lat'],city['lon']) <= radius*1000: subcities.append(city) return subcities
def getEventsInCircle(lat,lon,radius,eventlist): """ Select earthquakes from a list of events using a lat/lon center and a radius in km. @param lat: Latitude at center of circle. @param lon: Longitude at center of circle. @param radius: Radius of search in km. @param eventlist: List of event dictionaries, each containing (at least) keys lat,lon,depth,mag. @return: Filtered list of earthquake dictionaries. """ elat = np.array([e['lat'] for e in eventlist]) #extract the latitudes from each dictionary in the list elon = np.array([e['lon'] for e in eventlist]) #extract the longitudes from each dictionary in the list d = sdist(lat,lon,elat,elon)/1000.0 #do vectorized distance calculation from center point to all lat/lon pairs az = [] for i in range(0,len(elat)): az.append(getAzimuth(lat,lon,elat[i],elon[i])) #vectorize the azimuth function someday for i in range(0,len(eventlist)): eventlist[i]['distance'] = d[i] #add distance field to each dictionary in the list eventlist[i]['azimuth'] = az[i] #add azimuth field to each dictionary in the list idx = (d <= radius).nonzero()[0] #array of indices where distance is less than input threshold newlist = (np.array(eventlist)[idx]).tolist() #return a shortened list return newlist
def createDeltaPlots(dataframe,plotdir): df2 = dataframe.copy() df2 = df2[np.isfinite(df2['MAGINITIAL'])] firstmag = dataframe['MAGINITIAL'].as_matrix() lastmag = dataframe['MAGPDE'].as_matrix() firstdepth = dataframe['DDEPTHINITIAL'].as_matrix() lastdepth = dataframe['DDEPTHPDE'].as_matrix() firstlat = dataframe['DLATINITIAL'].as_matrix() lastlat = dataframe['DLATPDE'].as_matrix() firstlon = dataframe['DLONINITIAL'].as_matrix() lastlon = dataframe['DLONPDE'].as_matrix() dmag = lastmag - firstmag ddepth = lastdepth - firstdepth dloc = distance.sdist(firstlat,firstlon,lastlat,lastlon)/1000.0 #get the number of each quantity nmag = len((np.abs(dmag) >= 0.5).nonzero()[0]) ndepth = len((np.abs(ddepth) > 50).nonzero()[0]) ndist100 = len((np.abs(dloc) > 100).nonzero()[0]) ndist50 = len((np.abs(dloc) > 50).nonzero()[0]) #get the 90% quantiles for each difference ifinite = np.isfinite(dmag) qmag = mstats.mquantiles(np.abs(dmag[ifinite]),0.9)[0] qdepth = mstats.mquantiles(np.abs(ddepth[ifinite]),0.9)[0] qdist = mstats.mquantiles(np.abs(dloc[ifinite]),0.9)[0] ylabel = '# of earthquakes' fig,axeslist = plt.subplots(nrows=3,ncols=1) fig.set_size_inches(6,10) #mag change histogram plt.sca(axeslist[0]) dmag[dmag > 1.0] = 1.0 dmag[dmag < -1.0] = -1.0 drange1 = np.arange(-2.05,2.05,0.1) drange2 = np.arange(-2.0,2.5,0.5) plt.hist(dmag,bins=drange1,align='mid') axlim = plt.axis() plt.xticks(drange2) #plt.axis([-1.1,1.1,axlim[2],axlim[3]]) plt.ylabel(ylabel) plt.title('magnitude change (PDE-initial)') #depth change histogram ddepth[ddepth > 50] = 50 ddepth[ddepth < -50] = -50 plt.sca(axeslist[1]) plt.hist(ddepth,bins=np.arange(-52.5,52.5,5),align='mid') axlim = plt.axis() plt.axis([-50.0,50.0,axlim[2],axlim[3]]) plt.xticks(np.arange(-50,60,10)) plt.ylabel(ylabel) plt.title('depth change [km] (PDE-initial)') #location change histogram dloc[dloc > 100] = 100 plt.sca(axeslist[2]) plt.hist(dloc,bins=np.arange(2.5,105.5,5),align='mid') plt.ylabel(ylabel) axlim = plt.axis() #plt.xticks(np.arange(0,100,20)) plt.xticks(np.arange(0,120,20)) plt.axis([0,105,axlim[2],axlim[3]]) plt.title('epicentral change [km]') fig.tight_layout() plt.savefig(os.path.join(plotdir,'changes.pdf')) plt.savefig(os.path.join(plotdir,'changes.png')) plt.close() print 'Saving changes.pdf' return (nmag,ndepth,ndist100,ndist50,qmag,qdepth,qdist)
print ('couldnt read this file',SGfile) newtrdata = pd.DataFrame() for slab in slablist: BAdata = BAdataset[BAdataset.slab == slab] TRdata = trenches[trenches.slab == slab] depthlist = [] for index,row in TRdata.iterrows(): tlon,tlat = row['lon'],row['lat'] locba = BAdata[(BAdata.lon<tlon+0.5)&(BAdata.lon>tlon-0.5) &\ (BAdata.lat<tlat+0.5)&(BAdata.lat>tlat-0.5)] if len(locba)>0: locba['dist'] = sdist(tlat, tlon, locba['lat'], locba['lon']) mindist = locba['dist'].min() thisba = locba[locba.dist == mindist] if slab == 'him': depthlist.append(thisba['elev'].values[0]/1000) else: depthlist.append(thisba['depth'].values[0]) else: depthlist.append(np.nan) print (slab, tlon, tlat) TRdata['depth'] = depthlist newtrdata = pd.concat([newtrdata,TRdata])