Advertisement
Python253

array_plot_smooth_spline

May 23rd, 2024
644
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.51 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: array_plot_smooth_spline.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    This script generates a plot of an array of values with a smooth spline passing through the array points.
  10.    It also calculates the sum and average of the array, and plots the maximum area rectangular histogram.
  11.  
  12. Requirements:
  13.    - Python 3.x
  14.    - matplotlib
  15.    - numpy
  16.    - scipy
  17.  
  18. Functions:
  19.    - max_area_histogram(heights): Calculates the maximum area of a rectangular histogram given an array of heights.
  20.  
  21. Usage:
  22.    - Run the script and input the number of elements in the array and the array values.
  23.    - The script will plot the array values with a smooth spline passing through them.
  24.    - It will also display the sum and average of the array, and calculate the maximum area rectangular histogram.
  25.  
  26. Example Output:
  27.  
  28.    Enter the number of elements in the array: 6
  29.    Enter the array elements one by one. Hit Enter after each value:
  30.    2
  31.    5
  32.    3
  33.    2
  34.    5
  35.    3
  36.    Array: [2, 5, 3, 2, 5, 3]
  37.    Sum of the array: 20
  38.    Average of the array: 3.3333333333333335
  39.    Maximum area rectangular histogram: 12
  40.  
  41. Additional Notes:
  42.    - The smooth spline is generated using interpolation techniques.
  43.    - The area under the smooth spline is filled with a transparent color for visualization.
  44. """
  45.  
  46. # Get Essential Imports
  47. import matplotlib.pyplot as plt
  48. import numpy as np
  49. from scipy.interpolate import make_interp_spline
  50.  
  51. def max_area_histogram(heights):
  52.     """
  53.    Calculate the maximum area of a rectangular histogram given an array of heights.
  54.  
  55.    This function implements the histogram algorithm to calculate the maximum area
  56.    that can be obtained from a rectangular histogram formed by the given heights.
  57.  
  58.    Parameters:
  59.    heights (list): A list of integers representing the heights of the histogram bars.
  60.  
  61.    Returns:
  62.    int: The maximum area of the rectangular histogram.
  63.    """
  64.     stack: list = []
  65.     max_area = 0
  66.     index = 0
  67.     while index < len(heights):
  68.         if not stack or heights[index] >= heights[stack[-1]]:
  69.             stack.append(index)
  70.             index += 1
  71.         else:
  72.             top_of_stack = stack.pop()
  73.             area = (heights[top_of_stack] * ((index - stack[-1] - 1) if stack else index))
  74.             max_area = max(max_area, area)
  75.     while stack:
  76.         top_of_stack = stack.pop()
  77.         area = (heights[top_of_stack] * ((index - stack[-1] - 1) if stack else index))
  78.         max_area = max(max_area, area)
  79.     return max_area
  80.  
  81. # Input
  82. while True:
  83.     try:
  84.         n = int(input("Enter the number of elements in the array: "))
  85.         if n <= 0:
  86.             print("Please enter a positive integer for the number of elements.")
  87.             continue
  88.         print("Enter the array elements one by one. Hit Enter after each value:")
  89.         array_heights = []
  90.         for i in range(n):
  91.             height = int(input())
  92.             array_heights.append(height)
  93.  
  94.         # Output the array
  95.         print("Array:", array_heights)
  96.  
  97.         # Calculate and output the sum of the array
  98.         array_sum = sum(array_heights)
  99.         print("Sum of the array:", array_sum)
  100.  
  101.         # Calculate the average of the array
  102.         array_average = array_sum / n
  103.         print("Average of the array:", array_average)
  104.  
  105.         # Generate a smooth spline passing through the array points
  106.         x = np.arange(n)
  107.         y = array_heights
  108.         spline = make_interp_spline(x, y)
  109.         x_smooth = np.linspace(0, n-1, 1000)
  110.         y_smooth = spline(x_smooth)
  111.  
  112.         # Plot the array and spline
  113.         plt.figure(figsize=(10, 6))
  114.         plt.plot(x_smooth, y_smooth, color='red', linewidth=2, label='Smooth Spline')
  115.         plt.fill_between(x_smooth, y_smooth, color='pink', alpha=0.75)  # Fill under the spline with color
  116.         plt.scatter(x, y, color='blue', marker='o', label='Array Points')
  117.         for i, txt in enumerate(array_heights):
  118.             plt.annotate(str(txt), (x[i], y[i]), textcoords="offset points", xytext=(0,10), ha='center')
  119.         plt.xlabel('Index')
  120.         plt.ylabel('Value')
  121.         plt.title('Array Plot with Smooth Spline')
  122.         plt.legend()
  123.         plt.grid(True)
  124.         plt.show()
  125.  
  126.         # Calculate and output the maximum area rectangular histogram
  127.         print("Maximum area rectangular histogram:", max_area_histogram(array_heights))
  128.         break
  129.     except ValueError:
  130.         print("Invalid input. Please enter a valid integer.")
  131.  
  132.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement