diff --git a/earthquakes.py b/earthquakes.py index 1a00c7d..99fc8b7 100644 --- a/earthquakes.py +++ b/earthquakes.py @@ -2,6 +2,7 @@ # pyright: basic import os +import sys from datetime import datetime import pandas as pd @@ -11,7 +12,7 @@ from utils import parser, crud, stats HEADER = """=== Terramotos ===""" MENU ="""[1] Criar a base de dados -[2] Atualizar uma entrada +[] Atualizar uma entrada (Removido) [3] Apagar um evento [4] Apagar uma entrada de um evento [5] Visualizar um evento @@ -58,7 +59,7 @@ def main(): retInfo = None while isRunning: - os.system("cls") + os.system("cls" if sys.platform == "windows" else "clear") print(HEADER + "\n" + MENU) usrIn = input("Opção: ").lower() @@ -78,23 +79,24 @@ def main(): input("Base de dados não encontrada. Por favor tenta de novo.") case "2": - 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) + 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: @@ -121,7 +123,7 @@ def main(): retInfo = "ID do event não encontrado!" else: - os.system("cls") + os.system("cls" if sys.platform == "windows" else "clear") table = crud.get_table(db, eid_choice) _prettify_event(table) crud.show_table(table) @@ -146,6 +148,7 @@ def main(): retInfo = "ID do event não encontrado!" else: + os.system("cls" if sys.platform == "windows" else "clear") table = crud.get_table(db, choice) _prettify_event(table) crud.show_table(table) @@ -187,7 +190,7 @@ def main(): retInfo = "ID do event não encontrado!" else: - os.system("cls") + os.system("cls" if sys.platform == "windows" else "clear") table = crud.get_table(db, eid_choice) _prettify_event(table) crud.show_table(table) diff --git a/utils/parser.py b/utils/parser.py index 49cb9e8..43ac6a3 100644 --- a/utils/parser.py +++ b/utils/parser.py @@ -159,6 +159,7 @@ def _parse_type_3(data: list[str]): for line in data: if line.startswith(" SENTIDO") or line.startswith(" REGIAO"): c, v = line[:-2].strip().split(": ", maxsplit=1) + v = v.split(",")[0] comments[c.capitalize()] = v return comments @@ -173,8 +174,8 @@ 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)]) - dados.rename(columns={'STAT': "Estacao", 'SP': "Componente" , 'PHASW': "Tipo Onda", 'HR': "Hora", 'MM': "Min", 'SECON': "Seg", 'AMPL': "Amplitude"}, inplace=True) + 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) return dados diff --git a/utils/stats.py b/utils/stats.py index cbb97c6..8ef25cd 100644 --- a/utils/stats.py +++ b/utils/stats.py @@ -1,6 +1,7 @@ # pyright: basic import os +import sys import pandas as pd import numpy as np @@ -29,7 +30,7 @@ CHOICE = {"1": "Magnitudes", "2": "Distancia","3": "Prof"} def filter_submenu(type: str): - os.system("cls") + os.system("cls" if sys.platform == "windows" else "clear") print(f"{STAT_HEADER}\n = {type} = ") print(FILTER_CHOICES) @@ -45,7 +46,7 @@ def filter_submenu(type: str): def stat_menu(df: pd.DataFrame): inStats = True while inStats: - os.system("cls") + os.system("cls" if sys.platform == "windows" else "clear") print(STAT_HEADER + "\n" + STAT_MENU) usrIn = input("Opção: ").lower() diff --git a/utils/utils.py b/utils/utils.py new file mode 100644 index 0000000..fd89b06 --- /dev/null +++ b/utils/utils.py @@ -0,0 +1,76 @@ +#! /usr/bin/env python +# pyright: basic + +from datetime import time +import json +from math import modf +from typing import Any + +from numpy import nan +import pandas as pd + + +def save_as_json(info: dict[str, Any]) -> bool: + with open("test.json", "w") as fp: + json.dump(info, fp) + + return True + +# TODO: passar os nomes das colunas, para não haver problemas no futuro, caso se altere os nomes da dataframe +def create_dict_struct(df: pd.DataFrame, event_cols, station_cols) -> dict[str, Any]: + # get all events by their id + uniqueIds = df["ID"].unique() + + allEvents = {} + + 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)].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_stations_info_1(info: pd.DataFrame) -> dict[str, Any]: + stationsDict = {} + for idx in range(len(info)): + aux = info.iloc[idx] + + micro, sec = tuple(map(int, modf(aux["Seg"]))) + hms = time(hour=aux["Hora"],minute=aux["Min"], second=sec, microsecond=micro).strftime("%H:%M:%S.%f") + station = {"Componente": aux["Componente"], "Hora": hms, "Distancia": float(aux["DIS"])} + + if type(aux["Tipo Onda"]) != float: + station.update({"Tipo Onda": aux["Tipo Onda"]}) + if aux["Tipo Onda"] == "IAML": + station.update({"Amplitude": float(aux["Amplitude"])}) + + + if aux["Estacao"] not in stationsDict.keys(): + stationsDict[aux["Estacao"]] = [station] + else: + stationsDict[aux["Estacao"]].append(station) + return {"Estacoes": stationsDict} + + +def create_mag_info(magnitudes): + mags = {} + for value in magnitudes: + mags[value["Tipo"]] = value["Magnitude"] + return mags + + +if __name__ == '__main__': + import parser + + df = parser.parse("dados.txt") + a = create_dict_struct(df, None, None) + save_as_json(a)