mirosh111000

Мірошниченко_КМЗПМ_ЛР№7

Dec 15th, 2025
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.67 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from numba import jit
  4. import concurrent.futures
  5. import time
  6.  
  7. N = 256      
  8. L = 100.0      
  9. dx = L / N      
  10. dt = 0.0001      
  11. plot_times = [0, 10, 50, 100, 200, 500]
  12. K = 1.0        
  13.  
  14. params_case_1 = {'nu_x': 1.0, 'nu_y': -1.0, 'title': r'$\nu_x=1.0, \nu_y=-1.0$'}
  15. params_case_2 = {'nu_x': -1.0, 'nu_y': 1.0, 'title': r'$\nu_x=-1.0, \nu_y=1.0$'}
  16.  
  17. def format_duration(seconds):
  18.     m, s = divmod(int(seconds), 60)
  19.     return f"{m} хв {s} с"
  20.  
  21. @jit(nopython=True, fastmath=True, nogil=True)
  22. def compute_step(h, nu_x, nu_y, K, dx, dt):
  23.     N = h.shape[0]
  24.     dx2 = dx*dx
  25.    
  26.     lap = np.zeros((N, N))
  27.     new_h = np.zeros((N, N))
  28.    
  29.     for i in range(N):
  30.         im = i - 1 if i > 0 else N - 1
  31.         ip = i + 1 if i < N - 1 else 0
  32.         for j in range(N):
  33.             jm = j - 1 if j > 0 else N - 1
  34.             jp = j + 1 if j < N - 1 else 0
  35.             lap[i, j] = (h[i, jp] + h[i, jm] + h[ip, j] + h[im, j] - 4*h[i, j]) / dx2
  36.  
  37.     for i in range(N):
  38.         im = i - 1 if i > 0 else N - 1
  39.         ip = i + 1 if i < N - 1 else 0
  40.         for j in range(N):
  41.             jm = j - 1 if j > 0 else N - 1
  42.             jp = j + 1 if j < N - 1 else 0
  43.            
  44.             d2x = (h[i, jp] - 2*h[i, j] + h[i, jm]) / dx2
  45.             d2y = (h[ip, j] - 2*h[i, j] + h[im, j]) / dx2
  46.             nabla4 = (lap[i, jp] + lap[i, jm] + lap[ip, j] + lap[im, j] - 4*lap[i, j]) / dx2
  47.            
  48.             dh = (nu_x * d2x) + (nu_y * d2y) - (K * nabla4)
  49.             new_h[i, j] = h[i, j] + dh * dt
  50.            
  51.     return new_h
  52.  
  53. def run_simulation_task(params):
  54.     nu_x = params['nu_x']
  55.     nu_y = params['nu_y']
  56.     title = params['title']
  57.    
  58.     np.random.seed(42)
  59.     h = np.random.uniform(-0.1, 0.1, (N, N))
  60.     results = {0: h.copy()}
  61.    
  62.     max_time = max(plot_times)
  63.     total_steps = int(max_time / dt)
  64.     save_steps = {int(t / dt): t for t in plot_times if t > 0}
  65.    
  66.     h = compute_step(h, nu_x, nu_y, K, dx, dt)
  67.    
  68.     for step in range(1, total_steps + 1):
  69.         h = compute_step(h, nu_x, nu_y, K, dx, dt)
  70.        
  71.         if step in save_steps:
  72.             t_val = save_steps[step]
  73.             results[t_val] = h.copy()
  74.    
  75.     return title, results
  76.  
  77. def plot_results(results, title_text):
  78.     fig, axes = plt.subplots(2, 3, figsize=(15, 10))
  79.     axes = axes.flatten()
  80.     sorted_times = sorted(results.keys())
  81.    
  82.     for i, t in enumerate(sorted_times):
  83.         if i >= len(axes): break
  84.         ax = axes[i]
  85.         data = results[t]
  86.         im = ax.imshow(data, cmap='viridis', origin='lower', extent=[0, N*dx, 0, N*dx], aspect='auto')
  87.         ax.set_title(f"t = {t}")
  88.         ax.set_xticks([])
  89.         ax.set_yticks([])
  90.        
  91.     plt.suptitle(f"Динаміка морфології поверхні ({title_text})", fontsize=16)
  92.     plt.tight_layout()
  93.     plt.show()
  94.  
  95. if __name__ == '__main__':
  96.    
  97.     start_total = time.time()
  98.    
  99.     with concurrent.futures.ThreadPoolExecutor() as executor:
  100.         future1 = executor.submit(run_simulation_task, params_case_1)
  101.         future2 = executor.submit(run_simulation_task, params_case_2)
  102.        
  103.         results_list = []
  104.         for future in concurrent.futures.as_completed([future1, future2]):
  105.             try:
  106.                 title, res = future.result()
  107.                 results_list.append((title, res))
  108.             except Exception as e:
  109.                 print(f"Error: {e}")
  110.  
  111.     results_list.sort(key=lambda x: x[0])
  112.  
  113.     total_time = time.time() - start_total
  114.     print(f"Час виконання: {format_duration(total_time)}")
  115.  
  116.     for title, res in results_list:
  117.         plot_results(res, title)
Advertisement
Add Comment
Please, Sign In to add comment