In [1]:
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 20191125
@author: zhangji
test the linear relationship
U_t =?= U_sh + U_wm
U_t is the total velocity
U_sh is the velocity induced by shear flow
U_wm is the active velocity.
"""
# %pylab inline
# pylab.rcParams['figure.figsize'] = (25, 11)
# fontsize = 40
# import numpy as np
# import scipy as sp
# from scipy.optimize import leastsq, curve_fit
# from scipy import interpolate
# from scipy.interpolate import interp1d
# from scipy.io import loadmat, savemat
# # import scipy.misc
# import matplotlib
# from matplotlib import pyplot as plt
# from matplotlib import animation, rc
# import matplotlib.ticker as mtick
# from mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes
# from mpl_toolkits.mplot3d import Axes3D, axes3d
# from sympy import symbols, simplify, series, exp
# from sympy.matrices import Matrix
# from sympy.solvers import solve
# from IPython.display import display, HTML
# from tqdm import tqdm_notebook as tqdm
# import pandas as pd
# import re
# from scanf import scanf
# import os
# import glob
# from codeStore import support_fun as spf
# from src.support_class import *
# from src import stokes_flow as sf
# rc('animation', html='html5')
# PWD = os.getcwd()
# font = {'size': 20}
# matplotlib.rc('font', **font)
# np.set_printoptions(linewidth=90, precision=5)
%load_ext autoreload
%autoreload 2
import os
import glob
import re
import pandas as pd
from scanf import scanf
import natsort
import numpy as np
import scipy as sp
from scipy.optimize import leastsq, curve_fit
from scipy import interpolate
from scipy import spatial
# from scipy.interpolate import interp1d
from scipy.io import loadmat, savemat
# import scipy.misc
import importlib
from IPython.display import display, HTML
import pickle
import matplotlib
from matplotlib import pyplot as plt
from matplotlib import colors as mcolors
from matplotlib import animation, rc
import matplotlib.ticker as mtick
from mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes
from mpl_toolkits.mplot3d import Axes3D, axes3d
from matplotlib import ticker, cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from time import time
from src import support_class as spc
from src import jeffery_model as jm
from codeStore import support_fun as spf
from codeStore import support_fun_table as spf_tb
# %matplotlib notebook
%matplotlib inline
rc('animation', html='html5')
rc('text', usetex=True)
params = {'text.latex.preamble': [r'\usepackage{bm}', r'\usepackage{amsmath}']}
plt.rcParams.update(params)
fontsize = 40
figsize = (30, 16)
PWD = os.getcwd()
In [2]:
fig = plt.figure(figsize=(2, 2))
fig.patch.set_facecolor('white')
ax0 = fig.add_subplot(1, 1, 1)
In [3]:
fft_pickle = 'hlxB01_tau1a'
In [4]:
with open('%s.pickle' % fft_pickle, 'rb') as handle:
pickle_data = pickle.load(handle)
tw = pickle_data[0][1][4][2].values
tw_fft = np.fft.fft2(tw)
tw_fft[0, 0]
Out[4]:
In [16]:
# do 2D IFFT myself and compare with numpy version
use_idx_max = 6
# ((psi, ((theta, phi, ui))))
with open('%s.pickle' % fft_pickle, 'rb') as handle:
pickle_data = pickle.load(handle)
ttheta, tphi = pickle_data[0][1][0][:2]
tpsi = np.array([ti[0] for ti in pickle_data])
tw = pickle_data[0][1][5][2].values
tw_fft = np.fft.fft2(tw)
th_freq = np.fft.fftfreq(ttheta.size, 1 / ttheta.size)
ph_freq = np.fft.fftshift(np.fft.fftfreq(tphi.size, 1 / tphi.size))
idx_max = np.dstack(np.unravel_index(np.argsort(np.abs(tw_fft).ravel()), tw_fft.shape))[0][::-1]
# numpy version IFFT
idx = np.zeros_like(tw_fft, dtype=bool)
for ti in idx_max[:use_idx_max]:
idx[ti[0], ti[1]] = 1
tw_fft2 = tw_fft * idx
tw2 = np.fft.ifft2(tw_fft2)
# do IFFT myself
tw3 = np.zeros_like(tw2)
tM, tN = tw_fft.shape
tm, tn = np.meshgrid(np.arange(tM), np.arange(tN), indexing='ij')
for tk, tl in idx_max[:use_idx_max]:
tAkl = tw_fft[tk, tl]
tw3 = tw3 + tAkl * np.exp(2 * np.pi * 1j * (tm * tk / tM + tn * tl / tN)) / (tM * tN)
print(tk, tl, tAkl)
print((np.abs(tw3.imag) / np.abs(tw3)).max())
print((tw3 - tw).max(), (tw3 - tw2).max())
In [13]:
tM, tN
Out[13]:
In [11]:
# print values of primary frequence
print_idx_max = 20
# ((psi, ((theta, phi, ui))))
with open('%s.pickle' % fft_pickle, 'rb') as handle:
pickle_data = pickle.load(handle)
ttheta, tphi = pickle_data[0][1][0][:2]
tpsi = np.array([ti[0] for ti in pickle_data])
tw = pickle_data[0][1][3][2].values
tw_fft = np.fft.fft2(tw)
th_freq = np.fft.fftfreq(ttheta.size, 1 / ttheta.size)
ph_freq = np.fft.fftshift(np.fft.fftfreq(tphi.size, 1 / tphi.size))
idx_max = np.dstack(np.unravel_index(np.argsort(np.abs(tw_fft).ravel()), tw_fft.shape))[0][::-1]
for i0, (tk, tl) in enumerate(idx_max[:print_idx_max]):
if not np.mod(i0, 2):
print('*', tk, tl, tw_fft[tk, tl])
else:
print(' ', tk, tl, tw_fft[tk, tl])
In [26]:
print(tw.shape, tw_fft.shape, ttheta.shape, tphi.shape)
In [23]:
# 2D fft of Wx, Wy, Wz
importlib.reload(spf_tb)
use_uidx = 3 # 3: wx, 4: wy, 5: wz
tktl_list = [[0, 125], [63, 2], [63, 125]]
# ((psi, ((theta, phi, ui))))
with open('%s.pickle' % fft_pickle, 'rb') as handle:
pickle_data = pickle.load(handle)
ttheta, tphi = pickle_data[0][1][0][:2]
tpsi = np.array([ti[0] for ti in pickle_data])
tw = pickle_data[0][1][use_uidx][2].values
for tktl in tktl_list:
if np.sum(tktl) < 1:
spf_tb.show_fft_major(tw, (tktl, ), ttheta, tphi)
else:
spf_tb.show_fft_fit(tw, tktl, ttheta, tphi)
spf_tb.show_fft_major(tw, tktl_list, ttheta, tphi)
Out[23]:
In [76]:
# 2D fft of Wx, Wy, Wz, investigate Amp and \alpha as function of \psi
importlib.reload(spf_tb)
use_uidx = 3 # 3: wx, 4: wy, 5: wz
tktl = [0, 2]
tktl = [63, 2]
tktl = [1, 2]
# ((psi, ((theta, phi, ui))))
with open('%s.pickle' % fft_pickle, 'rb') as handle:
pickle_data = pickle.load(handle)
ttheta, tphi = pickle_data[0][1][0][:2]
tpsi = np.array([ti[0] for ti in pickle_data])
Akl_list = []
Amp_list = []
alpha_list = []
psi_list = []
for tpsi, table_psi_data in pickle_data[:]:
psi_list.append(tpsi)
tw = table_psi_data[use_uidx][2].values
# spf_tb.show_fft_fit(tw, tktl, ttheta, tphi)
Akl1, Amp_use, w_th_use, w_ph_use, alpha_use = spf_tb.factor_wpi_kl1(tw, tktl)
Akl_list.append(Akl1)
Amp_list.append(Amp_use)
alpha_list.append(alpha_use)
fig, axes = plt.subplots(2, 2, figsize=(8, 6), dpi=200)
fig.patch.set_facecolor('white')
ax = axes[0, 0]
ax.plot(psi_list, np.real(Akl_list))
ax.set_xlabel('$\\psi$')
ax.set_ylabel('$\\Re(\\Omega_{p%d})$' % (use_uidx - 2))
ax = axes[0, 1]
ax.plot(psi_list, np.imag(Akl_list))
ax.set_xlabel('$\\psi$')
ax.set_ylabel('$\\Im(\\Omega_{p%d})$' % (use_uidx - 2))
ax = axes[1, 0]
ax.plot(psi_list, Amp_list)
ax.set_xlabel('$\\psi$')
ax.set_ylabel('$\\frac{2 \\left \\lVert \\Omega_{p%d} \\right \\rVert}{n_\\theta n_\\phi}$' % (use_uidx - 2))
ax = axes[1, 1]
ax.plot(psi_list, alpha_list)
ax.set_xlabel('$\\psi$')
ax.set_ylabel('$\\alpha_{0%d}$' % (use_uidx - 2))
plt.tight_layout()
In [ ]:
In [105]:
use_uidx = 3 # 3: wx, 4: wy, 5: wz
In [106]:
# do 3D IFFT myself and compare with numpy version
importlib.reload(spf_tb)
use_idx_max = 6
# ((psi, ((theta, phi, ui), )))
with open('%s.pickle' % fft_pickle, 'rb') as handle:
pickle_data = pickle.load(handle)
ttheta, tphi = pickle_data[0][1][0][:2]
tpsi = np.array([ti[0] for ti in pickle_data])
U_all = [[] for i in range(6)]
for tpsi, table_psi_data in pickle_data:
for (ty, tx, tU), Ui in zip(table_psi_data, U_all):
Ui.append((tpsi, ty, tx, tU))
tw = np.dstack([tU.values for _, _, _, tU in U_all[use_uidx]])
tw_fft = np.fft.fftn(tw)
idx_max = np.dstack(np.unravel_index(np.argsort(np.abs(tw_fft).ravel()), tw_fft.shape))[0][::-1]
# numpy version IFFT
idx = np.zeros_like(tw_fft, dtype=bool)
for ti in idx_max[:use_idx_max]:
idx[ti[0], ti[1], ti[2]] = 1
tw_fft2 = tw_fft * idx
tw2 = np.fft.ifftn(tw_fft2)
print()
# do IFFT myself
tw3 = np.zeros_like(tw2)
tM, tN, tO = tw_fft.shape
tm, tn, to = np.meshgrid(np.arange(tM), np.arange(tN), np.arange(tO), indexing='ij')
for tk, tl, tj in idx_max[:use_idx_max]:
tAkl = tw_fft[tk, tl, tj]
tw3 = tw3 + tAkl * np.exp(2 * np.pi * 1j * tm * tk / tM) / tM * \
np.exp(2 * np.pi * 1j * tn * tl / tN) / tN * \
np.exp(2 * np.pi * 1j * to * tj / tO) / tO
print(tk, tl, tj, tAkl)
print((np.abs(tw3.imag) / np.abs(tw3)).max())
print(np.abs(tw3 - tw2).max())
In [107]:
# print values of primary frequence
importlib.reload(spf_tb)
print_idx_max = 100
# ((psi, ((theta, phi, ui), )))
with open('%s.pickle' % fft_pickle, 'rb') as handle:
pickle_data = pickle.load(handle)
ttheta, tphi = pickle_data[0][1][0][:2]
tpsi = np.array([ti[0] for ti in pickle_data])
U_all = [[] for i in range(6)]
for tpsi, table_psi_data in pickle_data:
for (ty, tx, tU), Ui in zip(table_psi_data, U_all):
Ui.append((tpsi, ty, tx, tU))
tw = np.dstack([tU.values for _, _, _, tU in U_all[use_uidx]])
tw_fft = np.fft.fftn(tw)
idx_max = np.dstack(np.unravel_index(np.argsort(np.abs(tw_fft).ravel()), tw_fft.shape))[0][::-1]
t1 = []
for i0, (tk, tl, tj) in enumerate(idx_max[:print_idx_max]):
t1.append(np.abs(tw_fft[tk, tl, tj]))
if not np.mod(i0, 2):
print('%5d * [%d, %d, %d] ' % (i0, tk, tl, tj), tw_fft[tk, tl, tj], np.abs(tw_fft[tk, tl, tj]))
else:
print(' [%d, %d, %d] ' % (tk, tl, tj), tw_fft[tk, tl, tj], np.abs(tw_fft[tk, tl, tj]))
In [108]:
tktltj_list = ([0, 2, 0], [63, 125, 0], [63, 2, 0], ) # wx
# tktltj_list = ([0, 0, 0], [63, 0, 0], [0, 125, 0], [63, 125, 0], [63, 2, 0]) # wy
# tktltj_list = ([63, 126, 0], [63, 1, 0], [0, 125, 0], [63, 125, 0], [63, 2, 0]) # wz
In [110]:
t1 = [np.abs(tw_fft[tk, tl, tj]) for tk, tl, tj in idx_max]
plt.semilogy(t1, '.')
plt.xlim(-1, 50)
# plt.ylim(10, 100)
Out[110]:
In [103]:
importlib.reload(spf_tb)
# ((psi, ((theta, phi, ui), )))
with open('%s.pickle' % fft_pickle, 'rb') as handle:
pickle_data = pickle.load(handle)
ttheta_all, tphi_all = pickle_data[0][1][0][:2]
tpsi_all = np.array([ti[0] for ti in pickle_data])
U_all = [[] for i in range(6)]
for _, table_psi_data in pickle_data:
for (_, _, tU), Ui in zip(table_psi_data, U_all):
Ui.append(tU)
tw = np.dstack(U_all[use_uidx])
spf_tb.show_3dfft_major(tw, tktltj_list, ttheta_all, tphi_all, tpsi_all)
Out[103]:
In [ ]:
In [2]:
importlib.reload(spf_tb)
fft_pickle = 'hlxB01_tau1a'
with open('%s.pickle' % fft_pickle, 'rb') as handle:
pickle_data = pickle.load(handle)
ttheta_all, tphi_all = pickle_data[0][1][0][:2]
tpsi_all = np.array([ti[0] for ti in pickle_data])
U_all = [[] for i in range(6)]
for _, table_psi_data in pickle_data:
for (ttheta, tphi, tU), Ui in zip(table_psi_data, U_all):
Ui.append(tU)
In [21]:
from shutil import copyfile
pickle_name = 'hlxB01_baseFlow2'
mdf_pickle_name = 'hlxB01_baseFlow2_mdf'
with open('%s.pickle' % pickle_name, 'rb') as handle:
pickle_dict = pickle.load(handle)
t1 = pickle_dict['uw_Base_list'].copy()
for i0 in (0, 1, 2, 3, 4, 5, 6, 7, 8, 9):
t1[i0] = np.zeros_like(t1[i0])
# t1[1][3] = pickle_dict['uw_Base_list'][1][3]
# t1[2][3] = pickle_dict['uw_Base_list'][2][3]
# t1[3][4] = pickle_dict['uw_Base_list'][3][4]
t1[3][5] = pickle_dict['uw_Base_list'][3][5]
t1[4][4] = pickle_dict['uw_Base_list'][4][4]
t1[4][5] = pickle_dict['uw_Base_list'][4][5]
t1[5][3] = pickle_dict['uw_Base_list'][5][3]
t1[9] = pickle_dict['uw_Base_list'][9]
display(np.vstack(t1)[1:6, 3:])
# display(pickle_dict['uw_Base_list'])
pickle_dict['uw_Base_list'] = t1
tname = '%s.pickle' % mdf_pickle_name
with open(tname, 'wb') as handle:
pickle.dump(pickle_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)
copyfile(tname, os.path.join(os.getcwd(), os.pardir, os.pardir, 'src', tname))
print('save table_data to %s' % tname)
In [13]:
# pickle_name = 'hlxB01_baseFlow'
pickle_name = 'hlxB01_baseFlow2'
with open('%s.pickle' % pickle_name, 'rb') as handle:
pickle_dict = pickle.load(handle)
# print(np.vstack(pickle_dict['uw_Base_list']).shape)
uEbase_list = np.vstack(pickle_dict['uw_Base_list'])[1:6, 0:3]
uSbase_list = np.vstack(pickle_dict['uw_Base_list'])[6:9, 0:3]
wEbase_list = np.vstack(pickle_dict['uw_Base_list'])[1:6, 3:6]
wSbase_list = np.vstack(pickle_dict['uw_Base_list'])[6:9, 3:6]
print(wEbase_list)
print(wSbase_list)
print(pickle_dict['uw_Base_list'][9])
In [65]:
importlib.reload(spf_tb)
pickle_name = 'hlxB01_baseFlow'
with open('%s.pickle' % pickle_name, 'rb') as handle:
pickle_dict = pickle.load(handle)
uEbase_list = np.vstack(pickle_dict['uw_Base_list'])[1:6, 0:3]
uSbase_list = np.vstack(pickle_dict['uw_Base_list'])[6:9, 0:3]
wSbase_list = np.vstack(pickle_dict['uw_Base_list'])[6:9, 3:6]
wEbase_list0 = np.vstack(pickle_dict['uw_Base_list'])[1:6, 3:6]
wEbase_list = np.zeros_like(wEbase_list0)
wEbase_list[3, 1] = wEbase_list0[3, 1]
wEbase_list[4, 0] = wEbase_list0[4, 0]
U_cal_all = [[] for i in range(6)]
uS_cal_list = []
for i0 in range(tpsi_all.size):
tpsi = tpsi_all[i0]
tux = U_all[0][i0]
tuy = U_all[1][i0]
tuz = U_all[2][i0]
tux_cal = tux.copy()
tuy_cal = tuy.copy()
tuz_cal = tuz.copy()
for i1 in range(ttheta_all.size):
ttheta = ttheta_all[i1]
for i2 in range(tphi_all.size):
tphi = tphi_all[i2]
Eij_loc = spf_tb.Eij_loc(ttheta, tphi, tpsi)
Sij_loc = spf_tb.Sij_loc(ttheta, tphi, tpsi)
Ebase_fct = np.array([Eij_loc[0, 0], Eij_loc[2, 2], Eij_loc[0, 1], Eij_loc[0, 2], Eij_loc[1, 2]])
Sbase_fct = np.array([Sij_loc[2, 1], Sij_loc[0, 2], Sij_loc[1, 0]])
uE_loc = np.sum([a * b for a, b in zip(Ebase_fct, uEbase_list)], axis=0)
uE = np.dot(spf_tb.Rrot(ttheta, tphi, tpsi), uE_loc)
uS = np.array((0, 0, 0))
tu_cal = uE + uS
tux_cal.iloc[i1].iloc[i2] = tu_cal[0]
tuy_cal.iloc[i1].iloc[i2] = tu_cal[1]
tuz_cal.iloc[i1].iloc[i2] = tu_cal[2]
U_cal_all[0].append(tux_cal)
U_cal_all[1].append(tuy_cal)
U_cal_all[2].append(tuz_cal)
# print(np.linalg.norm(np.vstack(uS_cal_list) - np.array((0, 0, 0)), axis=-1).max())
wS_cal_list = []
wE_err_list = []
for i0 in range(tpsi_all.size):
tpsi = tpsi_all[i0]
twx = U_all[3][i0]
twy = U_all[4][i0]
twz = U_all[5][i0]
twx_cal = twx.copy()
twy_cal = twy.copy()
twz_cal = twz.copy()
for i1 in range(ttheta_all.size):
ttheta = ttheta_all[i1]
for i2 in range(tphi_all.size):
tphi = tphi_all[i2]
Eij_loc = spf_tb.Eij_loc(ttheta, tphi, tpsi)
Sij_loc = spf_tb.Sij_loc(ttheta, tphi, tpsi)
Ebase_fct = np.array([Eij_loc[0, 0], Eij_loc[2, 2], Eij_loc[0, 1], Eij_loc[0, 2], Eij_loc[1, 2]])
Sbase_fct = np.array([Sij_loc[2, 1], Sij_loc[0, 2], Sij_loc[1, 0]])
wE_loc = np.sum([a * b for a, b in zip(Ebase_fct, wEbase_list)], axis=0)
wE = np.dot(spf_tb.Rrot(ttheta, tphi, tpsi), wE_loc)
# wS_loc = np.sum([a * b for a, b in zip(Sbase_fct, wSbase_list)], axis=0)
# wS = np.dot(spf_tb.Rrot(ttheta, tphi, tpsi), wS_loc)
# wS_cal_list.append(wS)
wS = np.array((0, 0.5, 0))
tw_cal = wE + wS
twx_cal.iloc[i1].iloc[i2] = tw_cal[0]
twy_cal.iloc[i1].iloc[i2] = tw_cal[1]
twz_cal.iloc[i1].iloc[i2] = tw_cal[2]
U_cal_all[3].append(twx_cal)
U_cal_all[4].append(twy_cal)
U_cal_all[5].append(twz_cal)
# print(np.linalg.norm(np.vstack(wS_cal_list) - np.array((0, 0.5, 0)), axis=-1).max())
# print(np.linalg.norm(np.vstack(wE_err_list), axis=-1).max())
In [66]:
for use_uidx in (0, 1, 2, 3, 4, 5):
tu_cal = np.dstack(U_cal_all[use_uidx])
spf_tb.show_ui_psi(tu_cal, ttheta_all, tphi_all, tpsi_all, dpi=200)
In [68]:
for use_uidx in (0, 1, 2, 3, 4, 5):
tu_cal = np.dstack(U_cal_all[use_uidx])
tu_sim = np.dstack(U_all[use_uidx])
spf_tb.show_ui_psi(tu_cal - tu_sim, ttheta_all, tphi_all, tpsi_all, dpi=200)
In [ ]:
In [5]:
from src.objComposite import *
from codeStore.helix_common import *
from src import stokes_flow as sf
problem_kwargs = {'nth': 10,
'rh11': 0.1,
'solve_method': 'gmres',
'save_vtk': False,
'plot_geo': False,
'rot_theta': 0,
'ffweighty': 2.0,
'restart': False,
'n_tail': 1,
'getConvergenceHistory': False,
'center': np.array([0, 0, 0]),
'ffweightT': 2.0,
'eh': -1.0,
'precondition_method': 'none',
'region_type': 'rectangle',
'belemshandle': 'belems',
'matname': 'body1',
'field_range': np.array([[-3, -3, -3], [ 3, 3, 3]]),
'hfct': 1.0,
'rel_Uh': np.array([0., 0., 0., 0., 0., 0.]),
'ffweightz': 2.0,
'matrix_method': 'pf',
'ph': 0.666667,
'n_node_threshold': 5000,
'zoom_factor': 1.0,
'left_hand': False,
'ch': 3.0,
'ffweightx': 2.0,
'fileHandle': 'hlxC01B05_baseFlow',
'rh1': 0.2, 'with_cover': 2,
'rT2': 0.001,
'rot_norm': np.array([1, 0, 0]),
'rh2': 0.03,
'repeat_n': 1,
'n_grid': np.array([10, 10, 10]),
'bnodeshandle': 'bnodes',
'basei': 1,
'MPISIZE': 1,
'rh12': 0.1,
'pickProblem': False}
tail_obj_list = create_ecoli_tail(moveh=np.zeros(3), **problem_kwargs)
In [8]:
%matplotlib notebook
tail_obj_list = create_ecoli_tail(moveh=np.zeros(3), **problem_kwargs)
tobj = sf.StokesFlowObj()
tobj.combine(tail_obj_list)
tobj.node_rotation(norm=np.array([0, 1, 0]), theta=np.pi / 2)
tobj2 = tobj.copy()
tobj.node_rotation(norm=np.array([0, 0, 1]), theta=np.pi)
tobj3 = tobj.copy()
tobj3.node_rotation(norm=np.array([0, 1, 0]), theta=np.pi)
tobj.show_u_nodes()
tobj2.show_u_nodes()
tobj3.show_u_nodes()
Out[8]: