Compare commits
2 Commits
827e9b5c77
...
afef4c4d5c
| Author | SHA1 | Date | |
|---|---|---|---|
| afef4c4d5c | |||
| 047f5e25ac |
@@ -1,18 +1,21 @@
|
||||
#! /usr/bin/env python
|
||||
# pyright: basic
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from utils import parser, crud, stats
|
||||
from utils import parser, crud, stats, utils
|
||||
|
||||
HEADER = """=== Terramotos ==="""
|
||||
|
||||
EVENT_COLS = ["Data", "Latitude", "Longitude", "Profundidade", "Tipo Evento", "Gap", "Magnitudes", "Regiao", "Sentido"]
|
||||
STATION_COLS = ["Estacao", "Hora", "Min", "Seg", "Componente", "Distancia Epicentro", "Tipo Onda"]
|
||||
|
||||
MENU ="""[1] Criar a base de dados
|
||||
[] Atualizar uma entrada (Removido)
|
||||
[3] Apagar um evento
|
||||
[4] Apagar uma entrada de um evento
|
||||
[5] Visualizar um evento
|
||||
@@ -24,20 +27,13 @@ MENU ="""[1] Criar a base de dados
|
||||
[Q] Sair
|
||||
"""
|
||||
|
||||
def guardar_df(df: pd.DataFrame, fname: str) -> bool:
|
||||
with open(fname, "w") as fp:
|
||||
fname = f"{fname}.txt"
|
||||
try:
|
||||
fp.write(df.to_string())
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def guardar_json(df: pd.DataFrame, fname: str) -> bool:
|
||||
_retValues = utils.create_dict_struct(df, EVENT_COLS, None)
|
||||
|
||||
with open(fname , "w") as fp:
|
||||
try:
|
||||
df.to_json(fp, indent=4)
|
||||
json.dump(_retValues, fp)
|
||||
except:
|
||||
return False
|
||||
return True
|
||||
@@ -78,26 +74,6 @@ def main():
|
||||
else:
|
||||
input("Base de dados não encontrada. Por favor tenta de novo.")
|
||||
|
||||
case "2":
|
||||
pass
|
||||
# if db is not None:
|
||||
# crud.read_ids(db)
|
||||
# eid_choice = _get_usr_input("Escolhe o ID: ", int)
|
||||
#
|
||||
# if not _event_exists(db, eid_choice):
|
||||
# retInfo = "ID do event não encontrado!"
|
||||
#
|
||||
# else:
|
||||
# table = crud.get_table(db, eid_choice)
|
||||
# crud.show_table(table)
|
||||
# row_choice = _get_usr_input("Escolhe a linha a atualizar: ", int)
|
||||
# new_data = {}
|
||||
# for col in crud.TABLE_READ_RET:
|
||||
# val = _get_usr_input(f"Novo valor para {col} (Enter para manter o valor atual): ")
|
||||
# if val is not None:
|
||||
# new_data[col] = val
|
||||
# crud.update_table_row(db, row_choice, new_data)
|
||||
|
||||
case "3":
|
||||
if db is not None:
|
||||
crud.read_ids(db)
|
||||
@@ -129,7 +105,6 @@ def main():
|
||||
crud.show_table(table)
|
||||
|
||||
row_choice = _get_usr_input("Escolhe a linha a apagar:", int)
|
||||
# TODO: balizar a escolha para apenas as linhas do evento em questao
|
||||
|
||||
db, msg = crud.delete_table_row(db, eid_choice, row_choice)
|
||||
new_table = crud.get_table(db, eid_choice)
|
||||
|
||||
@@ -101,8 +101,7 @@ def _parse_preamble(hLines: list[str]):
|
||||
case "6":
|
||||
aux[6].append(line)
|
||||
case "E":
|
||||
pass
|
||||
# aux["E"].append(line)
|
||||
aux["E"].append(line)
|
||||
case "I":
|
||||
aux["I"].append(line)
|
||||
case "F":
|
||||
@@ -136,7 +135,7 @@ def _parse_type_1(data: list[str]):
|
||||
depth = float(aux[38:43])
|
||||
no_stat = int(aux[48:51])
|
||||
|
||||
hypo = {"Data": dt.isoformat(), "Distancia": dist_ind, "Tipo Ev": ev_type, "Lat": lat, "Long": long, "Prof": depth, "Estacoes": no_stat, "Magnitudes": list()}
|
||||
hypo = {"Data": dt.isoformat(), "Distancia": dist_ind, "Tipo Evento": ev_type, "Latitude": lat, "Longitude": long, "Profundidade": depth, "Estacoes": no_stat, "Magnitudes": list()}
|
||||
for l in data:
|
||||
hypo["Magnitudes"] = hypo["Magnitudes"] + _parse_mag(l)
|
||||
|
||||
@@ -175,7 +174,7 @@ def _parse_type_6(data: list[str]):
|
||||
def _parse_type_7(data: list[str]):
|
||||
aux = io.StringIO("\n".join(data))
|
||||
dados = pd.read_fwf(aux, colspecs=[(1,5), (6,8),(10,15), (18,20), (20,22), (23,28), (34,38), (71,75)])
|
||||
dados.rename(columns={'STAT': "Estacao", 'SP': "Componente" , 'PHASW': "Tipo Onda", 'HR': "Hora", 'MM': "Min", 'SECON': "Seg", 'AMPL': "Amplitude", " DIST": "Dist. Epi"}, inplace=True)
|
||||
dados.rename(columns={'STAT': "Estacao", 'SP': "Componente" , 'PHASW': "Tipo Onda", 'HR': "Hora", 'MM': "Min", 'SECON': "Seg", 'AMPL': "Amplitude", " DIST": "Distancia Epicentro"}, inplace=True)
|
||||
return dados
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import json
|
||||
from math import modf
|
||||
from typing import Any
|
||||
|
||||
from numpy import nan
|
||||
import pandas as pd
|
||||
|
||||
|
||||
@@ -26,17 +25,24 @@ def create_dict_struct(df: pd.DataFrame, event_cols, station_cols) -> dict[str,
|
||||
for id in uniqueIds:
|
||||
filteredDf = df.loc[df["ID"] == id]
|
||||
first_row = filteredDf.head(1)
|
||||
allEvents[int(id)] = create_event_info(first_row)
|
||||
allEvents[int(id)] = create_event_info(first_row, event_cols)
|
||||
allEvents[int(id)].update(create_stations_info_1(filteredDf))
|
||||
|
||||
return allEvents
|
||||
|
||||
|
||||
def create_event_info(info: pd.DataFrame) -> dict[str, Any]:
|
||||
return {"DataHora": info.iloc[0]["Data"], "Lat": float(info.iloc[0]["Lat"]), "Long": float(info.iloc[0]["Long"]),
|
||||
"Profundidade": float(info.iloc[0]["Prof"]), "Tipo Evento": info.iloc[0]["Tipo Ev"],
|
||||
"Magnitude": create_mag_info(info.iloc[0]["Magnitudes"]), "Regiao": info.iloc[0]["Regiao"],
|
||||
"Sentido": info.iloc[0]["Sentido"]}
|
||||
def create_event_info(info: pd.DataFrame, cols) -> dict[str, Any]:
|
||||
informacoes = dict()
|
||||
|
||||
for v in cols:
|
||||
if v == "Magnitudes":
|
||||
informacoes[v] = create_mag_info(info.iloc[0][v])
|
||||
elif v in {"Latitude", "Longitude", "Profundidade", "Gap"}:
|
||||
informacoes[v] = float(info.iloc[0][v])
|
||||
else:
|
||||
informacoes[v] = info.iloc[0][v]
|
||||
|
||||
return informacoes
|
||||
|
||||
|
||||
def create_stations_info_1(info: pd.DataFrame) -> dict[str, Any]:
|
||||
|
||||
Reference in New Issue
Block a user