Advertisement
cybereq

pyth

Nov 29th, 2023
442
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.26 KB | None | 0 0
  1. import numpy as np
  2. import plotly.graph_objs as go
  3. from scipy.optimize import minimize
  4.  
  5. def f(x):
  6.     x1, x2 = x
  7.     return x1**2 - 5*x1 + 2*x2**2 - x2 - x1*x2
  8.  
  9. def constraint1(x):
  10.     return x[0]
  11.  
  12. def constraint2(x):
  13.     return x[1]
  14.  
  15. def constraint3(x):
  16.     return 5 - x[0] - x[1]
  17.  
  18. constraint_1 = {'type': 'ineq', 'fun': constraint1}
  19. constraint_2 = {'type': 'ineq', 'fun': constraint2}
  20. constraint_3 = {'type': 'ineq', 'fun': constraint3}
  21. constraints = [constraint_1, constraint_2, constraint_3]
  22.  
  23. result = minimize(f, [0, 0], constraints=constraints)
  24. minimum = result.x  # Współrzędne punktu minimalnego
  25.  
  26. x = np.linspace(-2, 6, 400)
  27. y = np.linspace(-2, 6, 400)
  28. X, Y = np.meshgrid(x, y)
  29. Z = f([X, Y])
  30.  
  31. fig = go.Figure(data=go.Contour(x=x, y=y, z=Z, colorscale='spectral', opacity=0.8))
  32. fig.update_layout(xaxis_title='x1', yaxis_title='x2', title='Funkcja f(x1,x2) z ograniczeniami')
  33.  
  34. x_constraint = np.linspace(0, 5, 100)
  35. y_constraint = 5 - x_constraint
  36. 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'))
  37. fig.add_annotation(x=3, y=2, text="x1 + x2 >= 5", showarrow=False, font=dict(color='white', size=15))
  38.  
  39. x_line = np.linspace(-2, 6, 10)
  40. y_line = np.zeros_like(x_line)
  41. fig.add_trace(go.Scatter(x=x_line, y=y_line, mode='lines', line=dict(color='black', width=3, dash='dash'), name='x1 >= 0'))
  42. fig.add_annotation(x=6, y=0.5, text="x1 >= 0", showarrow=False, font=dict(color='white', size=15))
  43.  
  44. y_line = np.linspace(-2, 6, 10)
  45. x_line = np.zeros_like(y_line)
  46. fig.add_trace(go.Scatter(x=x_line, y=y_line, mode='lines', line=dict(color='black', width=3, dash='dash'), name='x2 >= 0'))
  47. fig.add_annotation(x=0.5, y=6, text="x2 >= 0", showarrow=False, font=dict(color='white', size=15))
  48.  
  49. fig.add_trace(go.Scatter(x=[minimum[0]], y=[minimum[1]], mode='markers', marker=dict(color='blue', size=10), name='Minimum'))
  50. fig.add_trace(go.Scatter(x=[29/8], y=[11/8], mode='markers', marker=dict(color='yellow', size=10), name='Minimum globalne'))
  51.  
  52. fig.update_layout(legend=dict(x=1.2, y=1), # Ustawienie legendy z prawej strony
  53.                   xaxis_title='x1', yaxis_title='x2', title='Funkcja f(x1,x2) z ograniczeniami')
  54. fig.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement