Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: metal_albedo_analysis_tool_plus.py
- # Version: 1.0.1
- # Author: Jeoi Reqi
- """
- Description:
- - This script provides a comprehensive suite of tools for analyzing the optical properties of metals and common materials, focusing on albedo and index of refraction (IOR).
- - Albedo refers to the proportion of incident light that is reflected by a surface, making it a crucial factor in determining the visual appearance of metals and materials.
- - Index of refraction (IOR) quantifies how light bends as it passes through a material, influencing its optical properties such as reflection and refraction.
- - By leveraging the provided functionalities, users can explore and understand the albedo characteristics of various metals and common materials.
- - Users can also compare the metal IOR values to gain insights into their optical behaviors.
- - This script also outputs the difference in value of the compared metal IOR to the terminal.
- Requirements:
- - Python 3.x
- - Numpy module for numerical computations & array manipulation
- - Matplotlib library for data visualization
- Functions:
- - visualize_metal_colors():
- Visualizes metal colors by plotting their albedo.
- - display_metal_data():
- Displays the available metal data as a numbered list.
- - calculate_albedo():
- Calculates the albedo of a specific metal selected by the user.
- - compare_ior(metal1, metal2):
- Compares the index of refraction between two metals selected by the user.
- - visualize_common_materials_albedo():
- Visualizes the albedo of common materials.
- - visualize_metal_ior():
- Visualizes the index of refraction (IOR) of metals by plotting their values.
- - search_metal_by_ior():
- Allows the user to search for metals based on a specified range of index of refraction (IOR) values.
- - visualize_common_materials_ior():
- Visualizes the index of refraction (IOR) of common materials.
- Usage:
- - Run the script in a Python environment.
- - Follow the on-screen menu options to choose between different functionalities.
- - Enter the appropriate input as prompted to perform desired actions.
- Example Output:
- :: MENU OPTIONS ::
- 1. Visualize Metal Colors
- 2. Calculate Albedo
- 3. Compare Index of Refraction
- 4. Visualize Albedo of Common Materials
- 0. Exit
- Enter your choice (0-4): 3
- Metal data:
- 1. Aluminum
- 2. Brass
- 3. Chrome
- 4. Cobalt
- 5. Copper
- 6. Gold
- 7. Iron
- 8. Lead
- 9. Mercury
- 10. Nickel
- 11. Palladium
- 12. Platinum
- 13. Silver
- 14. Titanium
- 15. Zinc
- Enter the number of the first metal: 7
- Enter the number of the second metal: 11
- Palladium has a higher Index of Refraction (1.0250) than Iron (1.0060).
- The difference is 0.0190.
- Additional Notes:
- - Metal data includes information such as RGB values and index of refraction.
- - The script utilizes Matplotlib for data visualization.
- - Users can interactively explore metal properties and compare them using this tool.
- """
- import numpy as np
- import matplotlib.pyplot as plt
- # Common Metal Data
- """
- - This dictionary contains data about common metals including their RGB color values and Index of Refraction (IOR).
- * metal_data : dict
- A dictionary where each key represents a metal name and each value is another dictionary containing the following:
- - Color_RGB: Tuple representing the color of the metal in RGB format.
- - IOR: Index of Refraction value for the metal.
- """
- metal_data = {
- "Aluminum": {"Color_RGB": (245, 246, 246), "IOR": 1.002},
- "Brass": {"Color_RGB": (214, 185, 123), "IOR": 1.005},
- "Chrome": {"Color_RGB": (196, 197, 197), "IOR": 1.03},
- "Cobalt": {"Color_RGB": (211, 210, 207), "IOR": 1.031},
- "Copper": {"Color_RGB": (250, 208, 192), "IOR": 1.219},
- "Gold": {"Color_RGB": (255, 226, 155), "IOR": 1.350},
- "Iron": {"Color_RGB": (198, 198, 200), "IOR": 1.006},
- "Lead": {"Color_RGB": (67, 69, 71), "IOR": 1.016},
- "Mercury": {"Color_RGB": (229, 228, 228), "IOR": 1.013},
- "Nickel": {"Color_RGB": (211, 203, 190), "IOR": 1.016},
- "Palladium": {"Color_RGB": (222, 217, 211), "IOR": 1.025},
- "Platinum": {"Color_RGB": (213, 208, 200), "IOR": 1.024},
- "Silver": {"Color_RGB": (252, 250, 245), "IOR": 1.082},
- "Titanium": {"Color_RGB": (195, 186, 177), "IOR": 1.086},
- "Zinc": {"Color_RGB": (213, 234, 237), "IOR": 1.011},
- }
- # Common Materials & Their Albedo Range (Min, Max)
- """
- - This dictionary contains data about common materials along with their albedo range, represented by a tuple containing the min and max values.
- * common_materials : dict
- - A dictionary where each key represents a material name, and each value is a tuple containing the albedo range (minimum, maximum).
- If the maximum value is not available, it is represented as `None`.
- """
- common_materials = {
- "Acrylic glass": (1.490, 1.492),
- "Air": (1.000, None),
- "Alabaster": (0.92, 0.92),
- "Alcohol, Ethyl (grain)": (1.360, None),
- "Aluminum": (1.390, 1.440),
- "Asphalt": (1.635, None),
- "Beer": (1.345, None),
- "Black Acrylic Paint": (0.05, 0.05),
- "Bronze": (1.180, None),
- "Colored Paint": (0.15, 0.35),
- "Crystal": (2.000, None),
- "Diamond": (2.418, None),
- "Emerald": (1.560, 1.605),
- "Eye, Lens": (1.410, None),
- "Forged Iron": (0.04, 0.04),
- "Glass": (1.500, None),
- "Glass, Pyrex": (1.474, None),
- "Gold": (0.470, None),
- "Granite Gray": (0.35, 0.4),
- "Ice": (1.309, None),
- "Iron": (2.950, None),
- "Ivory": (1.540, None),
- "Lead": (2.010, None),
- "Lucite": (1.495, None),
- "Magnesium Oxide": (0.96, 0.96),
- "Mercury (liquid)": (1.620, None),
- "Milk": (1.350, None),
- "Natural Silk Fabric": (0.35, 0.55),
- "Nickel": (1.080, None),
- "Nylon": (1.530, None),
- "Pearl": (1.530, 1.690),
- "Plaster": (0.4, 0.45),
- "Plastic": (1.460, None),
- "Skin": (0.25, 0.35),
- "Teflon": (1.350, 1.380),
- "Titanium": (2.160, None),
- "Vodka": (1.363, None),
- "Water (35 deg C)": (1.325, None),
- "White Acrylic Paint": (0.8, 0.8),
- "White Gypsum": (0.85, 0.85),
- "White Paper Sheet": (0.6, 0.7),
- }
- # Function To Visualize Metal Colors
- def visualize_metal_colors():
- """
- Visualize the albedo of common metals.
- - This function generates a horizontal bar plot visualizing the albedo (mean color) of common metals.
- - Each bar represents a metal, and its length corresponds to the albedo value.
- """
- color_values = []
- metal_names = []
- # Sort metal data alphabetically by metal names
- sorted_metal_data = sorted(metal_data.items(), key=lambda x: x[0])
- for metal_name, metal_data_single in sorted_metal_data:
- metal_names.append(metal_name)
- color_values.append(np.mean(metal_data_single["Color_RGB"]) / 255)
- plt.figure(figsize=(10, 6))
- plt.title('Metal Albedo')
- # Reverse the order of metal names
- metal_names = metal_names[::-1]
- color_values = color_values[::-1]
- bars = plt.barh(metal_names, color_values, color='green')
- plt.xlabel('Albedo')
- plt.ylabel('Metal')
- plt.grid(axis='x')
- plt.xlim(0.65, 1.0) # Set the x-axis limits to start at 0.65
- # Add annotations to each bar
- for bar in bars:
- width = bar.get_width()
- plt.text(width, bar.get_y() + bar.get_height() / 2,
- f'{width:.3f}',
- va='center', ha='left',
- color='black', fontweight='bold')
- plt.show()
- # Function To Display Metal Data As A Numbered List
- def display_metal_data():
- """
- Display metal data as a numbered list.
- - This function prints the list of common metals along with their index numbers.
- """
- print("\nMetal data:")
- for index, (metal_name, _) in enumerate(metal_data.items(), start=1):
- print(f"{index:2}. {metal_name}")
- # Function To Calculate The Albedo Of A Specific Metal
- def calculate_albedo():
- """
- Calculate the albedo of a specific metal.
- - This function prompts the user to select a metal from the list and calculates its albedo.
- """
- # Step 1: Display the list of available metals.
- display_metal_data()
- # Step 2: Prompt the user to select a metal from the list.
- metal_index_str = input("\nEnter the number of the metal: ")
- try:
- metal_index = int(metal_index_str)
- if 1 <= metal_index <= len(metal_data):
- metal_name = list(metal_data.keys())[metal_index - 1]
- metal_single = metal_data[metal_name]
- # Step 3: Calculate the albedo of the selected metal.
- albedo = np.mean(metal_single["Color_RGB"]) / 255
- print(f"\nThe albedo of {metal_name} is: {albedo:.4f}")
- else:
- print("\nInvalid metal number!")
- except ValueError:
- print("\nInvalid input! Please enter a valid number.")
- # Function To Compare The Index Of Refraction Between Two Metals
- def compare_ior(metal1_str, metal2_str):
- """
- Compare the Index of Refraction (IOR) between two metals.
- - This function takes two metal indices as input and compares their IOR values.
- """
- try:
- # Step 1: Convert input strings to integers.
- metal1_index = int(metal1_str)
- metal2_index = int(metal2_str)
- # Step 2: Check if the input indices are within the valid range.
- if 1 <= metal1_index <= len(metal_data) and 1 <= metal2_index <= len(metal_data):
- # Step 3: Retrieve metal names based on the input indices.
- metal1_name = list(metal_data.keys())[metal1_index - 1]
- metal2_name = list(metal_data.keys())[metal2_index - 1]
- metal1_data = metal_data[metal1_name]
- metal2_data = metal_data[metal2_name]
- # Step 4: Compare the IOR values of the two metals.
- if metal1_data["IOR"] > metal2_data["IOR"]:
- print(f"\n{metal1_name} has a higher Index of Refraction ({metal1_data['IOR']:.4f}) than {metal2_name} ({metal2_data['IOR']:.4f}).")
- print(f"The difference is {metal1_data['IOR'] - metal2_data['IOR']:.4f}.")
- elif metal1_data["IOR"] < metal2_data["IOR"]:
- print(f"\n{metal2_name} has a higher Index of Refraction ({metal2_data['IOR']:.4f}) than {metal1_name} ({metal1_data['IOR']:.4f}).")
- print(f"The difference is {metal2_data['IOR'] - metal1_data['IOR']:.4f}.")
- else:
- print(f"\nThe Index of Refraction of {metal1_name} ({metal1_data['IOR']:.4f}) and {metal2_name} ({metal2_data['IOR']:.4f}) are equal.")
- else:
- print("\nInvalid metal numbers!")
- except ValueError:
- print("\nInvalid input! Please enter valid numbers.")
- print()
- # Function To Visualize Albedo Of Common Materials
- def visualize_common_materials_albedo():
- """
- Visualize the albedo of common materials.
- - This function generates a horizontal bar plot visualizing the albedo range of common materials.
- - Each bar represents a material, and the range of albedo is shown using two colors for minimum and maximum values.
- """
- material_names = list(common_materials.keys())
- min_values = [common_materials[material][0] if common_materials[material][0] is not None else 0 for material in material_names]
- max_values = [common_materials[material][1] if common_materials[material][1] is not None else 0 for material in material_names]
- y_pos = np.arange(len(material_names))
- # Reverse the y_pos array
- y_pos = y_pos[::-1]
- plt.figure(figsize=(14, 18))
- plt.title('Albedo of Common Materials')
- # Step 1: Create horizontal bar plot
- bars_max = plt.barh(y_pos, max_values, color='yellow', label='Max')
- bars_min = plt.barh(y_pos, min_values, color='green', alpha=0.5, label='Min')
- plt.yticks(y_pos, material_names)
- plt.xlabel('Albedo Range')
- plt.ylabel('Material')
- plt.legend(loc='upper right')
- plt.grid(axis='x')
- plt.xlim(0, 3.6)
- # Step 2: Add annotations to each bar for max values with the range
- for bar_max, bar_min, max_val, min_val in zip(bars_max, bars_min, max_values, min_values):
- if max_val != 0:
- annotation = f"[MIN: {min_val:.3f} - MAX: {max_val:.3f}]"
- plt.text(bar_max.get_width(), bar_max.get_y() + bar_max.get_height() / 2,
- annotation,
- va='center', ha='left',
- color='black', fontweight='bold')
- elif min_val != 0:
- annotation = f"[MIN: {min_val:.3f} - MAX: N/A]"
- plt.text(bar_min.get_width(), bar_min.get_y() + bar_min.get_height() / 2,
- annotation,
- va='center', ha='left',
- color='black', fontweight='bold')
- plt.show()
- # Menu-Driven Interface
- while True:
- print("\n:: MENU OPTIONS ::\n")
- print("1. Visualize Metal Colors")
- print("2. Calculate Albedo")
- print("3. Compare Index of Refraction")
- print("4. Visualize Albedo of Common Materials")
- print("0. Exit")
- choice = input("\nEnter your choice (0-4): ")
- if choice == '1':
- print("\nMetal Data:")
- for metal, data in metal_data.items():
- print(f"{metal}: RGB={data['Color_RGB']} IOR: {data['IOR']:.4f}")
- visualize_metal_colors()
- elif choice == '2':
- calculate_albedo()
- elif choice == '3':
- display_metal_data()
- metal1 = input("\nEnter the number of the first metal: ")
- metal2 = input("\nEnter the number of the second metal: ")
- compare_ior(metal1, metal2)
- elif choice == '4':
- visualize_common_materials_albedo()
- elif choice == '0':
- print("\nExiting program... Goodbye!\n")
- break
- else:
- print("\nInvalid choice! Please enter a valid option.\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement