Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import plotly.graph_objs as go
- from scipy.optimize import minimize
- def f(x):
- x1, x2 = x
- return x1**2 - 5*x1 + 2*x2**2 - x2 - x1*x2
- def constraint1(x):
- return x[0]
- def constraint2(x):
- return x[1]
- def constraint3(x):
- return 5 - x[0] - x[1]
- constraint_1 = {'type': 'ineq', 'fun': constraint1}
- constraint_2 = {'type': 'ineq', 'fun': constraint2}
- constraint_3 = {'type': 'ineq', 'fun': constraint3}
- constraints = [constraint_1, constraint_2, constraint_3]
- result = minimize(f, [0, 0], constraints=constraints)
- minimum = result.x # Współrzędne punktu minimalnego
- x = np.linspace(-2, 6, 400)
- y = np.linspace(-2, 6, 400)
- X, Y = np.meshgrid(x, y)
- Z = f([X, Y])
- fig = go.Figure(data=go.Contour(x=x, y=y, z=Z, colorscale='spectral', opacity=0.8))
- fig.update_layout(xaxis_title='x1', yaxis_title='x2', title='Funkcja f(x1,x2) z ograniczeniami')
- x_constraint = np.linspace(0, 5, 100)
- y_constraint = 5 - x_constraint
- fig.add_trace(go.Scatter(x=x_constraint, y=y_constraint, mode='lines', fill='tozeroy', fillcolor='rgba(4, 7241, 12, 0.5)', line=dict(color='black', width=3, dash='dash'), name='x1 + x2 >= 5'))
- fig.add_annotation(x=3, y=2, text="x1 + x2 >= 5", showarrow=False, font=dict(color='white', size=15))
- x_line = np.linspace(-2, 6, 10)
- y_line = np.zeros_like(x_line)
- fig.add_trace(go.Scatter(x=x_line, y=y_line, mode='lines', line=dict(color='black', width=3, dash='dash'), name='x1 >= 0'))
- fig.add_annotation(x=6, y=0.5, text="x1 >= 0", showarrow=False, font=dict(color='white', size=15))
- y_line = np.linspace(-2, 6, 10)
- x_line = np.zeros_like(y_line)
- fig.add_trace(go.Scatter(x=x_line, y=y_line, mode='lines', line=dict(color='black', width=3, dash='dash'), name='x2 >= 0'))
- fig.add_annotation(x=0.5, y=6, text="x2 >= 0", showarrow=False, font=dict(color='white', size=15))
- fig.add_trace(go.Scatter(x=[minimum[0]], y=[minimum[1]], mode='markers', marker=dict(color='blue', size=10), name='Minimum'))
- fig.add_trace(go.Scatter(x=[29/8], y=[11/8], mode='markers', marker=dict(color='yellow', size=10), name='Minimum globalne'))
- fig.update_layout(legend=dict(x=1.2, y=1), # Ustawienie legendy z prawej strony
- xaxis_title='x1', yaxis_title='x2', title='Funkcja f(x1,x2) z ograniczeniami')
- fig.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement