executable-engineering 0.1.39__py3-none-any.whl → 0.1.41__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,8 +6,13 @@ from .openoptimization_module import OptimizerOpen
6
6
  from .gradientoptimization_module import OptimizerGrad
7
7
  from .numerical_error_module import python_internal_binary, decimal_to_binary
8
8
  from .linearsystems_module import visual_solve_2d, visualize_conditioning, visualize_matrix_norms, jacobi_step, gauss_seidel_step, sor_step, visualize_convergence_2d, create_diagonally_dominant_matrix, iter_solve, steepest_descent, conjugate_gradient, IterationTracker, discretise_poisson, spai
9
+ from .functions_module import weierstrass, plot_and_find_roots, complex_plot_with_shadow, plot_polynomial_roots_companion
9
10
 
10
11
  __all__ = [
12
+ "plot_polynomial_roots_companion",
13
+ "plot_and_find_roots",
14
+ "complex_plot_with_shadow",
15
+ "weierstrass",
11
16
  "discretise_poisson",
12
17
  "spai",
13
18
  "visual_solve_2d",
@@ -134,22 +134,30 @@ class RootFinderClosed:
134
134
  )
135
135
  plt.close(fig)
136
136
  return HTML(anim.to_jshtml())
137
-
137
+
138
138
  def show_toggle_closed(self, interval_ms=750):
