Advertisement
rasmit

Untitled

Sep 21st, 2023 (edited)
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.79 KB | None | 0 0
  1. # modified viz.py (run after each grid size simulation)
  2. import os
  3. import glob
  4. import argparse
  5. import pandas  as pd
  6.  
  7. parser = argparse.ArgumentParser(description="Visualize the results of a case")
  8. parser.add_argument('case_dir', type=str, help="Path to the case directory")
  9. parser.add_argument('fps',      type=int, help="Frames per second for the video")
  10.  
  11. ARGS     = vars(parser.parse_args())
  12. DIRPATH  = os.path.abspath(ARGS['case_dir'])
  13. CASENAME = os.path.basename(DIRPATH)
  14.  
  15. TARGET_ASPECT_RATIO = 16 / 9
  16.  
  17. PLOT_PADDING = 0.04
  18. PLOT_DIMS    = (15, 10)
  19.  
  20. VARS = {
  21.     'Density':  ['prim.1', ['Density'] , '#ed4337'],
  22.     'Velocity': ['prim.2', ['Velocity'], '#3561f2'],
  23.     'Pressure': ['prim.3', ['Pressure'], '#28ed87'],
  24. }
  25.  
  26. DATA = {}
  27.  
  28. print(f"Importing data from {os.path.relpath(DIRPATH, os.getcwd())}...")
  29.  
  30. Nx = 399 # ran after each grid size computation with sed
  31.  
  32. # parse data
  33. for name, cfg in VARS.items():
  34.     print(f"* {name} ({cfg[0]}):")
  35.     print(f"  * Reading data files...")
  36.  
  37.     dfs = {}
  38.     for f in glob.glob(os.path.join(DIRPATH, f'D_{Nx}', f'{cfg[0]}.*.*.dat')):
  39.         proc, t_step = int(f.split('.')[-3]), int(f.split('.')[-2])
  40.  
  41.         if t_step != dfs:
  42.             dfs[t_step] = []
  43.                
  44.         dfs[t_step].append(pd.read_csv(f, sep='\s+', header=None, names=['x'] + cfg[1]))
  45.    
  46.     print(f"  * Concatenating processors...")
  47.     for t_step in dfs.keys():
  48.         dfs[t_step] = pd.concat(dfs[t_step])
  49.    
  50.     print(f"  * Merging across timesteps...")
  51.     for t_step, df in dfs.items():    
  52.         if t_step not in DATA:
  53.             DATA[t_step] = df
  54.         else:
  55.             DATA[t_step] = pd.merge(DATA[t_step], df)
  56.  
  57. # remove empty timesteps and get the data at the two desired timesteps
  58. t_steps = list(DATA.keys())
  59. t_steps.sort()
  60.  
  61. for t_step in t_steps:
  62.     DATUM = DATA[t_step]
  63.     if DATUM.empty:
  64.         del DATA[t_step]
  65.  
  66. n = 1
  67. t_step_0 = t_steps[0]
  68. t_step_1 = t_steps[n]
  69.  
  70. # sort data by x and y positions before subtracting
  71. DATA_0 = DATA[t_step_0].drop("Velocity", axis=1).drop("Pressure", axis=1)#.reset_index().sort_index()
  72. DATA_1 = DATA[t_step_1].drop("Velocity", axis=1).drop("Pressure", axis=1)#.reset_index().sort_index()
  73.  
  74. DATA_0.sort_values(["x"])
  75. DATA_1.sort_values(["x"])
  76.  
  77. # calculating error vectors and take sum (L1) and max (Linf) and save to a file - these are modified properly later
  78. diff = DATA[t_step_1][["Density"]].subtract(DATA[t_step_0][["Density"]]).abs()
  79. print(f"Norms from t_step {0} to t_step {n}: {diff.sum().to_string(index=False)}, {diff.max().to_string(index=False)}")
  80. with open("./data.txt", "a+") as data_file:
  81.     data_file.write(f"{Nx},{diff.sum().to_string(index=False)},{diff.max().to_string(index=False)}\n")
  82.    
  83. # norms.py (runs after all grid sizes have been simulated and basic norms calculated
  84. import numpy as np
  85. from scipy.stats import linregress
  86. import matplotlib.pyplot as plt
  87.  
  88. # read data and correct L1 norm by multiplying by h = L/grid_size = 10/grid_size for each grid size
  89. with open("./data.txt", "r") as data_file:
  90.     data = [line.strip("\n\r").split(",") for line in data_file.readlines()]
  91.  
  92.     Nx = np.array([float(line[0])+1 for line in data])
  93.     h = np.array([10/(grid_size) for grid_size in Nx])
  94.     L1 = np.array([float(line[1]) for line in data]) * h
  95.     Linf = np.array([float(line[2]) for line in data])
  96.  
  97. # we plot 1/N instead of just N
  98. recipN = np.array([float(x) for x in Nx]) ** -1
  99.  
  100. # get slope data
  101. print(linregress(np.log10(recipN), np.log10(L1)))
  102. print(linregress(np.log10(recipN), np.log10(Linf)))
  103.  
  104. # plot w/ log scale
  105. fig = plt.figure()
  106. ax = fig.add_subplot(2, 1, 1)
  107. ax.set_xscale("log")
  108. ax.set_yscale("log")
  109. plt.scatter(recipN, L1, label="L1")
  110. plt.scatter(recipN, Linf, label="Linf")
  111.  
  112. plt.xlabel("N^-1")
  113. plt.ylabel("norm(alpha_rho1)")
  114. plt.legend()
  115. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement