Advertisement
Python253

array_plotter

May 24th, 2024
371
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.99 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: array_plotter.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script reads multiple arrays from a file and plots each array as a smooth spline on a single graph.
  10.    - It displays a legend showing the average values of each array.
  11.    - Additionally, the script prints the indices, values, and averages of each array to the console.
  12.  
  13. Requirements:
  14.    - Python 3.x
  15.    - matplotlib
  16.    - numpy
  17.    - scipy
  18.    - tkinter
  19.  
  20. Functions:
  21.    - read_arrays_from_file(file_path):
  22.        Reads arrays from the specified file.
  23.    - select_file():
  24.        Prompts the user to select a file using a file dialog.
  25.    - plot_arrays(arrays):
  26.        Plots the given arrays with smooth splines and displays the average values in the legend.
  27.    - main():
  28.        The main function that coordinates reading the file, printing array details, plotting the arrays, and handling any errors.
  29.  
  30. Usage:
  31.    - Run the script in a Python environment with the required libraries installed.
  32.    - A file dialog will prompt you to select a file containing arrays.
  33.    - The script will print the array indices, values, and averages to the console.
  34.    - A plot window will display the arrays with smooth splines and a legend showing their average values.
  35.    - Closing the plot window will terminate the script with a goodbye message.
  36.  
  37. Additional Notes:
  38.    - Ensure the input file is properly formatted, with each array on a new line and values separated by commas.
  39.    - The script uses Tkinter for the file dialog, which may require a GUI environment to run properly.
  40. """
  41.  
  42. import os
  43. import tkinter as tk
  44. from tkinter import filedialog
  45. import numpy as np
  46. import matplotlib.pyplot as plt
  47. from scipy.interpolate import make_interp_spline
  48.  
  49. def read_arrays_from_file(file_path):
  50.     """
  51.    Reads arrays of floating-point numbers from a specified file.
  52.  
  53.    Args:
  54.        file_path (str): The path to the file containing arrays.
  55.  
  56.    Returns:
  57.        list of list of float: A list where each element is a list of floating-point numbers
  58.        representing an array from the file.
  59.    """
  60.     with open(file_path, 'r') as file:
  61.         lines = file.readlines()
  62.         arrays = []
  63.         for line in lines:
  64.             array = [float(num.strip('[],\n')) for num in line.split()]
  65.             arrays.append(array)
  66.         return arrays
  67.  
  68. def select_file():
  69.     """
  70.    Opens a file dialog for the user to select a file containing arrays.
  71.  
  72.    Returns:
  73.        str: The file path of the selected file, or an empty string if no file was selected.
  74.    """
  75.     root = tk.Tk()
  76.     root.withdraw()  # Hide the main window
  77.     file_path = filedialog.askopenfilename(title="Select file with arrays", filetypes=[("Text files", "*.txt")])
  78.     return file_path
  79.  
  80. def plot_arrays(arrays):
  81.     """
  82.    Plots the given arrays with smooth splines and displays the average values in the legend.
  83.  
  84.    Args:
  85.        arrays (list of list of float): A list where each element is a list of floating-point numbers
  86.        representing an array to plot.
  87.    """
  88.     colors = plt.cm.tab10(np.linspace(0, 1, len(arrays)))
  89.     for i, array in enumerate(arrays):
  90.         x = np.arange(len(array))
  91.         y = np.array(array)
  92.         x_smooth = np.linspace(x.min(), x.max(), 300)
  93.         spl = make_interp_spline(x, y, k=3)
  94.         y_smooth = spl(x_smooth)
  95.         avg_value = np.mean(array)
  96.         label = f'A{i+1:02d} ( Avg: {avg_value:.2f})' if i < 9 else f'A{i+1:02d} (Avg: {avg_value:.2f})'
  97.         plt.plot(x_smooth, y_smooth, color=colors[i], label=label)
  98.         plt.scatter(x, y, color=colors[i], marker='o')
  99.     plt.xlabel('Index')
  100.     plt.ylabel('Value')
  101.     plt.title('Arrays Plot')
  102.     plt.grid(True)
  103.     plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
  104.     plt.show()
  105.  
  106. def main():
  107.     """
  108.    The main function that coordinates reading the file, printing array details, plotting the arrays,
  109.    and handling any errors.
  110.    """
  111.     print("-" * 25)
  112.     file_path = select_file()
  113.     if not file_path:
  114.         print("\nNo file selected!\n\nExiting Program...   GoodBye!\n")
  115.         return
  116.     try:
  117.         arrays = read_arrays_from_file(file_path)
  118.         overall_averages = []
  119.         for i, array in enumerate(arrays):
  120.             print(f"Array {i + 1} Index:")
  121.             for idx, val in enumerate(array, start=1):
  122.                 print(f" {idx}: {val}")
  123.                
  124.             average = np.mean(array)
  125.             overall_averages.append(average)
  126.             print(f"Array {i + 1} Average: {average:.2f}\n")
  127.             print("-" * 25)
  128.        
  129.         print("All Arrays Averages:\n")
  130.         for i, average in enumerate(overall_averages, start=1):
  131.             print(f" Array {i} Average: {average:.2f}")
  132.        
  133.         plot_arrays(arrays)
  134.     except Exception as e:
  135.         print(f"\nAn error occurred: {e}")
  136.         exit(1)
  137.  
  138.     print("\nPlot window closed. Goodbye!")
  139.     exit(0)
  140.  
  141. if __name__ == "__main__":
  142.     main()
  143.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement