import pandas as pd
import numpy as np
import tqdm
from haversine import haversine
import plotly.express as px
import matplotlib.pyplot as plt
import warnings
"ignore", np.ComplexWarning)
warnings.simplefilter(from IPython.display import HTML
Import
from matplotlib import cm
from pygsp import graphs, filters, plotting, utils
import plotly.graph_objects as go
import rpy2
import rpy2.robjects as ro
from rpy2.robjects.vectors import FloatVector
from rpy2.robjects.packages import importr
import warnings
"ignore") warnings.filterwarnings(
import pickle
Earthquake
= pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv') df
= pd.concat([pd.read_csv('00_05.csv'),pd.read_csv('05_10.csv'),pd.read_csv('10_15.csv'),pd.read_csv('15_20.csv')]).iloc[:,[0,1,2,4]].rename(columns={'latitude':'Latitude','longitude':'Longitude','mag':'Magnitude'}).reset_index().iloc[:,1:] df_global
= df_global.assign(Year=list(map(lambda x: x.split('-')[0], df_global.time))).iloc[:,1:] df_global
= df_global.Year.astype(np.float64) df_global.Year
class MooYaHo:
def __init__(self,df):
self.df = df
self.f = df.Magnitude.to_numpy()
self.year = df.Year.to_numpy()
self.lat = df.Latitude.to_numpy()
self.long = df.Longitude.to_numpy()
self.n = len(self.f)
self.theta= None
def get_distance(self):
self.D = np.zeros([self.n,self.n])
= np.stack([self.lat, self.long],axis=1)
locations for i in tqdm.tqdm(range(self.n)):
for j in range(i,self.n):
self.D[i,j]=haversine(locations[i],locations[j])
self.D = self.D+self.D.T
def get_weightmatrix(self,theta=1,beta=0.5,kappa=4000):
self.theta = theta
= np.where(self.D<kappa,self.D,0)
dist self.W = np.exp(-(dist/self.theta)**2)
def _eigen(self):
= self.W.sum(axis=1)
d= np.diag(d)
Dself.L = np.diag(1/np.sqrt(d)) @ (D-self.W) @ np.diag(1/np.sqrt(d))
self.lamb, self.Psi = np.linalg.eigh(self.L)
self.Lamb = np.diag(self.lamb)
def fit(self,m):
self._eigen()
self.fhat = self.Psi[:,0:m]@self.Psi[:,0:m].T@self.f
self.df = self.df.assign(MagnitudeHat = self.fhat)
self.df = self.df.assign(Residual = self.df.Magnitude- self.df.MagnitudeHat)
self.f,'.')
plt.plot(self.fhat,'x') plt.plot(
class MooYaHo2(MooYaHo): # ebayesthresh 기능추가
def fit2(self): # fit with ebayesthresh
self._eigen()
self.fbar = self.Psi.T @ self.f # fbar := graph fourier transform of f
self.power = self.fbar**2
= importr('EbayesThresh').ebayesthresh
ebayesthresh self.power_threshed=np.array(ebayesthresh(FloatVector(self.fbar**2)))
self.fbar_threshed = np.where(self.power_threshed>0,self.fbar,0)
self.fhat = self.Psi@self.fbar_threshed
self.df = self.df.assign(MagnitudeHat = self.fhat)
self.df = self.df.assign(Residual = self.df.Magnitude- self.df.MagnitudeHat)
self.con = np.where(self.df.Residual>0.7,1,0)
class eachlocation(MooYaHo2):
def haiti(self,MagThresh=7,ResThresh=1,adjzoom=5,adjmarkersize = 40):
= px.density_mapbox(self.df,
fig ='Latitude',
lat='Longitude',
lon='Magnitude',
z=15,
radius=dict(lat=18.4430, lon=-72.5710),
center= adjzoom,
zoom=900,
height= 0.8,
opacity ="open-street-map",
mapbox_style=[-3,3])
range_color={"r":0,"t":0,"l":0,"b":0})
fig.update_layout(margin= self.df.query('Magnitude > @MagThresh')['Latitude'],
fig.add_scattermapbox(lat = self.df.query('Magnitude > @MagThresh')['Longitude'],
lon = self.df.query('Magnitude > @MagThresh')['Magnitude'],
text = 5,
marker_size= 'blue',
marker_color= 0.1
opacity
)= self.df.query('Residual**2 > @ResThresh')['Latitude'],
fig.add_scattermapbox(lat = self.df.query('Residual**2 > @ResThresh')['Longitude'],
lon = self.df.query('Magnitude > @ResThresh')['Magnitude'],
text = adjmarkersize,
marker_size= 'red',
marker_color= 0.8
opacity
)
fig.add_trace(go.Scattermapbox(=self.df.query('Residual**2 > @ResThresh')['Latitude'],
lat=self.df.query('Residual**2 > @ResThresh')['Longitude'],
lon='markers',
mode=go.scattermapbox.Marker(
marker=20,
size='rgb(255, 255, 255)',
color=0.4
opacity
)
))return fig
def lquique(self,MagThresh=7,ResThresh=1,adjzoom=5, adjmarkersize= 40):
= px.density_mapbox(self.df,
fig ='Latitude',
lat='Longitude',
lon='Magnitude',
z=15,
radius=dict(lat=-32.6953, lon=-71.4416),
center=adjzoom,
zoom=900,
height= 0.8,
opacity ="open-street-map",
mapbox_style=[-7,7])
range_color={"r":0,"t":0,"l":0,"b":0})
fig.update_layout(margin= self.df.query('Magnitude > @MagThresh')['Latitude'],
fig.add_scattermapbox(lat = self.df.query('Magnitude > @MagThresh')['Longitude'],
lon = self.df.query('Magnitude > @MagThresh')['Magnitude'],
text = 5,
marker_size= 'blue',
marker_color= 0.1
opacity
)= self.df.query('Residual**2 > @ResThresh')['Latitude'],
fig.add_scattermapbox(lat = self.df.query('Residual**2 > @ResThresh')['Longitude'],
lon = self.df.query('Magnitude > @ResThresh')['Magnitude'],
text = adjmarkersize,
marker_size= 'red',
marker_color= 0.8
opacity
)
fig.add_trace(go.Scattermapbox(=self.df.query('Residual**2 > @ResThresh')['Latitude'],
lat=self.df.query('Residual**2 > @ResThresh')['Longitude'],
lon='markers',
mode=go.scattermapbox.Marker(
marker=20,
size='rgb(255, 255, 255)',
color=0.8
opacity
)
))return fig
def sichuan(self,MagThresh=7,ResThresh=1,adjzoom=5,adjmarkersize=40):
= px.density_mapbox(self.df,
fig ='Latitude',
lat='Longitude',
lon='Magnitude',
z=15,
radius=dict(lat=30.3080, lon=102.8880),
center=adjzoom,
zoom=900,
height= 0.6,
opacity ="open-street-map",
mapbox_style=[-7,7])
range_color={"r":0,"t":0,"l":0,"b":0})
fig.update_layout(margin= self.df.query('Magnitude > @MagThresh')['Latitude'],
fig.add_scattermapbox(lat = self.df.query('Magnitude > @MagThresh')['Longitude'],
lon = self.df.query('Magnitude > @MagThresh')['Magnitude'],
text = 5,
marker_size= 'blue',
marker_color= 0.1
opacity
)= self.df.query('Residual**2 > @ResThresh')['Latitude'],
fig.add_scattermapbox(lat = self.df.query('Residual**2 > @ResThresh')['Longitude'],
lon = self.df.query('Magnitude > @ResThresh')['Magnitude'],
text = adjmarkersize,
marker_size= 'red',
marker_color= 0.8
opacity
)
fig.add_trace(go.Scattermapbox(=self.df.query('Residual**2 > @ResThresh')['Latitude'],
lat=self.df.query('Residual**2 > @ResThresh')['Longitude'],
lon='markers',
mode=go.scattermapbox.Marker(
marker=20,
size='rgb(255, 255, 255)',
color=0.8
opacity
)
))return fig
=eachlocation(df_global.query("2010 <= Year < 2015")) each_location
-
get distance
each_location.get_distance()
100%|██████████| 12498/12498 [03:22<00:00, 61.58it/s]
>0].mean() each_location.D[each_location.D
8810.865423093777
>0]) plt.hist(each_location.D[each_location.D
(array([14176290., 16005894., 21186674., 22331128., 19394182., 17548252.,
16668048., 13316436., 12973260., 2582550.]),
array([8.97930163e-02, 2.00141141e+03, 4.00273303e+03, 6.00405465e+03,
8.00537626e+03, 1.00066979e+04, 1.20080195e+04, 1.40093411e+04,
1.60106627e+04, 1.80119844e+04, 2.00133060e+04]),
<BarContainer object of 10 artists>)
-
weight matrix
=(8810.865423093777),kappa=2500) each_location.get_weightmatrix(theta
-
fit
each_location.fit2()
=6.9,ResThresh=0.5,adjzoom=5,adjmarkersize=40)
each_location.haiti(MagThresh= each_location.haiti(MagThresh=6.9,ResThresh=0.5,adjzoom=5,adjmarkersize=50)
fig with open('earth_haiti.pkl', 'wb') as file:
file)
pickle.dump(fig,
with open('earth_haiti.pkl', 'rb') as file:
= pickle.load(file)
earth_haiti earth_haiti.show()
=6.4,ResThresh=0.4,adjzoom=5,adjmarkersize=40)
each_location.lquique(MagThresh= each_location.lquique(MagThresh=6.4,ResThresh=0.4,adjzoom=5,adjmarkersize=50)
fig
with open('earth_lquique.pkl', 'wb') as file:
file)
pickle.dump(fig,
with open('earth_lquique.pkl', 'rb') as file:
= pickle.load(file)
earth_lquique earth_lquique.show()
=6.5,ResThresh=0.4,adjzoom=5,adjmarkersize=40)
each_location.sichuan(MagThresh= each_location.sichuan(MagThresh=6.5,ResThresh=0.4,adjzoom=5,adjmarkersize=50)
fig with open('earth_sichuan.pkl', 'wb') as file:
file)
pickle.dump(fig,
with open('earth_sichuan.pkl', 'rb') as file:
= pickle.load(file)
earth_sichuan earth_sichuan.show()