This code is a script for analyzing possible neutral problems...

August 28, 2025 at 06:35 PM

import os import pandas as pd import numpy as np from datetime import datetime # Configurações do sistema CAMINHO_PASTA = r"C:\Users\bso4\Downloads\Nivel de Tensao" NOME_PLANILHA = "dados_nivel_tensao.xlsx" caminho_excel = os.path.join(CAMINHO_PASTA, NOME_PLANILHA) # Arquivos de saída arquivo_resultado = os.path.join(CAMINHO_PASTA, "resultado_analise.txt") arquivo_excel_resultado = os.path.join(CAMINHO_PASTA, "resultado_detalhado.xlsx") print("🔧 ROBÔ DE ANÁLISE DE PROBLEMAS DE NEUTRO") print("=" * 60) if not os.path.exists(caminho_excel): print(f"❌ Arquivo não encontrado: {caminho_excel}") print("💡 Verifique se o arquivo está na pasta correta") else: print(f"📊 Lendo planilha: {caminho_excel}") try: # Lê a planilha Excel df = pd.read_excel(caminho_excel) # Verifica se as colunas necessárias existem colunas_necessarias = ['Fase A', 'Fase B', 'Fase C'] for coluna in colunas_necessarias: if coluna not in df.columns: raise ValueError(f"Coluna '{coluna}' não encontrada na planilha") # Função mais inteligente para análise de neutro def analisar_problemas_neutro(row): # Pega somente os valores preenchidos valores = [row[col] for col in colunas_necessarias if pd.notna(row[col])] # Caso não haja dados suficientes if len(valores) < 2: return "Não analisado", "Normal", "Poucos dados para análise" # Se todos os valores são iguais if len(set(valores)) == 1: return "OK", "Normal", "Tensões equilibradas" # Caso haja diferenças entre os valores possível problema de neutro # Detecta tendência entre as fases if valores == sorted(valores): tendencia = "Aumentando" elif valores == sorted(valores, reverse=True): tendencia = "Diminuindo" else: tendencia = "Instável" # Calcula diferença máxima entre as fases para detalhar diferenca = max(valores) - min(valores) return "Possível problema de neutro", tendencia, f"Variação entre fases: {diferenca:.1f}V" # Aplica a análise para cada linha print("🔍 Analisando dados...") resultados = df.apply(analisar_problemas_neutro, axis=1) df[['Tipo_Problema', 'Tendência', 'Detalhes']] = pd.DataFrame(resultados.tolist(), index=df.index) # Estatísticas gerais total_clientes = len(df) clientes_ok = len(df[df['Tipo_Problema'] == 'OK']) clientes_problema = len(df[df['Tipo_Problema'].str.contains('neutro', case=False)]) # Monta relatório detalhado relatorio = [] relatorio.append("=" * 60) relatorio.append("📋 RELATÓRIO DE ANÁLISE DE PROBLEMAS DE NEUTRO") relatorio.append("=" * 60) relatorio.append(f"📅 Data da análise: {datetime.now().strftime('%d/%m/%Y %H:%M')}") relatorio.append(f"📊 Arquivo analisado: {NOME_PLANILHA}") relatorio.append("") relatorio.append("📈 ESTATÍSTICAS GERAIS:") relatorio.append(f" • Total de clientes analisados: {total_clientes}") relatorio.append(f" • Clientes OK: {clientes_ok}") relatorio.append(f" • Possíveis problemas de neutro: {clientes_problema}") relatorio.append("") # Lista os clientes com possíveis problemas problemas = df[df['Tipo_Problema'].str.contains('neutro', case=False)] if len(problemas) > 0: relatorio.append("🔍 CLIENTES COM POSSÍVEL PROBLEMA DE NEUTRO:") for _, row in problemas.iterrows(): relatorio.append(f"⚡ Cliente: {row.get('ID_Cliente', 'Sem ID')}") relatorio.append(f" Fases → A={row['Fase A']}V | B={row['Fase B']}V | C={row['Fase C']}V") relatorio.append(f" Status: {row['Tipo_Problema']} | Tendência: {row['Tendência']}") relatorio.append(f" Detalhes: {row['Detalhes']}") relatorio.append("") else: relatorio.append("✅ Nenhum problema de neutro detectado") relatorio.append("=" * 60) # Salva relatório em TXT with open(arquivo_resultado, 'w', encoding='utf-8') as f: f.write('\n'.join(relatorio)) # Salva planilha detalhada em Excel df.to_excel(arquivo_excel_resultado, index=False) # Resumo final no console print("✅ ANÁLISE CONCLUÍDA!") print("=" * 40) print(f"📁 Relatório salvo: {arquivo_resultado}") print(f"📊 Excel detalhado: {arquivo_excel_resultado}") print("") print("📈 RESULTADOS:") print(f" • Clientes analisados: {total_clientes}") print(f" • Possíveis problemas de neutro: {clientes_problema}") print(f" • Clientes OK: {clientes_ok}") except Exception as e: print(f"❌ ERRO: {e}") print("💡 Verifique a estrutura do arquivo Excel")

This code is a script for analyzing possible neutral problems in an electrical system based on voltage data for three phases (Phase A, Phase B, and Phase C) extracted from an Excel file. Here’s what it does step-by-step:


Key Actions:

  1. Setup and Initialization:

    • The script sets up folder paths and filenames for input and output files.
    • CAMINHO_PASTA and NOME_PLANILHA specify the folder and name of the input Excel file.
    • Checks if the input Excel file exists. If not, it notifies the user and exits.
  2. Reading the Excel File:

    • Reads the Excel file into a Pandas DataFrame (df).
    • Verifies if the required columns ['Fase A', 'Fase B', 'Fase C'] exist in the DataFrame. If one or more are missing, it raises an exception.
  3. Analyzing Neutral Problems:

    • Defines a function, analisar_problemas_neutro, to analyze potential neutral problems for each row based on Phase A, Phase B, and Phase C voltage values.
      • If insufficient data is available (less than two non-null values), marks the row as "Not analyzed".
      • If all phase voltages are equal, considers the voltages as balanced and marks the result as "Normal".
      • If there is variation between the voltages, it calculates the difference between minimum and maximum voltages and determines if the tendency in the phases is increasing, decreasing, or unstable. This suggests a "possible neutral problem".
    • This function is applied to each row of the DataFrame, and results are stored in new columns: Tipo_Problema, Tendência, and Detalhes.
  4. Generating Statistical Insights:

    • Summarizes the total number of rows, how many cases are "OK," and how many have a "possible neutral problem."
  5. Generating and Saving Reports:

    • Compiles a detailed report in plain text format describing the analysis results, including statistical insights and records of customers with potential problems.
    • Saves the updated DataFrame (with analysis results) to a new Excel file.
  6. Output and Logs:

    • Displays a summary of the results in the console, including file paths where the detailed report (resultado_analise.txt) and Excel output (resultado_detalhado.xlsx) are saved.
  7. Error Handling:

    • If any errors occur (e.g., missing columns, issues reading the Excel file), the script provides an error message guiding the user to verify the Excel file's structure.

What the Outputs Represent:

  • TXT Report (resultado_analise.txt):
    • Includes overall statistics, a summary of the analysis, and a list of customers flagged as having possible neutral problems.
  • Excel File (resultado_detalhado.xlsx):
    • The original data with additional columns containing the analysis results for each customer.

Summary of Purpose:

This script automates the process of:

  • Identifying potential electrical neutral issues by analyzing phase voltages.
  • Producing actionable insights and saving them in a human-readable format (TXT and Excel).
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node