-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Prediction #4
Open
natsyz
wants to merge
33
commits into
Zsaschz:main
Choose a base branch
from
natsyz:prediction
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Prediction #4
Changes from 6 commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
4e765e4
add spark docker
natsyz cd6ed50
refactor and add function
natsyz d376e40
update spark image
natsyz e80e7ae
Merge branch 'main' into main
natsyz e77878e
init predict module
natsyz 279b22e
attempt to fix missing timestamp from influx
Zsaschz 26b93b3
local predict
natsyz 11bfaa5
refactor
natsyz fbe3a43
add generator to simulate realtime data
Zsaschz a477f14
refactor db module
Zsaschz 43bb8b5
refactor to use multiprocess
Zsaschz 94ab505
add option to simulate realtime
Zsaschz 39fe5dd
map to fetch stations data & refactor
Zsaschz f16f512
fix generator file
Zsaschz 166b3a2
add fill empty timestamp and send key to kafka
Zsaschz f210c4e
fix time format for kafka event
Zsaschz 0d7b91e
add predict script
natsyz 3a547b5
Add pause time
natsyz c6d8236
add nginx conf
Zsaschz bf0ec4f
add seedlink realtime query and change window data on kafka
Zsaschz 7e5823a
refactor event time
Zsaschz f08ec33
Update station model
natsyz 636ff23
Merge branch 'rest' of https://github.com/Zsaschz/eews-event-driven i…
natsyz 3e14168
Update flow: without read from db
natsyz 050d92a
dockerize seedlink and rest api
Zsaschz 98f5f8a
Merge pull request #7 from natsyz/rest
Zsaschz c1f6270
finish frontend and add prettier config
Zsaschz 1b1693c
update rest api and seedlink
Zsaschz 62308de
Merge branch 'rest' of https://github.com/Zsaschz/eews-event-driven i…
natsyz a203f71
merging p arrival prediction
natsyz ed52ba8
add prediction script
natsyz 1980538
update code from cloud
natsyz 4025597
syntax fixing
natsyz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
from database.influxdb import * | ||
from stream_processing.kafka import KafkaConsumer | ||
from stream_processing.topics import P_ARRIVAL_TOPIC | ||
from utils.helper_functions import get_nearest_station, letInterpolate, denormalization | ||
from predict.predictor import Predictor | ||
from dotenv import load_dotenv | ||
import datetime | ||
|
||
load_dotenv() | ||
|
||
consumer = KafkaConsumer(P_ARRIVAL_TOPIC, "eews", {}) | ||
predictor = Predictor() | ||
|
||
def main(msg): | ||
stations = get_nearest_station(msg["station"], 200000) | ||
|
||
seis_data = [] | ||
|
||
for station in stations: | ||
data = read_seis_influx(station, datetime.datetime.strptime(msg["time"],'%Y-%m-%dT%H:%M:%S.%fZ')) | ||
if data: | ||
data_preprocessed = preprocess(data) | ||
seis_data.append(data_preprocessed) | ||
|
||
if len(seis_data) == 1: | ||
seis_data *= 3 | ||
elif len(seis_data) == 2: | ||
seis_data.append(seis_data[0]) | ||
|
||
preds = predictor.predict(seis_data) | ||
data_mtr = denormalization(preds.iloc[0]) | ||
|
||
print(f"{data_mtr =}") | ||
|
||
|
||
def read_seis_influx(station: str, time: datetime.datetime): | ||
client = InfluxDBClient( | ||
url=INFLUXDB_URL, | ||
org=INFLUXDB_ORG, | ||
token=INFLUXDB_TOKEN | ||
) | ||
query_api = client.query_api() | ||
start_time = (time - datetime.timedelta(0,5)).strftime('%Y-%m-%dT%H:%M:%S.%fZ') | ||
stop_time = (time + datetime.timedelta(0,5)).strftime('%Y-%m-%dT%H:%M:%S.%fZ') | ||
data = [] | ||
|
||
query = f"""from(bucket: "eews") | ||
|> range(start: {start_time}, stop: {stop_time}) | ||
|> filter(fn: (r) => r._measurement == "seismograf" and r.station == "{station}")""" | ||
|
||
tables = query_api.query(query, org="eews") | ||
|
||
data = [] | ||
for table in tables: | ||
res = [] | ||
for record in table.records: | ||
res.append(record.get_value()) | ||
data.append(res) | ||
|
||
return data | ||
|
||
def preprocess(data): | ||
data_interpolated = list(map(lambda x : letInterpolate(x, 2000), data)) | ||
|
||
data_interpolated_transformed = [] | ||
|
||
assert len(data_interpolated[0]) == 2000 | ||
assert len(data_interpolated[1]) == 2000 | ||
assert len(data_interpolated[2]) == 2000 | ||
|
||
for i in range(len(data_interpolated[0])): | ||
data_interpolated_transformed.append([data_interpolated[0][i], data_interpolated[1][i], data_interpolated[2][i]]) | ||
return data_interpolated_transformed | ||
|
||
if __name__ == "__main__": | ||
consumer.consume(on_message=main, on_error=None) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import numpy as np | ||
import pandas as pd | ||
import pickle | ||
import threading | ||
|
||
class Predictor(): | ||
_instance = None | ||
_lock = threading.Lock() | ||
|
||
def __new__(cls): | ||
with cls._lock: | ||
if cls._instance is None: | ||
cls._instance = super(Predictor, cls).__new__(cls) | ||
|
||
return cls._instance | ||
|
||
def __init__(self): | ||
self.model = pickle.load(open('predict\model\model.pkl', 'rb')) | ||
|
||
def predict(self, data): | ||
predictions = self.model.predict(np.array(data), batch_size=4) | ||
result = pd.DataFrame(columns=['lat','long','depth','magnitude','time']) | ||
|
||
for prediction, col_result in zip(np.array(predictions), ['lat','long','depth','magnitude','time']): | ||
result[col_result] = prediction.squeeze() | ||
|
||
return result |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
### SPARK APP | ||
# | ||
## Command in terminal pc | ||
# docker cp sandbox_predict.py [container-id]:/opt/bitnami/spark/sandbox_predict.py | ||
# docker cp model.pkl [container-id]:/opt/bitnami/spark/model.pkl | ||
# docker exec [container-name] ./bin/spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.4.1 --master spark://[host]:[port] sandbox_predict.py | ||
# | ||
## Command in terminal docker (spark) | ||
# pip install influxdb_client motor keras tensorflow | ||
# | ||
## Notes | ||
# this code has not been run yet due to resource limitation on my end :( | ||
# | ||
### | ||
|
||
from influxdb_client import InfluxDBClient | ||
from motor import motor_asyncio | ||
|
||
from pyspark.sql import SparkSession | ||
from pyspark.sql.types import * | ||
import pyspark.sql.functions as f | ||
|
||
import datetime | ||
import pickle | ||
|
||
BOOTSTAP_SERVERS = "$" | ||
MONGO_URL = "$" | ||
MONGO_DATABASE = "$" | ||
INFLUXDB_ORG = "$" | ||
INFLUXDB_URL = "$" | ||
INFLUXDB_TOKEN = "$" | ||
|
||
model = pickle.load(open('model.pkl', 'rb')) | ||
|
||
def main(): | ||
spark, sc = init_spark() | ||
model_broadcast = sc.broadcast(model) | ||
|
||
df = spark \ | ||
.readStream \ | ||
.format("kafka") \ | ||
.option("kafka.bootstrap.servers", BOOTSTAP_SERVERS) \ | ||
.option("subscribe", "p-arrival") \ | ||
.load() | ||
|
||
schema = StructType([StructField('station', StringType()), StructField('time', StringType())]) | ||
schema_output = StructType([StructField('lat', StringType()), \ | ||
StructField('long', StringType()), \ | ||
StructField('depth', StringType()), \ | ||
StructField('magnitude', StringType()), \ | ||
StructField('time', StringType())]) | ||
|
||
df_json = df.selectExpr("CAST(value AS STRING) as json") \ | ||
.select(f.from_json('json', schema).alias('data')) \ | ||
.select('data.*') | ||
|
||
def apply_prediction(station, time): | ||
import json | ||
import datetime | ||
|
||
# get data stasiun (mongo) | ||
stations = get_nearest_station(station, 200000) | ||
|
||
# get and preprocess data (influx) | ||
seis_data = [] | ||
|
||
for station in stations: | ||
data = read_seis_influx(station, datetime.datetime.strptime(time,'%Y-%m-%dT%H:%M:%S.%fZ')) # [[e,...,e],[n,...,n],[z,...,z]] | ||
data_preprocessed = preprocess(data) | ||
seis_data.append(data_preprocessed) | ||
|
||
if len(stations) == 1: | ||
seis_data *= 3 | ||
elif len(stations) == 2: | ||
seis_data.append(seis_data[0]) | ||
|
||
# predict | ||
preds = model_broadcast.predict(seis_data) | ||
data_mtr = denormalization(preds.iloc[0]) | ||
|
||
return data_mtr | ||
|
||
prediction_udf = f.udf(lambda data1, data2: apply_prediction(data1, data2), StringType()) | ||
|
||
query = df_json.select(f.from_json(prediction_udf(df_json.station, df_json.time), schema_output).alias('response'))\ | ||
.select('response.*') \ | ||
.writeStream \ | ||
.trigger(once=True) \ | ||
.format("console") \ | ||
|
||
query.awaitTermination() | ||
|
||
|
||
def init_spark(): | ||
spark = SparkSession.builder.getOrCreate() | ||
sc = spark.sparkContext | ||
return spark, sc | ||
|
||
def read_seis_influx(station: str, time: datetime.datetime): | ||
client = InfluxDBClient( | ||
url=INFLUXDB_URL, | ||
org=INFLUXDB_ORG, | ||
token=INFLUXDB_TOKEN | ||
) | ||
query_api = client.query_api() | ||
start_time = (time - datetime.timedelta(0,5)).strftime('%Y-%m-%dT%H:%M:%S.%fZ') | ||
stop_time = (time + datetime.timedelta(0,5)).strftime('%Y-%m-%dT%H:%M:%S.%fZ') | ||
data = [] | ||
|
||
query = f"""from(bucket: "eews") | ||
|> range(start: {start_time}, stop: {stop_time}) | ||
|> filter(fn: (r) => r._measurement == "seismograf" and r.station == "{station}")""" | ||
|
||
tables = query_api.query(query, org="eews") | ||
|
||
data = [] | ||
for table in tables: #ENZ | ||
res = [] | ||
for record in table.records: | ||
res.append(record.get_value()) | ||
data.append(res) | ||
|
||
return data | ||
|
||
def get_nearest_station(name, max_distance): | ||
client = motor_asyncio.AsyncIOMotorClient(MONGO_URL) | ||
db = client[MONGO_DATABASE] | ||
coordinates = db['seismometer'].find_one({ 'name': name })['location']['coordinates'] | ||
stations = db['seismometer'].find({ 'location': {'$nearSphere': {'$geometry': {'type': 'Point', 'coordinates': coordinates}, '$maxDistance': max_distance}}}, {'name': 1, '_id': 0}) | ||
return names if len(names:=[station['name'] for station in stations]) <= 3 else names[:3] | ||
|
||
def preprocess(data): | ||
data_interpolated = list(map(lambda x : letInterpolate(x, 2000), data)) # interpolate to 2000 data each channel | ||
|
||
data_interpolated_transformed = [] # transform to [[e,n,z], ..., [e,n,z]] | ||
|
||
for i in range(len(data_interpolated[0])): | ||
data_interpolated_transformed.append([data_interpolated[0][i], data_interpolated[1][i], data_interpolated[2][i]]) | ||
return data_interpolated_transformed | ||
|
||
def letInterpolate(inp, new_len): | ||
delta = (len(inp)-1) / (new_len-1) | ||
outp = [interpolate(inp, i*delta) for i in range(new_len)] | ||
return outp | ||
|
||
def interpolate(lst, fi): | ||
i, f = int(fi // 1), fi % 1 # Split floating-point index into whole & fractional parts. | ||
j = i+1 if f > 0 else i # Avoid index error. | ||
return (1-f) * lst[i] + f * lst[j] | ||
|
||
def denormalization(data): | ||
max,min = {},{} | ||
max['lat'] = -6.64264 | ||
min['lat'] = -11.5152 | ||
max['long'] = 115.033 | ||
min['long'] = 111.532 | ||
max['depth'] = 588.426 | ||
min['depth'] = 1.16 | ||
max['magnitude'] = 6.5 | ||
min['magnitude'] = 3.0 | ||
max['time'] = 74.122 | ||
min['time'] = 4.502 | ||
|
||
dats = {} | ||
for col in data.index: | ||
dats[col] = data[col]*(max[col] - min[col])+min[col] | ||
return dats | ||
|
||
if __name__ == "__main__": | ||
main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Move all of the db client initialization to on top of the file so that it is only being initialized once. The current code means you will create a new connection to the db every time you want to query