139
- bisect_anim_html = self._make_animation_closed('Bisection', interval_ms)
140
- falsepos_anim_html = self._make_animation_closed('False Position', interval_ms)
141
-
142
- if bisect_anim_html is None or falsepos_anim_html is None:
143
- print("Cannot create animations. Check initial interval [a, b].")
144
- return
145
-
146
- bisect_content = widgets.HTML(value=bisect_anim_html.data)
147
- falsepos_content = widgets.HTML(value=falsepos_anim_html.data)
148
-
149
- tab_container = widgets.Tab()
150
- tab_container.children = [bisect_content, falsepos_content]
151
-
152
- tab_container.set_title(0, 'Bisection')
153
- tab_container.set_title(1, 'False Position')
154
-
155
- display(tab_container)
139
+ bisect_anim_html = self._make_animation_closed('Bisection', interval_ms)
140
+ falsepos_anim_html = self._make_animation_closed('False Position', interval_ms)
141
+
142
+ if bisect_anim_html is None or falsepos_anim_html is None:
143
+ print("Cannot create animations. Check initial interval [a, b].")
144
+ return
145
+
146
+ # Create Output widgets to capture rich HTML and script execution
147
+ bisect_out = widgets.Output()
148
+ falsepos_out = widgets.Output()
149
+
150
+ with bisect_out:
151
+ display(bisect_anim_html)
152
+
153
+ with falsepos_out:
154
+ display(falsepos_anim_html)
155
+
156
+ # Assign Output widgets as the tab children
157
+ tab_container = widgets.Tab()
158
+ tab_container.children = [bisect_out, falsepos_out]
159
+
160
+ tab_container.set_title(0, 'Bisection')
161
+ tab_container.set_title(1, 'False Position')
162
+
163
+ display(tab_container)
@@ -0,0 +1,151 @@
1
+ import numpy as np
2
+
3
+ def weierstrass(x, a=0.5, b=13, iterations=100):
4
+ """
5
+ Computes the Weierstrass function.
6
+
7
+ Parameters:
8
+ x (array-like): The points at which to evaluate the function.
9
+ a (float): Parameter 0 < a < 1.
10
+ b (float): Parameter such that ab > 1 + 3pi/2.
11
+ iterations (int): Number of terms in the sum.
12
+
13
+ Returns:
14
+ y (ndarray): The function values.
15
+ """
16
+ x = np.asarray(x)
17
+ y = np.zeros_like(x, dtype=float)
18
+ for n in range(iterations):
19
+ y += (a**n) * np.cos((b**n) * np.pi * x)
20
+ return y
21
+
22
+ import plotly.graph_objects as go
23
+ from scipy.optimize import root
24
+
25
+ def plot_and_find_roots(func):
26
+ x = np.linspace(-10, 10, 400)
27
+ y = func(x)
28
+
29
+ # Find roots
30
+ x0s = np.arange(-10, 10, 1)
31
+ roots = []
32
+ for x0 in x0s:
33
+ r = root(func, x0=x0)
34
+ if r.success:
35
+ roots.append((r.x[0], r.fun[0]))
36
+
37
+ # Remove duplicate roots (within tolerance)
38
+ unique_roots = []
39
+ tol = 1e-6
40
+ for rx, ry in roots:
41
+ if not any(abs(rx - ux) < tol for ux, _ in unique_roots):
42
+ unique_roots.append((rx, ry))
43
+
44
+ # Plot with Plotly
45
+ fig = go.Figure()
46
+ fig.add_trace(go.Scatter(x=x, y=y, mode='lines', name='f(x)'))
47
+ fig.add_hline(y=0, line_dash='dash', line_color='black', annotation_text='x-axis')
48
+ if unique_roots:
49
+ rx_vals = [rx for rx, _ in unique_roots]
50
+ fig.add_trace(go.Scatter(x=rx_vals, y=[0]*len(unique_roots), mode='markers', marker=dict(color='red', size=10), name='Roots'))
51
+ fig.update_layout(title='Plot of f(x) and its Roots', xaxis_title='x', yaxis_title='f(x)', xaxis_range=[-10, 10], yaxis_range=[-10, 10])
52
+ fig.show()
53
+
54
+ def complex_plot_with_shadow(func, title='Complex Plot of f(z)', roots=None, plot_range=(-3, 3)):
55
+ real_range = np.linspace(plot_range[0], plot_range[1], 100)
56
+ imag_range = np.linspace(plot_range[0], plot_range[1], 100)
57
+ abs_val = np.empty((len(real_range), len(imag_range)))
58
+
59
+ for i, real in enumerate(real_range):
60
+ for j, imag in enumerate(imag_range):
61
+ z = complex(real, imag)
62
+ result = func(z)
63
+ abs_val[i, j] = abs(result)
64
+
65
+ surface = go.Surface(
66
+ z=abs_val.T,
67
+ x=real_range,
68
+ y=imag_range,
69
+ colorscale='Viridis',
70
+ contours=dict(z=dict(show=True, usecolormap=True, highlightcolor="limegreen", project_z=True))
71
+ )
72
+
73
+ data = [surface]
74
+
75
+ if roots is not None:
76
+ root_x = [r.real for r in roots]
77
+ root_y = [r.imag for r in roots]
78
+ # Calculate z for roots (which is abs(func(r)) = 0)
79
+ root_z = [0 for r in roots]
80
+
81
+ data.append(go.Scatter3d(
82
+ x=root_x, y=root_y, z=root_z,
83
+ mode='markers',
84
+ marker=dict(color='red', size=5, symbol='circle'),
85
+ name='Roots'
86
+ ))
87
+
88
+ fig = go.Figure(data=data)
89
+ fig.update_layout(
90
+ title=title,
91
+ scene=dict(xaxis_title='Real', yaxis_title='Imaginary', zaxis_title='|f(z)|')
92
+ )
93
+ fig.show()
94
+
95
+
96
+ from scipy.linalg import companion
97
+
98
+ def plot_polynomial_roots_companion(n):
99
+ """
100
+ Creates a random polynomial of order n, solves for its roots
101
+ using the companion matrix method, and plots the polynomial
102
+ along with the roots as a complex surface with a shadow.
103
+ """
104
+ # Create random coefficients from -10 to 10
105
+ # A polynomial of order n has n+1 coefficients. Let's make the leading coefficient non-zero.
106
+ coeffs = np.random.uniform(-10, 10, n + 1)
107
+
108
+ # Make sure leading coefficient is not too small
109
+ if abs(coeffs[0]) < 1:
110
+ coeffs[0] = 1.0 * np.sign(coeffs[0]) if coeffs[0] != 0 else 1.0
111
+
112
+ poly_func = np.poly1d(coeffs)
113
+
114
+ print("Polynomial:")
115
+ print(poly_func)
116
+
117
+ # Solve for roots using companion matrix
118
+ comp_matrix = companion(coeffs)
119
+
120
+ print("\nCompanion Matrix:")
121
+ print(np.round(comp_matrix, 2))
122
+
123
+ roots = np.linalg.eigvals(comp_matrix)
124
+
125
+ print("\nRoots from eigenvalues of companion matrix:")
126
+ print(np.round(roots, 2))
127
+
128
+ # Determine plot range based on roots
129
+ max_abs_root = max(abs(roots)) if len(roots) > 0 else 1.0
130
+ plot_limit = max_abs_root * 1.5
131
+
132
+ # --- Real-space plot ---
133
+ x_real = np.linspace(-plot_limit, plot_limit, 400)
134
+ y_real = poly_func(x_real)
135
+
136
+ fig_real = go.Figure()
137
+ fig_real.add_trace(go.Scatter(x=x_real, y=y_real, mode='lines', name='f(x)'))
138
+ fig_real.add_hline(y=0, line_dash='dash', line_color='black', annotation_text='x-axis')
139
+
140
+ # Find real roots (imaginary part near 0)
141
+ real_roots = [r.real for r in roots if abs(r.imag) < 1e-6]
142
+ if real_roots:
143
+ fig_real.add_trace(go.Scatter(x=real_roots, y=[0]*len(real_roots), mode='markers', marker=dict(color='red', size=10), name='Real Roots'))
144
+
145
+ fig_real.update_layout(title=f"Real Space Plot: Roots of Order {n} Polynomial", xaxis_title='x', yaxis_title='f(x)')
146
+ fig_real.show()
147
+
148
+ # Plot using complex_plot_with_shadow
149
+ title = f"Complex Space Plot: Roots of Order {n} Polynomial"
150
+ complex_plot_with_shadow(poly_func, title=title, roots=roots, plot_range=(-plot_limit, plot_limit))
151
+
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: executable_engineering
3
- Version: 0.1.39
3
+ Version: 0.1.41
4
4
  Summary: Demonstrative tools for the Executable Engineering textbook
