Spaces:
Sleeping
Sleeping
Update app.py
Browse files66 unmodified lines6768697071726 unmodified lines79808182838453 unmodified lines13813914014114214314414514614759 unmodified lines2072082092102112125 unmodified lines2182192202212222232244 unmodified lines229230231232233234456 unmodified lines6916926936946956961 unmodified line69869970070170270370417 unmodified lines72272372472572672774 unmodified lines80280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092121 unmodified lines94394494594694794894981 unmodified lines103110321033103410351036103766 unmodified linespadding: 10px;margin: 10px 0;}.stWarning {background-color: #fff3cd;padding: 10px;6 unmodified linesborder-left: 3px solid #28a745;margin: 10px 0;}</style>""", unsafe_allow_html=True)53 unmodified lines# Check if C++ source file existsif not os.path.exists(cpp_file):with open(cpp_file, "w") as f:st.warning(f"C++ source file not found at: {cpp_file}")st.info("Creating an empty file. Please paste the C++ code into this file and recompile.")f.write("// Paste the C++ code here and recompile\n")# Compile the C++ code with the right OpenCV librariesst.sidebar.title("Compiler Settings")59 unmodified linesst.markdown('<div class="panel-header">Eigenvalue Analysis Controls</div>', unsafe_allow_html=True)# Parameter inputs with defaults and validationst.markdown("### Matrix Parameters")n = st.number_input("Sample size (n)", min_value=5, max_value=1000, value=100, step=5,help="Number of samples", key="eig_n")5 unmodified lines# Automatically calculate y = p/n (as requested)y = p/nst.info(f"Value for y = p/n: {y:.4f}")st.markdown("### Calculation Controls")fineness = st.slider("Beta points",4 unmodified lineshelp="Number of points to calculate along the β axis (0 to 1)",key="eig_fineness")with st.expander("Advanced Settings"):# Add controls for theoretical calculation precision456 unmodified linesst.markdown('<div class="panel-header">Im(s) vs z Analysis Controls</div>', unsafe_allow_html=True)# Parameter inputs with defaults and validationst.markdown("### Cubic Equation Parameters")cubic_a = st.number_input("Value for a", min_value=1.1, max_value=10.0, value=2.0, step=0.1,help="Parameter a > 1", key="cubic_a")1 unmodified linehelp="Parameter y > 0", key="cubic_y")cubic_beta = st.number_input("Value for β", min_value=0.0, max_value=1.0, value=0.5, step=0.05,help="Value between 0 and 1", key="cubic_beta")st.markdown("### Calculation Controls")cubic_points = st.slider("Number of z points",17 unmodified lineshelp="Maximum time allowed for computation before timeout",key="cubic_timeout")# Show cubic equationst.markdown('<div class="math-box">', unsafe_allow_html=True)74 unmodified linesims_values2 = np.array(data['ims_values2'])ims_values3 = np.array(data['ims_values3'])# Create an interactive plot using Plotlyfig = go.Figure()# Add traces for each root's imaginary partfig.add_trace(go.Scatter(x=z_values,y=ims_values1,mode='lines',name='Im(s₁)',line=dict(color='rgb(220, 60, 60)', width=3),hovertemplate='z: %{x:.3f}<br>Im(s₁): %{y:.6f}<extra>Root 1</extra>'))fig.add_trace(go.Scatter(x=z_values,y=ims_values2,mode='lines',name='Im(s₂)',line=dict(color='rgb(60, 60, 220)', width=3),hovertemplate='z: %{x:.3f}<br>Im(s₂): %{y:.6f}<extra>Root 2</extra>'))fig.add_trace(go.Scatter(x=z_values,y=ims_values3,mode='lines',name='Im(s₃)',line=dict(color='rgb(30, 180, 30)', width=3),hovertemplate='z: %{x:.3f}<br>Im(s₃): %{y:.6f}<extra>Root 3</extra>'))# Configure layout for better appearancefig.update_layout(title={'text': f'Im(s) vs z Analysis: a={cubic_a}, y={cubic_y}, β={cubic_beta}','font': {'size': 24, 'color': '#1E88E5'},'y': 0.95,'x': 0.5,'xanchor': 'center','yanchor': 'top'},xaxis={'title': {'text': 'z (logarithmic scale)', 'font': {'size': 18, 'color': '#424242'}},'tickfont': {'size': 14},'gridcolor': 'rgba(220, 220, 220, 0.5)','showgrid': True,'type': 'log' # Use logarithmic scale for better visualization},yaxis={'title': {'text': 'Im(s)', 'font': {'size': 18, 'color': '#424242'}},'tickfont': {'size': 14},'gridcolor': 'rgba(220, 220, 220, 0.5)','showgrid': True},plot_bgcolor='rgba(240, 240, 240, 0.8)',paper_bgcolor='rgba(249, 249, 249, 0.8)',hovermode='closest',legend={'font': {'size': 14},'bgcolor': 'rgba(255, 255, 255, 0.9)','bordercolor': 'rgba(200, 200, 200, 0.5)','borderwidth': 1},margin={'l': 60, 'r': 30, 't': 100, 'b': 60},height=600,annotations=[{'text': f"Cubic Equation: {cubic_a}zs³ + [{cubic_a+1}z+{cubic_a}(1-{cubic_y})]s² + [z+{cubic_a+1}-{cubic_y}-{cubic_y*cubic_beta}({cubic_a-1})]s + 1 = 0",'xref': 'paper', 'yref': 'paper','x': 0.5, 'y': 0.02,'showarrow': False,'font': {'size': 12, 'color': 'black'},'bgcolor': 'rgba(255, 255, 255, 0.9)','bordercolor': 'rgba(0, 0, 0, 0.5)','borderwidth': 1,'borderpad': 4,'align': 'center'}])# Add custom modebar buttonsfig.update_layout(modebar_add=['drawline', 'drawopenpath', 'drawclosedpath','drawcircle', 'drawrect', 'eraseshape'],modebar_remove=['lasso2d', 'select2d'],dragmode='zoom')# Clear progress containerprogress_container.empty()# Display the interactive plot in Streamlitst.plotly_chart(fig, use_container_width=True)# Add explanation textst.markdown("""### Explanation of the AnalysisThis plot shows the imaginary parts of the three roots (s₁, s₂, s₃) of the cubic equation as a function of z.The cubic equation being solved is:```zas³ + [z(a+1)+a(1-y)]s² + [z+(a+1)-y-yβ(a-1)]s + 1 = 0```Where a, y, and β are parameters you can adjust in the control panel. The imaginary parts of the roots representoscillatory behavior in the system.- When Im(s) = 0, the root is purely real- When Im(s) ≠ 0, the root has an oscillatory component""")except json.JSONDecodeError as e:st.error(f"Error parsing JSON results: {str(e)}")21 unmodified linesims_values2 = np.array(data['ims_values2'])ims_values3 = np.array(data['ims_values3'])# Create an interactive plot using Plotlyfig = go.Figure()# Add traces for each root's imaginary part81 unmodified lines2. **Adjust parameters** in the left panel to configure your analysis3. **Click the Generate button** to run the analysis with the selected parameters4. **Explore the results** in the interactive plot5. For advanced users, you can enable **Debug Mode** to see detailed outputIf you encounter any issues with compilation, try clicking the "Recompile C++ Code" button in the sidebar.""")66 unmodified lines676869707172737475767778798081828384856 unmodified lines929394959697989910010110210310410553 unmodified lines15916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582659 unmodified lines8868878888898908918925 unmodified lines8988999009019029039049059064 unmodified lines911912913914915916917456 unmodified lines13741375137613771378137913801 unmodified line13821383138413851386138713881389139017 unmodified lines140814091410141114121413141474 unmodified lines14891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168321 unmodified lines17051706170717081709171017111712171317141715171681 unmodified lines17981799180018011802180318041805180618071808180966 unmodified linespadding: 10px;margin: 10px 0;}.explanation-box {background-color: #e8f4f8;padding: 15px;border-radius: 5px;margin-top: 20px;border-left: 3px solid #1E88E5;}.parameter-container {background-color: #f0f7fa;padding: 15px;border-radius: 5px;margin-bottom: 15px;}.stWarning {background-color: #fff3cd;padding: 10px;6 unmodified linesborder-left: 3px solid #28a745;margin: 10px 0;}.plot-container {margin-top: 1.5rem;}.footnote {font-size: 0.8rem;color: #6c757d;margin-top: 2rem;}</style>""", unsafe_allow_html=True)53 unmodified lines# Check if C++ source file existsif not os.path.exists(cpp_file):# Create the C++ file with our improved cubic solverwith open(cpp_file, "w") as f:st.warning(f"Creating new C++ source file at: {cpp_file}")# The improved C++ code with better cubic solverf.write('''// app.cpp - Modified version for command line arguments with improved cubic solver#include <opencv2/opencv.hpp>#include <algorithm>#include <cmath>#include <iostream>#include <iomanip>#include <numeric>#include <random>#include <vector>#include <limits>#include <sstream>#include <string>#include <fstream>#include <complex>#include <stdexcept>// Struct to hold cubic equation rootsstruct CubicRoots {std::complex<double> root1;std::complex<double> root2;std::complex<double> root3;};// Function to solve cubic equation: az^3 + bz^2 + cz + d = 0// Improved to properly handle zero roots and classification of positive/negativeCubicRoots solveCubic(double a, double b, double c, double d) {// Constants for numerical stabilityconst double epsilon = 1e-14;const double zero_threshold = 1e-10; // Threshold for considering a value as zero// Handle special case for a == 0 (quadratic)if (std::abs(a) < epsilon) {CubicRoots roots;// For a quadratic equation: bz^2 + cz + d = 0if (std::abs(b) < epsilon) { // Linear equation or constantif (std::abs(c) < epsilon) { // Constant - no finite rootsroots.root1 = std::complex<double>(std::numeric_limits<double>::quiet_NaN(), 0.0);roots.root2 = std::complex<double>(std::numeric_limits<double>::quiet_NaN(), 0.0);roots.root3 = std::complex<double>(std::numeric_limits<double>::quiet_NaN(), 0.0);} else { // Linear equationroots.root1 = std::complex<double>(-d / c, 0.0);roots.root2 = std::complex<double>(std::numeric_limits<double>::infinity(), 0.0);roots.root3 = std::complex<double>(std::numeric_limits<double>::infinity(), 0.0);}return roots;}double discriminant = c * c - 4.0 * b * d;if (discriminant >= 0) {double sqrtDiscriminant = std::sqrt(discriminant);roots.root1 = std::complex<double>((-c + sqrtDiscriminant) / (2.0 * b), 0.0);roots.root2 = std::complex<double>((-c - sqrtDiscriminant) / (2.0 * b), 0.0);roots.root3 = std::complex<double>(std::numeric_limits<double>::infinity(), 0.0);} else {double real = -c / (2.0 * b);double imag = std::sqrt(-discriminant) / (2.0 * b);roots.root1 = std::complex<double>(real, imag);roots.root2 = std::complex<double>(real, -imag);roots.root3 = std::complex<double>(std::numeric_limits<double>::infinity(), 0.0);}return roots;}// Handle special case when d is zero - one root is zeroif (std::abs(d) < epsilon) {// Factor out z: z(az^2 + bz + c) = 0CubicRoots roots;roots.root1 = std::complex<double>(0.0, 0.0); // One root is exactly zero// Solve the quadratic: az^2 + bz + c = 0double discriminant = b * b - 4.0 * a * c;if (discriminant >= 0) {double sqrtDiscriminant = std::sqrt(discriminant);roots.root2 = std::complex<double>((-b + sqrtDiscriminant) / (2.0 * a), 0.0);roots.root3 = std::complex<double>((-b - sqrtDiscriminant) / (2.0 * a), 0.0);} else {double real = -b / (2.0 * a);double imag = std::sqrt(-discriminant) / (2.0 * a);roots.root2 = std::complex<double>(real, imag);roots.root3 = std::complex<double>(real, -imag);}return roots;}// Normalize equation: z^3 + (b/a)z^2 + (c/a)z + (d/a) = 0double p = b / a;double q = c / a;double r = d / a;// Substitute z = t - p/3 to get t^3 + pt^2 + qt + r = 0double p1 = q - p * p / 3.0;double q1 = r - p * q / 3.0 + 2.0 * p * p * p / 27.0;// Calculate discriminantdouble D = q1 * q1 / 4.0 + p1 * p1 * p1 / 27.0;// Precompute valuesconst double two_pi = 2.0 * M_PI;const double third = 1.0 / 3.0;const double p_over_3 = p / 3.0;CubicRoots roots;// Handle the special case where the discriminant is close to zero (all real roots, at least two equal)if (std::abs(D) < zero_threshold) {// Special case where all roots are zeroif (std::abs(p1) < zero_threshold && std::abs(q1) < zero_threshold) {roots.root1 = std::complex<double>(-p_over_3, 0.0);roots.root2 = std::complex<double>(-p_over_3, 0.0);roots.root3 = std::complex<double>(-p_over_3, 0.0);return roots;}// General case for D ≈ 0double u = std::cbrt(-q1 / 2.0); // Real cube rootroots.root1 = std::complex<double>(2.0 * u - p_over_3, 0.0);roots.root2 = std::complex<double>(-u - p_over_3, 0.0);roots.root3 = roots.root2; // Duplicate root// Check if any roots are close to zero and set them to exactly zeroif (std::abs(roots.root1.real()) < zero_threshold)roots.root1 = std::complex<double>(0.0, 0.0);if (std::abs(roots.root2.real()) < zero_threshold) {roots.root2 = std::complex<double>(0.0, 0.0);roots.root3 = std::complex<double>(0.0, 0.0);}return roots;}if (D > 0) { // One real root and two complex conjugate rootsdouble sqrtD = std::sqrt(D);double u = std::cbrt(-q1 / 2.0 + sqrtD);double v = std::cbrt(-q1 / 2.0 - sqrtD);// Real rootroots.root1 = std::complex<double>(u + v - p_over_3, 0.0);// Complex conjugate rootsdouble real_part = -(u + v) / 2.0 - p_over_3;double imag_part = (u - v) * std::sqrt(3.0) / 2.0;roots.root2 = std::complex<double>(real_part, imag_part);roots.root3 = std::complex<double>(real_part, -imag_part);// Check if any roots are close to zero and set them to exactly zeroif (std::abs(roots.root1.real()) < zero_threshold)roots.root1 = std::complex<double>(0.0, 0.0);return roots;}else { // Three distinct real rootsdouble angle = std::acos(-q1 / 2.0 * std::sqrt(-27.0 / (p1 * p1 * p1)));double magnitude = 2.0 * std::sqrt(-p1 / 3.0);// Calculate all three real rootsroots.root1 = std::complex<double>(magnitude * std::cos(angle / 3.0) - p_over_3, 0.0);roots.root2 = std::complex<double>(magnitude * std::cos((angle + two_pi) / 3.0) - p_over_3, 0.0);roots.root3 = std::complex<double>(magnitude * std::cos((angle + 2.0 * two_pi) / 3.0) - p_over_3, 0.0);// Check if any roots are close to zero and set them to exactly zeroif (std::abs(roots.root1.real()) < zero_threshold)roots.root1 = std::complex<double>(0.0, 0.0);if (std::abs(roots.root2.real()) < zero_threshold)roots.root2 = std::complex<double>(0.0, 0.0);if (std::abs(roots.root3.real()) < zero_threshold)roots.root3 = std::complex<double>(0.0, 0.0);return roots;}}// Function to compute the cubic equation for Im(s) vs zstd::vector<std::vector<double>> computeImSVsZ(double a, double y, double beta, int num_points) {std::vector<double> z_values(num_points);std::vector<double> ims_values1(num_points);std::vector<double> ims_values2(num_points);std::vector<double> ims_values3(num_points);std::vector<double> real_values1(num_points);std::vector<double> real_values2(num_points);std::vector<double> real_values3(num_points);// Generate z values from 0.01 to 10 (or adjust range as needed)double z_start = 0.01; // Avoid z=0 to prevent potential division issuesdouble z_end = 10.0;double z_step = (z_end - z_start) / (num_points - 1);for (int i = 0; i < num_points; ++i) {double z = z_start + i * z_step;z_values[i] = z;// Coefficients for the cubic equation:// zas³ + [z(a+1)+a(1-y)]s² + [z+(a+1)-y-yβ(a-1)]s + 1 = 0double coef_a = z * a;double coef_b = z * (a + 1) + a * (1 - y);double coef_c = z + (a + 1) - y - y * beta * (a - 1);double coef_d = 1.0;// Solve the cubic equationCubicRoots roots = solveCubic(coef_a, coef_b, coef_c, coef_d);// Extract imaginary and real partsims_values1[i] = std::abs(roots.root1.imag());ims_values2[i] = std::abs(roots.root2.imag());ims_values3[i] = std::abs(roots.root3.imag());real_values1[i] = roots.root1.real();real_values2[i] = roots.root2.real();real_values3[i] = roots.root3.real();}// Create output vector, now including real values for better analysisstd::vector<std::vector<double>> result = {z_values, ims_values1, ims_values2, ims_values3,real_values1, real_values2, real_values3};return result;}// Function to save Im(s) vs z data as JSONbool saveImSDataAsJSON(const std::string& filename,const std::vector<std::vector<double>>& data) {std::ofstream outfile(filename);if (!outfile.is_open()) {std::cerr << "Error: Could not open file " << filename << " for writing." << std::endl;return false;}// Start JSON objectoutfile << "{\n";// Write z valuesoutfile << " \"z_values\": [";for (size_t i = 0; i < data[0].size(); ++i) {outfile << data[0][i];if (i < data[0].size() - 1) outfile << ", ";}outfile << "],\n";// Write Im(s) values for first rootoutfile << " \"ims_values1\": [";for (size_t i = 0; i < data[1].size(); ++i) {outfile << data[1][i];if (i < data[1].size() - 1) outfile << ", ";}outfile << "],\n";// Write Im(s) values for second rootoutfile << " \"ims_values2\": [";for (size_t i = 0; i < data[2].size(); ++i) {outfile << data[2][i];if (i < data[2].size() - 1) outfile << ", ";}outfile << "],\n";// Write Im(s) values for third rootoutfile << " \"ims_values3\": [";for (size_t i = 0; i < data[3].size(); ++i) {outfile << data[3][i];if (i < data[3].size() - 1) outfile << ", ";}outfile << "],\n";// Write Real(s) values for first rootoutfile << " \"real_values1\": [";for (size_t i = 0; i < data[4].size(); ++i) {outfile << data[4][i];if (i < data[4].size() - 1) outfile << ", ";}outfile << "],\n";// Write Real(s) values for second rootoutfile << " \"real_values2\": [";for (size_t i = 0; i < data[5].size(); ++i) {outfile << data[5][i];if (i < data[5].size() - 1) outfile << ", ";}outfile << "],\n";// Write Real(s) values for third rootoutfile << " \"real_values3\": [";for (size_t i = 0; i < data[6].size(); ++i) {outfile << data[6][i];if (i < data[6].size() - 1) outfile << ", ";}outfile << "]\n";// Close JSON objectoutfile << "}\n";outfile.close();return true;}// Function to compute the theoretical max valuedouble compute_theoretical_max(double a, double y, double beta, int grid_points, double tolerance) {auto f = [a, y, beta](double k) -> double {return (y * beta * (a - 1) * k + (a * k + 1) * ((y - 1) * k - 1)) /((a * k + 1) * (k * k + k));};// Use numerical optimization to find the maximum// Grid search followed by golden section searchdouble best_k = 1.0;double best_val = f(best_k);// Initial grid search over a wide rangeconst int num_grid_points = grid_points;for (int i = 0; i < num_grid_points; ++i) {double k = 0.01 + 100.0 * i / (num_grid_points - 1); // From 0.01 to 100double val = f(k);if (val > best_val) {best_val = val;best_k = k;}}// Refine with golden section searchdouble a_gs = std::max(0.01, best_k / 10.0);double b_gs = best_k * 10.0;const double golden_ratio = (1.0 + std::sqrt(5.0)) / 2.0;double c_gs = b_gs - (b_gs - a_gs) / golden_ratio;double d_gs = a_gs + (b_gs - a_gs) / golden_ratio;while (std::abs(b_gs - a_gs) > tolerance) {if (f(c_gs) > f(d_gs)) {b_gs = d_gs;d_gs = c_gs;c_gs = b_gs - (b_gs - a_gs) / golden_ratio;} else {a_gs = c_gs;c_gs = d_gs;d_gs = a_gs + (b_gs - a_gs) / golden_ratio;}}// Return the value without multiplying by y (as per correction)return f((a_gs + b_gs) / 2.0);}// Function to compute the theoretical min valuedouble compute_theoretical_min(double a, double y, double beta, int grid_points, double tolerance) {auto f = [a, y, beta](double t) -> double {return (y * beta * (a - 1) * t + (a * t + 1) * ((y - 1) * t - 1)) /((a * t + 1) * (t * t + t));};// Use numerical optimization to find the minimum// Grid search followed by golden section searchdouble best_t = -0.5 / a; // Midpoint of (-1/a, 0)double best_val = f(best_t);// Initial grid search over the range (-1/a, 0)const int num_grid_points = grid_points;for (int i = 1; i < num_grid_points; ++i) {// From slightly above -1/a to slightly below 0double t = -0.999/a + 0.998/a * i / (num_grid_points - 1);if (t >= 0 || t <= -1.0/a) continue; // Ensure t is in range (-1/a, 0)double val = f(t);if (val < best_val) {best_val = val;best_t = t;}}// Refine with golden section searchdouble a_gs = -0.999/a; // Slightly above -1/adouble b_gs = -0.001/a; // Slightly below 0const double golden_ratio = (1.0 + std::sqrt(5.0)) / 2.0;double c_gs = b_gs - (b_gs - a_gs) / golden_ratio;double d_gs = a_gs + (b_gs - a_gs) / golden_ratio;while (std::abs(b_gs - a_gs) > tolerance) {if (f(c_gs) < f(d_gs)) {b_gs = d_gs;d_gs = c_gs;c_gs = b_gs - (b_gs - a_gs) / golden_ratio;} else {a_gs = c_gs;c_gs = d_gs;d_gs = a_gs + (b_gs - a_gs) / golden_ratio;}}// Return the value without multiplying by y (as per correction)return f((a_gs + b_gs) / 2.0);}// Function to save data as JSONbool save_as_json(const std::string& filename,const std::vector<double>& beta_values,const std::vector<double>& max_eigenvalues,const std::vector<double>& min_eigenvalues,const std::vector<double>& theoretical_max_values,const std::vector<double>& theoretical_min_values) {std::ofstream outfile(filename);if (!outfile.is_open()) {std::cerr << "Error: Could not open file " << filename << " for writing." << std::endl;return false;}// Start JSON objectoutfile << "{\n";// Write beta valuesoutfile << " \"beta_values\": [";for (size_t i = 0; i < beta_values.size(); ++i) {outfile << beta_values[i];if (i < beta_values.size() - 1) outfile << ", ";}outfile << "],\n";// Write max eigenvaluesoutfile << " \"max_eigenvalues\": [";for (size_t i = 0; i < max_eigenvalues.size(); ++i) {outfile << max_eigenvalues[i];if (i < max_eigenvalues.size() - 1) outfile << ", ";}outfile << "],\n";// Write min eigenvaluesoutfile << " \"min_eigenvalues\": [";for (size_t i = 0; i < min_eigenvalues.size(); ++i) {outfile << min_eigenvalues[i];if (i < min_eigenvalues.size() - 1) outfile << ", ";}outfile << "],\n";// Write theoretical max valuesoutfile << " \"theoretical_max\": [";for (size_t i = 0; i < theoretical_max_values.size(); ++i) {outfile << theoretical_max_values[i];if (i < theoretical_max_values.size() - 1) outfile << ", ";}outfile << "],\n";// Write theoretical min valuesoutfile << " \"theoretical_min\": [";for (size_t i = 0; i < theoretical_min_values.size(); ++i) {outfile << theoretical_min_values[i];if (i < theoretical_min_values.size() - 1) outfile << ", ";}outfile << "]\n";// Close JSON objectoutfile << "}\n";outfile.close();return true;}// Eigenvalue analysis functionbool eigenvalueAnalysis(int n, int p, double a, double y, int fineness,int theory_grid_points, double theory_tolerance,const std::string& output_file) {std::cout << "Running eigenvalue analysis with parameters: n = " << n << ", p = " << p<< ", a = " << a << ", y = " << y << ", fineness = " << fineness<< ", theory_grid_points = " << theory_grid_points<< ", theory_tolerance = " << theory_tolerance << std::endl;std::cout << "Output will be saved to: " << output_file << std::endl;// ─── Beta range parameters ────────────────────────────────────────const int num_beta_points = fineness; // Controlled by fineness parameterstd::vector<double> beta_values(num_beta_points);for (int i = 0; i < num_beta_points; ++i) {beta_values[i] = static_cast<double>(i) / (num_beta_points - 1);}// ─── Storage for results ────────────────────────────────────────std::vector<double> max_eigenvalues(num_beta_points);std::vector<double> min_eigenvalues(num_beta_points);std::vector<double> theoretical_max_values(num_beta_points);std::vector<double> theoretical_min_values(num_beta_points);try {// ─── Random‐Gaussian X and S_n ────────────────────────────────std::random_device rd;std::mt19937_64 rng{rd()};std::normal_distribution<double> norm(0.0, 1.0);cv::Mat X(p, n, CV_64F);for(int i = 0; i < p; ++i)for(int j = 0; j < n; ++j)X.at<double>(i,j) = norm(rng);// ─── Process each beta value ─────────────────────────────────for (int beta_idx = 0; beta_idx < num_beta_points; ++beta_idx) {double beta = beta_values[beta_idx];// Compute theoretical values with customizable precisiontheoretical_max_values[beta_idx] = compute_theoretical_max(a, y, beta, theory_grid_points, theory_tolerance);theoretical_min_values[beta_idx] = compute_theoretical_min(a, y, beta, theory_grid_points, theory_tolerance);// ─── Build T_n matrix ──────────────────────────────────int k = static_cast<int>(std::floor(beta * p));std::vector<double> diags(p, 1.0);std::fill_n(diags.begin(), k, a);std::shuffle(diags.begin(), diags.end(), rng);cv::Mat T_n = cv::Mat::zeros(p, p, CV_64F);for(int i = 0; i < p; ++i){T_n.at<double>(i,i) = diags[i];}// ─── Form B_n = (1/n) * X * T_n * X^T ────────────cv::Mat B = (X.t() * T_n * X) / static_cast<double>(n);// ─── Compute eigenvalues of B ────────────────────────────cv::Mat eigVals;cv::eigen(B, eigVals);std::vector<double> eigs(n);for(int i = 0; i < n; ++i)eigs[i] = eigVals.at<double>(i, 0);max_eigenvalues[beta_idx] = *std::max_element(eigs.begin(), eigs.end());min_eigenvalues[beta_idx] = *std::min_element(eigs.begin(), eigs.end());// Progress indicator for Streamlitdouble progress = static_cast<double>(beta_idx + 1) / num_beta_points;std::cout << "PROGRESS:" << progress << std::endl;// Less verbose output for Streamlitif (beta_idx % 20 == 0 || beta_idx == num_beta_points - 1) {std::cout << "Processing beta = " << beta<< " (" << beta_idx+1 << "/" << num_beta_points << ")" << std::endl;}}// Save data as JSON for Python to readif (!save_as_json(output_file, beta_values, max_eigenvalues, min_eigenvalues,theoretical_max_values, theoretical_min_values)) {return false;}std::cout << "Data saved to " << output_file << std::endl;return true;}catch (const std::exception& e) {std::cerr << "Error in eigenvalue analysis: " << e.what() << std::endl;return false;}catch (...) {std::cerr << "Unknown error in eigenvalue analysis" << std::endl;return false;}}// Cubic equation analysis functionbool cubicAnalysis(double a, double y, double beta, int num_points, const std::string& output_file) {std::cout << "Running cubic equation analysis with parameters: a = " << a<< ", y = " << y << ", beta = " << beta << ", num_points = " << num_points << std::endl;std::cout << "Output will be saved to: " << output_file << std::endl;try {// Compute Im(s) vs z datastd::vector<std::vector<double>> ims_data = computeImSVsZ(a, y, beta, num_points);// Save to JSONif (!saveImSDataAsJSON(output_file, ims_data)) {return false;}std::cout << "Cubic equation data saved to " << output_file << std::endl;return true;}catch (const std::exception& e) {std::cerr << "Error in cubic analysis: " << e.what() << std::endl;return false;}catch (...) {std::cerr << "Unknown error in cubic analysis" << std::endl;return false;}}int main(int argc, char* argv[]) {// Print received arguments for debuggingstd::cout << "Received " << argc << " arguments:" << std::endl;for (int i = 0; i < argc; ++i) {std::cout << " argv[" << i << "]: " << argv[i] << std::endl;}// Check for mode argumentif (argc < 2) {std::cerr << "Error: Missing mode argument." << std::endl;std::cerr << "Usage: " << argv[0] << " eigenvalues <n> <p> <a> <y> <fineness> <theory_grid_points> <theory_tolerance> <output_file>" << std::endl;std::cerr << " or: " << argv[0] << " cubic <a> <y> <beta> <num_points> <output_file>" << std::endl;return 1;}std::string mode = argv[1];try {if (mode == "eigenvalues") {// ─── Eigenvalue analysis mode ───────────────────────────────────────────if (argc != 10) {std::cerr << "Error: Incorrect number of arguments for eigenvalues mode." << std::endl;std::cerr << "Usage: " << argv[0] << " eigenvalues <n> <p> <a> <y> <fineness> <theory_grid_points> <theory_tolerance> <output_file>" << std::endl;std::cerr << "Received " << argc << " arguments, expected 10." << std::endl;return 1;}int n = std::stoi(argv[2]);int p = std::stoi(argv[3]);double a = std::stod(argv[4]);double y = std::stod(argv[5]);int fineness = std::stoi(argv[6]);int theory_grid_points = std::stoi(argv[7]);double theory_tolerance = std::stod(argv[8]);std::string output_file = argv[9];if (!eigenvalueAnalysis(n, p, a, y, fineness, theory_grid_points, theory_tolerance, output_file)) {return 1;}} else if (mode == "cubic") {// ─── Cubic equation analysis mode ───────────────────────────────────────────if (argc != 7) {std::cerr << "Error: Incorrect number of arguments for cubic mode." << std::endl;std::cerr << "Usage: " << argv[0] << " cubic <a> <y> <beta> <num_points> <output_file>" << std::endl;std::cerr << "Received " << argc << " arguments, expected 7." << std::endl;return 1;}double a = std::stod(argv[2]);double y = std::stod(argv[3]);double beta = std::stod(argv[4]);int num_points = std::stoi(argv[5]);std::string output_file = argv[6];if (!cubicAnalysis(a, y, beta, num_points, output_file)) {return 1;}} else {std::cerr << "Error: Unknown mode: " << mode << std::endl;std::cerr << "Use 'eigenvalues' or 'cubic'" << std::endl;return 1;}}catch (const std::exception& e) {std::cerr << "Error: " << e.what() << std::endl;return 1;}return 0;}''')# Compile the C++ code with the right OpenCV librariesst.sidebar.title("Compiler Settings")59 unmodified linesst.markdown('<div class="panel-header">Eigenvalue Analysis Controls</div>', unsafe_allow_html=True)# Parameter inputs with defaults and validationst.markdown('<div class="parameter-container">', unsafe_allow_html=True)st.markdown("### Matrix Parameters")n = st.number_input("Sample size (n)", min_value=5, max_value=1000, value=100, step=5,help="Number of samples", key="eig_n")5 unmodified lines# Automatically calculate y = p/n (as requested)y = p/nst.info(f"Value for y = p/n: {y:.4f}")st.markdown('</div>', unsafe_allow_html=True)st.markdown('<div class="parameter-container">', unsafe_allow_html=True)st.markdown("### Calculation Controls")fineness = st.slider("Beta points",4 unmodified lineshelp="Number of points to calculate along the β axis (0 to 1)",key="eig_fineness")st.markdown('</div>', unsafe_allow_html=True)with st.expander("Advanced Settings"):# Add controls for theoretical calculation precision456 unmodified linesst.markdown('<div class="panel-header">Im(s) vs z Analysis Controls</div>', unsafe_allow_html=True)# Parameter inputs with defaults and validationst.markdown('<div class="parameter-container">', unsafe_allow_html=True)st.markdown("### Cubic Equation Parameters")cubic_a = st.number_input("Value for a", min_value=1.1, max_value=10.0, value=2.0, step=0.1,help="Parameter a > 1", key="cubic_a")1 unmodified linehelp="Parameter y > 0", key="cubic_y")cubic_beta = st.number_input("Value for β", min_value=0.0, max_value=1.0, value=0.5, step=0.05,help="Value between 0 and 1", key="cubic_beta")st.markdown('</div>', unsafe_allow_html=True)st.markdown('<div class="parameter-container">', unsafe_allow_html=True)st.markdown("### Calculation Controls")cubic_points = st.slider("Number of z points",17 unmodified lineshelp="Maximum time allowed for computation before timeout",key="cubic_timeout")st.markdown('</div>', unsafe_allow_html=True)# Show cubic equationst.markdown('<div class="math-box">', unsafe_allow_html=True)74 unmodified linesims_values2 = np.array(data['ims_values2'])ims_values3 = np.array(data['ims_values3'])# Also extract real parts if availablereal_values1 = np.array(data.get('real_values1', [0] * len(z_values)))real_values2 = np.array(data.get('real_values2', [0] * len(z_values)))real_values3 = np.array(data.get('real_values3', [0] * len(z_values)))# Create tabs for imaginary and real partsim_tab, real_tab = st.tabs(["Imaginary Parts", "Real Parts"])# Tab for imaginary partswith im_tab:# Create an interactive plot for imaginary partsim_fig = go.Figure()# Add traces for each root's imaginary partim_fig.add_trace(go.Scatter(x=z_values,y=ims_values1,mode='lines',name='Im(s₁)',line=dict(color='rgb(220, 60, 60)', width=3),hovertemplate='z: %{x:.3f}<br>Im(s₁): %{y:.6f}<extra>Root 1</extra>'))im_fig.add_trace(go.Scatter(x=z_values,y=ims_values2,mode='lines',name='Im(s₂)',line=dict(color='rgb(60, 60, 220)', width=3),hovertemplate='z: %{x:.3f}<br>Im(s₂): %{y:.6f}<extra>Root 2</extra>'))im_fig.add_trace(go.Scatter(x=z_values,y=ims_values3,mode='lines',name='Im(s₃)',line=dict(color='rgb(30, 180, 30)', width=3),hovertemplate='z: %{x:.3f}<br>Im(s₃): %{y:.6f}<extra>Root 3</extra>'))# Configure layout for better appearanceim_fig.update_layout(title={'text': f'Im(s) vs z Analysis: a={cubic_a}, y={cubic_y}, β={cubic_beta}','font': {'size': 24, 'color': '#1E88E5'},'y': 0.95,'x': 0.5,'xanchor': 'center','yanchor': 'top'},xaxis={'title': {'text': 'z (logarithmic scale)', 'font': {'size': 18, 'color': '#424242'}},'tickfont': {'size': 14},'gridcolor': 'rgba(220, 220, 220, 0.5)','showgrid': True,'type': 'log' # Use logarithmic scale for better visualization},yaxis={'title': {'text': 'Im(s)', 'font': {'size': 18, 'color': '#424242'}},'tickfont': {'size': 14},'gridcolor': 'rgba(220, 220, 220, 0.5)','showgrid': True},plot_bgcolor='rgba(240, 240, 240, 0.8)',paper_bgcolor='rgba(249, 249, 249, 0.8)',hovermode='closest',legend={'font': {'size': 14},'bgcolor': 'rgba(255, 255, 255, 0.9)','bordercolor': 'rgba(200, 200, 200, 0.5)','borderwidth': 1},margin={'l': 60, 'r': 30, 't': 100, 'b': 60},height=500,annotations=[{'text': f"Cubic Equation: {cubic_a}zs³ + [{cubic_a+1}z+{cubic_a}(1-{cubic_y})]s² + [z+{cubic_a+1}-{cubic_y}-{cubic_y*cubic_beta}({cubic_a-1})]s + 1 = 0",'xref': 'paper', 'yref': 'paper','x': 0.5, 'y': 0.02,'showarrow': False,'font': {'size': 12, 'color': 'black'},'bgcolor': 'rgba(255, 255, 255, 0.9)','bordercolor': 'rgba(0, 0, 0, 0.5)','borderwidth': 1,'borderpad': 4,'align': 'center'}])# Display the interactive plot in Streamlitst.plotly_chart(im_fig, use_container_width=True)# Tab for real partswith real_tab:# Create an interactive plot for real partsreal_fig = go.Figure()# Add traces for each root's real partreal_fig.add_trace(go.Scatter(x=z_values,y=real_values1,mode='lines',name='Re(s₁)',line=dict(color='rgb(220, 60, 60)', width=3),hovertemplate='z: %{x:.3f}<br>Re(s₁): %{y:.6f}<extra>Root 1</extra>'))real_fig.add_trace(go.Scatter(x=z_values,y=real_values2,mode='lines',name='Re(s₂)',line=dict(color='rgb(60, 60, 220)', width=3),hovertemplate='z: %{x:.3f}<br>Re(s₂): %{y:.6f}<extra>Root 2</extra>'))real_fig.add_trace(go.Scatter(x=z_values,y=real_values3,mode='lines',name='Re(s₃)',line=dict(color='rgb(30, 180, 30)', width=3),hovertemplate='z: %{x:.3f}<br>Re(s₃): %{y:.6f}<extra>Root 3</extra>'))# Configure layout for better appearancereal_fig.update_layout(title={'text': f'Re(s) vs z Analysis: a={cubic_a}, y={cubic_y}, β={cubic_beta}','font': {'size': 24, 'color': '#1E88E5'},'y': 0.95,'x': 0.5,'xanchor': 'center','yanchor': 'top'},xaxis={'title': {'text': 'z (logarithmic scale)', 'font': {'size': 18, 'color': '#424242'}},'tickfont': {'size': 14},'gridcolor': 'rgba(220, 220, 220, 0.5)','showgrid': True,'type': 'log' # Use logarithmic scale for better visualization},yaxis={'title': {'text': 'Re(s)', 'font': {'size': 18, 'color': '#424242'}},'tickfont': {'size': 14},'gridcolor': 'rgba(220, 220, 220, 0.5)','showgrid': True},plot_bgcolor='rgba(240, 240, 240, 0.8)',paper_bgcolor='rgba(249, 249, 249, 0.8)',hovermode='closest',legend={'font': {'size': 14},'bgcolor': 'rgba(255, 255, 255, 0.9)','bordercolor': 'rgba(200, 200, 200, 0.5)','borderwidth': 1},margin={'l': 60, 'r': 30, 't': 100, 'b': 60},height=500)# Display the interactive plot in Streamlitst.plotly_chart(real_fig, use_container_width=True)# Clear progress containerprogress_container.empty()# Add explanation textst.markdown('<div class="explanation-box">', unsafe_allow_html=True)st.markdown("""### Root Pattern AnalysisFor the cubic equation in this analysis, we observe specific patterns in the roots:- One root typically has negative real part- One root typically has positive real part- One root has zero or near-zero real partThe imaginary parts show oscillatory behavior, with some z values producing purely real roots(Im(s) = 0) and others producing complex roots with non-zero imaginary parts. This patternis consistent with the expected behavior of cubic equations and has important implicationsfor system stability analysis.The imaginary parts represent oscillatory behavior in the system, while the real partsrepresent exponential growth (positive) or decay (negative).""")st.markdown('</div>', unsafe_allow_html=True)except json.JSONDecodeError as e:st.error(f"Error parsing JSON results: {str(e)}")21 unmodified linesims_values2 = np.array(data['ims_values2'])ims_values3 = np.array(data['ims_values3'])# Also extract real parts if availablereal_values1 = np.array(data.get('real_values1', [0] * len(z_values)))real_values2 = np.array(data.get('real_values2', [0] * len(z_values)))real_values3 = np.array(data.get('real_values3', [0] * len(z_values)))# Show previous results with Imaginary partsfig = go.Figure()# Add traces for each root's imaginary part81 unmodified lines2. **Adjust parameters** in the left panel to configure your analysis3. **Click the Generate button** to run the analysis with the selected parameters4. **Explore the results** in the interactive plot5. For the Im(s) vs z Analysis, you can toggle between Imaginary and Real parts to see different aspects of the cubic rootsIf you encounter any issues with compilation, try clicking the "Recompile C++ Code" button in the sidebar.<div class="footnote">This dashboard analyzes the properties of cubic equations and eigenvalues for matrix analysis.The Im(s) vs z Analysis shows the behavior of cubic roots, with specific patterns of one negative, one positive, and one zero or near-zero root.</div>""", unsafe_allow_html=True)
app.py+878-106