diff --git a/earthquakes.py b/earthquakes.py index 95def72..0696cc3 100644 --- a/earthquakes.py +++ b/earthquakes.py @@ -2,6 +2,7 @@ # pyright: basic import os +from datetime import datetime import pandas as pd @@ -13,11 +14,10 @@ MENU ="""[1] Criar a base de dados [2] Atualizar uma entrada [3] Apagar um evento [4] Apagar uma entrada de um evento -[5] Visualizar uma entrada +[5] Visualizar um evento [6] Guardar como JSON [7] Guardar como CSV [8] Estatísticas -[9] Atualizar uma entrada de um evento [Q] Sair """ @@ -78,9 +78,22 @@ def main(): case "2": if db is not None: - continue - else: - retInfo = "Base de dados não encontrada!" + 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: @@ -111,13 +124,10 @@ def main(): table = crud.get_table(db, eid_choice) _prettify_event(table) 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 - row_choice = _get_usr_input("Escolhe a linha a apagar:", int) - + row_choice = _get_usr_input("Escolhe a linha a apagar:", int) # TODO: balizar a escolha para apenas as linhas do evento em questao - row_choice = _get_usr_input("Escolhe a linha a apagar: ", int) + db = crud.delete_table_row(db, eid_choice, row_choice) new_table = crud.get_table(db, eid_choice) crud.show_table(new_table) @@ -137,6 +147,7 @@ def main(): else: table = crud.get_table(db, choice) + _prettify_event(table) crud.show_table(table) input() @@ -167,25 +178,6 @@ def main(): else: retInfo = "Base de dados não encontrada!" - case "9": - 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 "q": isRunning = False continue @@ -220,11 +212,6 @@ def _prettify_event(df): preambleInfo = df.drop_duplicates(subset="ID", keep="first") stations = df[["Estacao", "Componente", "Tipo Onda", "Amplitude"]] info = df.drop_duplicates(subset="Data", keep="first") - stations = df[["Estacao", "Componente", "Tipo Onda", "Amplitude"]] - data = datetime.fromisoformat(info.Data.values[0]).strftime("%c") - print(f"Região: {info["Regiao"].values[0]}\nData: {data}\nLatitude: {info.Lat.values[0]}\nLongitude: {info.Long.values[0]}" - + f"\nProfundidade: {info.Prof.values[0]}\nTipo de evento: {info['Tipo Ev'].values[0]}\n") - info = df.drop_duplicates(subset="Data", keep="first") data = datetime.fromisoformat(info.Data.values[0]).strftime("%c") print(f"Região: {info["Regiao"].values[0]}\nData: {data}\nLatitude: {info.Lat.values[0]}\nLongitude: {info.Long.values[0]}" + f"\nProfundidade: {info.Prof.values[0]}\nTipo de evento: {info['Tipo Ev'].values[0]}\n") diff --git a/utils/crud.py b/utils/crud.py index 0dcfc4e..9ba67c5 100644 --- a/utils/crud.py +++ b/utils/crud.py @@ -1,29 +1,37 @@ # pyright: basic import pandas as pd -from . import parser pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 150) +# -- globals + HEADER_COLS = ["Data", "Distancia", "Tipo Ev", "Lat", "Long", "Prof", "Magnitudes"] -TABLE_READ_RET = ["Data", "Lat", "Long", "Distancia", "Tipo Ev", "Amplitude"] +TABLE_READ_RET = ["Estacao","Componente","", "Amplitude"] + +# -- helper funcs def _get_uniques(df) -> pd.DataFrame: return df.get(["ID", "Data", "Regiao"]).drop_duplicates(subset="ID", keep="first") + def _show_events(df): for (_, row) in df.iterrows(): print(f"{row["ID"]}: {row["Regiao"]}") +# -- main + def read_ids(df): ids = _get_uniques(df) _show_events(ids) + def get_unique_events_table(df): return df.drop_duplicates(subset="ID", keep="first") + def read_header(df, event_id): # Informações do header do evento row = df[df["ID"] == event_id].iloc[0] @@ -37,12 +45,13 @@ def read_header(df, event_id): infoString = f"Header do evento {event_id}:\n" + "\n".join(info) return infoString + def show_table(df, retCols=TABLE_READ_RET): print(df.loc[:,retCols]) + def get_table(df, event_id): rows = df[df["ID"] == event_id] - rows = rows.drop("ID", axis=1) return rows @@ -61,12 +70,14 @@ def read_table_row(df, event_id, row_number_1): info.append(f"{i+1} {col}: {row[col]}") return f"Linha {row_number_1:02d} do evento {event_id}:\n" + "\n".join(info) + def update_table_row(df, row_line, new_data): for key, value in new_data.items(): if key in df.columns: df.loc[row_line, key] = value return f"Linha {row_line} do evento atualizada com sucesso." + def update_header(df, event_id, new_data): # atualiza o header de um evento for key, value in new_data.items(): @@ -74,17 +85,20 @@ def update_header(df, event_id, new_data): df.loc[(df["ID"] == event_id) | df.iloc[0], key] = value return f"Header do evento {event_id} atualizado com sucesso." + def delete_event(df, event_id): # Apaga um evento inteiro (header + tabela) new_df = df.drop(df[df["ID"] == event_id].index) print(f"Evento {event_id} apagado!") return new_df + def delete_table_row(df, event_id, row_number): # Apaga uma linha específica da tabela do evento new_df = df.drop([row_number]).reset_index(drop=True) return new_df + def create_blank_event(df, event_id): # Criar um evento vazio com linha de header e 1 linha de coluna df.loc[df["ID"] >= event_id, "ID"] += 1 @@ -98,7 +112,7 @@ def create_blank_event(df, event_id): return new_df - + def create_table_row(df, event_id, row_number_1): event_rows = df[df["ID"] == event_id] if event_rows.empty: diff --git a/utils/stats.py b/utils/stats.py index a5155ed..cbb97c6 100644 --- a/utils/stats.py +++ b/utils/stats.py @@ -5,7 +5,7 @@ import os import pandas as pd import numpy as np -STAT_HEADER ="""=== Earthquakes === +STAT_HEADER ="""=== Terramotos === == Estatísticas == """ @@ -51,12 +51,14 @@ def stat_menu(df: pd.DataFrame): match usrIn: case "1": - # TODO: verificar se estamos a tratar de numeros ou strings c = filter_submenu("Média") if c is not None: retValue = average(df, c) - print(f"A média de {c} é {retValue}") + if retValue: + print(f"A média de {c} é {retValue}") + else: + print("Um erro aconteceu. Nada a apresentar de momento.") else: continue @@ -65,17 +67,22 @@ def stat_menu(df: pd.DataFrame): if c is not None: retValue = variance(df, c) - print(f"A variância dos dados de {c} é {retValue}") + if retValue: + print(f"A variância dos dados de {c} é {retValue}") + else: + print("Um erro aconteceu. Nada a apresentar de momento.") else: continue case "3": - # TODO: verificar se estamos a tratar de numeros ou strings c = filter_submenu("Desvio Padrão") if c is not None: retValue = std_dev(df, c) - print(f"O desvio padrão de {c} é {retValue}") + if retValue: + print(f"O desvio padrão de {c} é {retValue}") + else: + print("Um erro aconteceu. Nada a apresentar de momento.") else: continue @@ -112,7 +119,7 @@ def stat_menu(df: pd.DataFrame): case _: pass - input("Clica Enter para continuar") + input("Clica `Enter` para continuar") def average(df: pd.DataFrame, filter_by): @@ -121,8 +128,10 @@ def average(df: pd.DataFrame, filter_by): if filter_by == "Magnitudes": values = _unpack_mags(values) - - return np.average(values) + try: + return np.average(values) + except: + return None def variance(df, filter_by): @@ -132,7 +141,10 @@ def variance(df, filter_by): if filter_by == "Magnitudes": values = _unpack_mags(values) - return np.var(values) + try: + return np.var(values) + except: + return None def std_dev(df, filter_by): @@ -142,7 +154,10 @@ def std_dev(df, filter_by): if filter_by == "Magnitudes": values = _unpack_mags(values) - return np.std(values) + try: + return np.std(values) + except: + return None def max_v(df, filter_by): @@ -164,6 +179,7 @@ def min_v(df, filter_by): return np.min(values) + def moda(df, filter_by): events = df.drop_duplicates(subset="ID", keep='first') values = events[filter_by].to_numpy()