5
5
  Home-page: https://github.com/themintlab/ExecutableEngineering/tree/main/executable_engineering
6
6
  Author: Michael Welland
@@ -1,14 +1,15 @@
1
- executable_engineering/__init__.py,sha256=TbE18BDMSDAqyHnJI0XQXMIcM6bXQv8ebV3rWijyVP0,1656
1
+ executable_engineering/__init__.py,sha256=-Pcd1x1O6zkA2ro9iz6RLgeq68yNQyV4aPBhNjQSKx4,1887
2
2
  executable_engineering/closedoptimization_module.py,sha256=i9KkdulyCZmriYKlx0CuUetjoMmxJm9ADWgStU3w85w,9273
3
- executable_engineering/closedrootfinder_module.py,sha256=ozccVABOrTiqcdkkqwAWRNo04MsDC0Z_f_tfukl3q20,5706
3
+ executable_engineering/closedrootfinder_module.py,sha256=hQ6iWNi16RkZTaE_WPUEwkohmrYrAyU8WWSXO2EPLJY,6000
4
+ executable_engineering/functions_module.py,sha256=NsPFoVwd3h7zsyW3QFTGZxciKyLQP1vepvmwXP2GQ20,5164
4
5
  executable_engineering/gradientoptimization_module.py,sha256=-2fErE9cemSEPeV9PlWOf4cF7Tr6DjilEw_NxvE-JYw,6601
5
6
  executable_engineering/linearsystems_module.py,sha256=w6UkwZu80gUz5bAIWY47xJbwaEVzR9tCcIBkMsKjIRk,18356
6
7
  executable_engineering/neuralnet_module.py,sha256=Hu9QFoMyODg4RCEpHmT9zTwzjcVFYM8ZLYtbB3CbrsA,10102
7
8
  executable_engineering/numerical_error_module.py,sha256=wxfYP8u29c19I2D6MxpQV3zDMV0DpS1QUqFpp3f6eGE,1204
8
9
  executable_engineering/openoptimization_module.py,sha256=OCPyrynkTo1It50RoT7irnL72aQn6FexE_R1SfFYxlg,8590
9
10
  executable_engineering/openrootfinder_module.py,sha256=R_lPtCQsIGLXV-j_uDpQepImOOgtgA7I6qnhUPwWLLc,5944
10
- executable_engineering-0.1.39.dist-info/licenses/LICENSE,sha256=Tg4nrt8rFhgpkPbIA8SWoCR3MlGLw0NufB8AE6-TH_o,1074
11
- executable_engineering-0.1.39.dist-info/METADATA,sha256=D3CtWo1BiOOo9yR8WeFNw-LBi94rd9flj-M2BxTqKC0,1648
12
- executable_engineering-0.1.39.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
13
- executable_engineering-0.1.39.dist-info/top_level.txt,sha256=0U5ATV5WGTLvN9rRSjQ54TyL-ztTyXaN3FzZ_QMq4HM,23
14
- executable_engineering-0.1.39.dist-info/RECORD,,
11
+ executable_engineering-0.1.41.dist-info/licenses/LICENSE,sha256=Tg4nrt8rFhgpkPbIA8SWoCR3MlGLw0NufB8AE6-TH_o,1074
12
+ executable_engineering-0.1.41.dist-info/METADATA,sha256=ayq_EWUXT-C5IuQrx1ys-RVtBFoOk6oN5WpCdazWAwE,1648
13
+ executable_engineering-0.1.41.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
14
+ executable_engineering-0.1.41.dist-info/top_level.txt,sha256=0U5ATV5WGTLvN9rRSjQ54TyL-ztTyXaN3FzZ_QMq4HM,23
15
+ executable_engineering-0.1.41.dist-info/RECORD,,