Doc473/optics
0
1import streamlit as st2import numpy as np3import pandas as pd4import plotly.graph_objects as go5from pycaret.regression import load_model6from fpdf import FPDF7import plotly.express as px8 9# Load the trained model10model = load_model('best_light_refraction_model')11 12# Snell's Law: n1 * sin(theta1) = n2 * sin(theta2)13def snells_law(n1, theta1, n2):14 theta1_rad = np.radians(theta1)15 theta2_rad = np.arcsin((n1 / n2) * np.sin(theta1_rad))16 return np.degrees(theta2_rad)17 18# Streamlit UI - Title19st.title('Interactive 3D Light Refraction Simulator')20 21# Sidebar input for material properties (for all tabs)22st.sidebar.header('Material Properties')23density = st.sidebar.slider('Density (g/cm³)', 0.5, 20.0, 5.0)24molar_mass = st.sidebar.slider('Molar Mass (g/mol)', 10, 300, 50)25atomic_number = st.sidebar.slider('Atomic Number', 1, 100, 20)26polarizability = st.sidebar.slider('Polarizability (ų)', 0.1, 3.0, 1.5)27wavelength = st.sidebar.slider('Wavelength (nm)', 380, 780, 550)28temperature = st.sidebar.slider('Temperature (°C)', -100, 500, 25)29material_type = st.sidebar.selectbox('Select Material Type', ['Gas', 'Liquid', 'Solid'])30material_type_encoded = {'Gas': 0, 'Liquid': 1, 'Solid': 2}[material_type]31 32# Prepare the input data for prediction33columns = ['density', 'molar_mass', 'atomic_number', 'polarizability', 'wavelength', 'temperature', 'material_type']34input_data = pd.DataFrame([[density, molar_mass, atomic_number, polarizability, wavelength, temperature, material_type_encoded]], columns=columns)35 36# Predict refractive index using the trained model37predicted_refractive_index = model.predict(input_data)[0]38 39# Simulating the bending of light and showing how it behaves at different angles40def light_bending_simulation():41 angle_of_incidence = st.slider('Incident Angle (degrees)', 0, 90, 45)42 refracted_angle = snells_law(1.0, angle_of_incidence, predicted_refractive_index)43 44 # Display bending simulation45 st.write(f"**Incident Angle**: {angle_of_incidence}°")46 st.write(f"**Refracted Angle**: {round(refracted_angle, 2)}°")47 48 # Visualize light path49 fig = go.Figure()50 51 # Light path before and after refraction52 x = [0, 1]53 y = [0, np.tan(np.radians(angle_of_incidence))]54 z = [0, 0]55 56 fig.add_trace(go.Scatter3d(x=x, y=y, z=z, mode='lines', name='Incident Ray', line=dict(color='blue')))57 refracted_x = [0, 1]58 refracted_y = [0, np.tan(np.radians(refracted_angle))]59 refracted_z = [0, 1]60 61 fig.add_trace(go.Scatter3d(x=refracted_x, y=refracted_y, z=refracted_z, mode='lines', name='Refracted Ray', line=dict(color='orange', dash='dash')))62 63 fig.update_layout(title='3D Light Refraction Simulation', scene=dict(64 xaxis_title='X', yaxis_title='Y', zaxis_title='Z'))65 66 st.plotly_chart(fig)67 68# Create an educational tutorial with more theory69def show_tutorial():70 tutorial_text = """71 **Refraction** is the bending of light when it passes from one medium into another with a different refractive index. 72 This phenomenon occurs because the speed of light changes when it enters a medium with a different optical density. 73 The degree to which light bends is determined by **Snell's Law**.74 75 ### **Snell's Law**:76 Snell's Law describes how light refracts at the interface between two materials. It is expressed as:77 78 $$ n_1 \\cdot \\sin(\\theta_1) = n_2 \\cdot \\sin(\\theta_2) $$79 80 Where:81 - \(n_1\) and \(n_2\) are the refractive indices of the first and second medium respectively.82 - \(\\theta_1\) is the angle of incidence (the angle the light makes with the normal to the surface).83 - \(\\theta_2\) is the angle of refraction (the angle the light makes with the normal in the second medium).84 85 ### **Refractive Index**:86 The refractive index is a measure of how much a material slows down light. The refractive index \(n\) of a medium is given by:87 88 $$ n = \\frac{c}{v} $$89 90 Where:91 - \(c\) is the speed of light in vacuum (approximately \(3 \\times 10^8\) m/s).92 - \(v\) is the speed of light in the material.93 94 ### **Factors Affecting Refraction**:95 Several factors influence the extent to which light refracts:96 - **Material Properties**: Different materials have different refractive indices, which cause varying amounts of bending.97 - **Wavelength**: Shorter wavelengths (like blue light) refract more than longer wavelengths (like red light).98 - **Temperature**: The refractive index of some materials changes with temperature, which can affect the behavior of light.99 100 ### **Applications of Refraction**:101 Refraction plays a critical role in many technologies:102 - **Eyeglasses and Lenses**: Corrective lenses use refraction to focus light properly onto the retina.103 - **Microscopes and Telescopes**: Refraction is key to magnifying distant or microscopic objects.104 - **Fiber Optic Communication**: Fiber optics rely on total internal reflection, a form of refraction, to transmit data over long distances.105 106 ### **Examples of Materials and Their Refractive Indices**:107 - **Glass**: ~1.5108 - **Water**: ~1.33109 - **Air**: ~1.0003110 - **Diamond**: ~2.42111 - **Quartz**: ~1.46112 - **Sapphire**: ~1.76113 - **Silicon**: ~3.42114 - **Plastic**: ~1.59115 - **Glycerin**: ~1.47116 - **Rubber**: ~1.52117 - **Lead Glass**: ~1.65118 - **Ice**: ~1.31119 - **Benzene**: ~1.50120 - **Toluene**: ~1.496121 - **Chlorine Gas**: ~1.0004122 """123 return tutorial_text124 125# Expanded Material Database (100+ Materials)126def material_database():127 st.subheader("Explore Material Properties Database")128 129 # Correcting the lengths of each list to ensure they are of equal length130 materials_data = {131 'Material': [132 'Air', 'Water', 'Ice', 'Ethanol', 'Methanol', 'Glycerol', 'Benzene', 'Toluene', 'Acetone', 'Chloroform',133 'Silicon Dioxide', 'Fused Silica', 'Pyrex', 'Crown Glass', 'Flint Glass', 'PMMA', 'Polycarbonate', 'Polystyrene',134 'Teflon', 'HDPE', 'Silicon', 'GaAs', 'Germanium', 'Al₂O₃', 'TiO₂', 'ZrO₂', 'Diamond', 'Cubic Zirconia',135 'SiC', 'Graphite', 'NaCl', 'CaF₂', 'MgF₂', 'ZnO', 'CuO', 'BaTiO₃', 'LiNbO₃', 'CaCO₃', 'MgO',136 'Sapphire', 'Si₃N₄', 'GaN', 'InP', 'CdS', 'Liquid Mercury', 'Garnet', 'Beryl', 'Acrylic', 'PVC'137 ],138 'Refractive Index': [139 1.000293, 1.3330, 1.309, 1.361, 1.3288, 1.473, 1.501, 1.496, 1.359, 1.445,140 1.458, 1.458, 1.472, 1.520, 1.620, 1.489, 1.586, 1.590, 1.350, 1.510,141 3.415, 3.3, 4.0, 1.767, 2.488, 2.15, 2.417, 2.17, 2.65, 1.73,142 1.544, 1.434, 1.375, 2.00, 2.63, 1.95, 2.29, 1.62, 1.73, 1.768,143 1.97, 2.30, 3.17, 2.50, 1.74, 1.833, 1.606, 1.530, 1.489144 ],145 'Density (g/cm³)': [146 0.00129, 1.000, 0.917, 0.789, 0.792, 1.261, 0.879, 0.867, 0.784, 1.489,147 2.20, 2.20, 2.23, 2.50, 4.00, 1.18, 1.20, 1.05, 2.20, 0.95,148 2.33, 5.32, 5.32, 3.98, 4.23, 5.68, 3.51, 6.00, 3.21, 2.25,149 2.16, 3.18, 3.15, 5.61, 6.31, 6.02, 4.64, 2.71, 3.58, 3.98,150 3.17, 6.15, 4.81, 4.82, 13.53, 4.10, 3.53, 1.19, 1.38151 ],152 'Molar Mass (g/mol)': [153 28.97, 18.02, 18.02, 46.07, 32.04, 92.09, 78.11, 92.14, 58.08, 119.38,154 60.08, 60.08, 60.08, None, None, 100.12, None, None, None, None,155 28.09, 144.64, 72.63, 101.96, 79.87, 123.22, 12.01, None, 40.10, 12.01,156 58.44, 78.07, 62.30, 81.38, 79.55, 233.19, 147.84, 100.09, 40.30, 101.96,157 140.28, 83.73, 145.79, 144.48, 200.59, None, None, None, 100.12158 ]159 }160 161 # Create DataFrame162 materials = pd.DataFrame(materials_data)163 st.write(materials)164 165# Create the PDF Report166def create_pdf_report():167 pdf = FPDF()168 pdf.add_page()169 pdf.set_font('Arial', 'B', 16)170 pdf.cell(200, 10, txt="Light Refraction and Material Properties Report", ln=True, align='C')171 172 pdf.ln(10) # Line break173 pdf.set_font('Arial', '', 12)174 175 pdf.cell(200, 10, txt=f"Predicted Refractive Index: {round(predicted_refractive_index, 4)}", ln=True)176 177 pdf.ln(10)178 pdf.multi_cell(0, 10, txt=f"""179 Material Properties:180 - Density: {density} g/cm³181 - Molar Mass: {molar_mass} g/mol182 - Atomic Number: {atomic_number}183 - Polarizability: {polarizability} ų184 - Wavelength: {wavelength} nm185 - Temperature: {temperature} °C186 - Material Type: {material_type}187 188 Theory:189 {show_tutorial()}190 """)191 192 return pdf193 194# Main Section: Organizing all sections195section = st.selectbox('Choose Section', ['Theory', 'Material Database', 'Refraction Simulation', 'Download PDF Report'])196 197if section == 'Theory':198 st.markdown(show_tutorial(), unsafe_allow_html=True)199elif section == 'Material Database':200 material_database()201elif section == 'Refraction Simulation':202 light_bending_simulation()203elif section == 'Download PDF Report':204 pdf = create_pdf_report()205 st.download_button('Download PDF', data=pdf.output(dest='S').encode('latin1'), file_name="light_refraction_report.pdf", mime='application/pdf')