repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
gecco-2022
|
gecco-2022-main/AND-XOR/DynamicalMatrix.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 22:09:09 2017
@author: Hightoutou
"""
def DM_mass(N, x0, y0, D0, m0, L):
import numpy as np
Lx = L[0]
Ly = L[1]
M = np.zeros((2*N, 2*N))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
rijsq = dx**2+dy**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0],[0,1]])/rij/dij
Mij = Mij1+Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
m_sqrt = np.zeros((2*N, 2*N))
m_inv = np.zeros((2*N, 2*N))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_3D(N, x0, y0, z0, D0, m0, L):
import numpy as np
Lx = L[0]
Ly = L[1]
Lz = L[2]
M = np.zeros((3*N, 3*N))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
dz = z0[i]-z0[j]
dz = dz-round(dz/Lz)*Lz
rijsq = dx**2+dy**2+dz**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy, dx*dz], [dy*dx, dy*dy, dy*dz], [dz*dx, dz*dy, dz*dz]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0,0],[0,1,0],[0,0,1]])/rij/dij
Mij = Mij1+Mij2
M[3*i:3*i+3,3*j:3*j+3] = Mij
M[3*j:3*j+3,3*i:3*i+3] = Mij
M[3*i:3*i+3,3*i:3*i+3] = M[3*i:3*i+3,3*i:3*i+3] - Mij
M[3*j:3*j+3,3*j:3*j+3] = M[3*j:3*j+3,3*j:3*j+3] - Mij
m_sqrt = np.zeros((3*N, 3*N))
m_inv = np.zeros((3*N, 3*N))
for i in range(N):
m_sqrt[3*i, 3*i] = 1/np.sqrt(m0[i])
m_sqrt[3*i+1, 3*i+1] = 1/np.sqrt(m0[i])
m_sqrt[3*i+2, 3*i+2] = 1/np.sqrt(m0[i])
m_inv[3*i, 3*i] = 1/m0[i]
m_inv[3*i+1, 3*i+1] = 1/m0[i]
m_inv[3*i+2, 3*i+2] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_Yfixed(N, x0, y0, D0, m0, Lx, y_bot, y_top, k):
import numpy as np
M = np.zeros((2*N, 2*N))
contactNum = 0
for i in range(N):
r_now = 0.5*D0[i]
if y0[i]-y_bot<r_now or y_top-y0[i]<r_now:
M[2*i+1, 2*i+1] = M[2*i+1, 2*i+1]+1/r_now/r_now
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
rijsq = dx**2+dy**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0],[0,1]])/rij/dij
Mij = Mij1+Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
M = k*M
m_sqrt = np.zeros((2*N, 2*N))
m_inv = np.zeros((2*N, 2*N))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_Xfixed(N, x0, y0, D0, m0, Ly):
import numpy as np
M = np.zeros((2*N, 2*N))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
rijsq = dx**2+dy**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0],[0,1]])/rij/dij
Mij = Mij1+Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
m_sqrt = np.zeros((2*N, 2*N))
m_inv = np.zeros((2*N, 2*N))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_DiffK_Yfixed(N, x0, y0, D0, m0, Lx, y_bot, y_top, k_list, k_type):
import numpy as np
M = np.zeros((2*N, 2*N))
contactNum = 0
for i in range(N):
r_now = 0.5*D0[i]
if y0[i]-y_bot<r_now or y_top-y0[i]<r_now:
M[2*i+1, 2*i+1] = M[2*i+1, 2*i+1] + k_list[k_type[i]] / r_now / r_now
for j in range(i):
dij = 0.5 * (D0[i] + D0[j])
dijsq = dij**2
dx = x0[i] - x0[j]
dx = dx - round(dx / Lx) * Lx
dy = y0[i] - y0[j]
rijsq = dx**2 + dy**2
if rijsq < dijsq:
contactNum += 1
k = k_list[(k_type[i] ^ k_type[j]) + np.maximum(k_type[i], k_type[j])]
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -k * rijmat / rijsq / dijsq
Mij2 = -k * (1.0 - rij / dij) * (rijmat / rijsq - [[1,0],[0,1]]) / rij / dij
Mij = Mij1 + Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
m_sqrt = np.zeros((2*N, 2*N))
m_inv = np.zeros((2*N, 2*N))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_Zfixed_3D(N, x0, y0, z0, D0, m0, L):
import numpy as np
Lx = L[0]
Ly = L[1]
Lz = L[2]
M = np.zeros((3*N, 3*N))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
dz = z0[i]-z0[j]
rijsq = dx**2+dy**2+dz**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy, dx*dz], [dy*dx, dy*dy, dy*dz], [dz*dz, dz*dy, dz*dz]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0,0],[0,1,0],[0,0,1]])/rij/dij
Mij = Mij1+Mij2
M[3*i:3*i+3,3*j:3*j+3] = Mij
M[3*j:3*j+3,3*i:3*i+3] = Mij
M[3*i:3*i+3,3*i:3*i+3] = M[3*i:3*i+3,3*i:3*i+3] - Mij
M[3*j:3*j+3,3*j:3*j+3] = M[3*j:3*j+3,3*j:3*j+3] - Mij
m_sqrt = np.zeros((3*N, 3*N))
m_inv = np.zeros((3*N, 3*N))
for i in range(N):
m_sqrt[3*i, 3*i] = 1/np.sqrt(m0[i])
m_sqrt[3*i+1, 3*i+1] = 1/np.sqrt(m0[i])
m_sqrt[3*i+2, 3*i+2] = 1/np.sqrt(m0[i])
m_inv[3*i, 3*i] = 1/m0[i]
m_inv[3*i+1, 3*i+1] = 1/m0[i]
m_inv[3*i+2, 3*i+2] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_UpPlate(N, x0, y0, D0, m0, Lx, y_up, m_up):
import numpy as np
M = np.zeros((2*N+1, 2*N+1))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
rijsq = dx**2+dy**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0],[0,1]])/rij/dij
Mij = Mij1+Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
for i in range(N):
r_now = 0.5*D0[i]
if y0[i]<r_now:
M[2*i+1, 2*i+1] = M[2*i+1, 2*i+1]+1/r_now**2
if y_up-y0[i]<r_now:
M[2*i+1, 2*i+1] = M[2*i+1, 2*i+1]+1/r_now**2
M[2*N, 2*N] = M[2*N, 2*N]+1/r_now**2
M[2*i+1, 2*N] = M[2*i+1, 2*N]-1/r_now**2
M[2*N, 2*i+1] = M[2*N, 2*i+1]-1/r_now**2
m_sqrt = np.zeros((2*N+1, 2*N+1))
m_inv = np.zeros((2*N+1, 2*N+1))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
m_sqrt[2*N, 2*N] = 1/np.sqrt(m_up)
m_inv[2*N, 2*N] = 1/m_up
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_UpPlate_3D(N, x0, y0, z0, D0, m0, Lx, Ly, z_up, m_up):
import numpy as np
M = np.zeros((3*N+1, 3*N+1))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
dz = z0[i]-z0[j]
rijsq = dx**2+dy**2+dz**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy, dx*dz], [dy*dx, dy*dy, dy*dz], [dz*dz, dz*dy, dz*dz]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0,0],[0,1,0],[0,0,1]])/rij/dij
Mij = Mij1+Mij2
M[3*i:3*i+3,3*j:3*j+3] = Mij
M[3*j:3*j+3,3*i:3*i+3] = Mij
M[3*i:3*i+3,3*i:3*i+3] = M[3*i:3*i+3,3*i:3*i+3] - Mij
M[3*j:3*j+3,3*j:3*j+3] = M[3*j:3*j+3,3*j:3*j+3] - Mij
for i in range(N):
r_now = 0.5*D0[i]
if z0[i]<r_now:
M[3*i+2, 3*i+2] = M[3*i+2, 3*i+2]+1/r_now**2
if z_up-z0[i]<r_now:
M[3*i+2, 3*i+2] = M[3*i+2, 3*i+2]+1/r_now**2
M[3*N, 3*N] = M[3*N, 3*N]+1/r_now**2
M[3*i+2, 3*N] = M[3*i+2, 3*N]-1/r_now**2
M[3*N, 3*i+2] = M[3*N, 3*i+2]-1/r_now**2
m_sqrt = np.zeros((3*N+1, 3*N+1))
m_inv = np.zeros((3*N+1, 3*N+1))
for i in range(N):
m_sqrt[3*i, 3*i] = 1/np.sqrt(m0[i])
m_sqrt[3*i+1, 3*i+1] = 1/np.sqrt(m0[i])
m_sqrt[3*i+2, 3*i+2] = 1/np.sqrt(m0[i])
m_inv[3*i, 3*i] = 1/m0[i]
m_inv[3*i+1, 3*i+1] = 1/m0[i]
m_inv[3*i+2, 3*i+2] = 1/m0[i]
m_sqrt[3*N, 3*N] = 1/np.sqrt(m_up)
m_inv[3*N, 3*N] = 1/m_up
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
| 12,537 | 30.423559 | 104 |
py
|
gecco-2022
|
gecco-2022-main/AND-XOR/ConfigPlot.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 21:01:26 2017
@author: Hightoutou
"""
import numpy as np
def ConfigPlot_DiffSize(N, x, y, D, L, mark_print):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
Dmin = min(D)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
D_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
D_all.append(D[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_alpha(0.3)
if D_all[i] > Dmin:
e.set_facecolor('C1')
else:
e.set_facecolor('C0')
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
def ConfigPlot_DiffMass(N, x, y, D, L, m, mark_print, hn):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffMass2(N, x, y, D, L, m, mark_print, hn, in1, in2, out):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
if i==in1:
e.set_edgecolor((0, 1, 0))
e.set_linewidth(4)
elif i==in2:
e.set_edgecolor((0, 0, 1))
e.set_linewidth(4)
elif i==out:
e.set_edgecolor((1, 0, 0))
e.set_linewidth(4)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffStiffness(N, x, y, D, L, m, mark_print, hn):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C2')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffStiffness2(N, x, y, D, L, m, mark_print, hn, in1, in2, out):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
if i==in1:
e.set_edgecolor((0, 1, 0))
e.set_linewidth(4)
elif i==in2:
e.set_edgecolor((0, 0, 1))
e.set_linewidth(4)
elif i==out:
e.set_edgecolor((1, 0, 0))
e.set_linewidth(4)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C2')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffStiffness3(N, x, y, D, L, m, mark_print, hn, in1, in2, out):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
if i==in1:
e.set_edgecolor((0, 1, 0))
e.set_linewidth(4)
plt.scatter(x_now, y_now, marker='^', s=80, color=(0, 1, 0, 1))
elif i==in2:
e.set_edgecolor((0, 0, 1))
e.set_linewidth(4)
plt.scatter(x_now, y_now, marker='s', s=80, color=(0, 0, 1, 1))
elif i==out:
e.set_edgecolor((1, 0, 0))
e.set_linewidth(4)
plt.scatter(x_now, y_now, marker='*', s=100, color=(1, 0, 0, 1))
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('k')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
import matplotlib.lines as mlines
red_star = mlines.Line2D([], [], color=(1, 0, 0), marker='*', linestyle='None',
markersize=10, label='Output')
blue_square = mlines.Line2D([], [], color=(0, 0, 1), marker='s', linestyle='None',
markersize=10, label='Input 2')
green_triangle = mlines.Line2D([], [], color=(0, 1, 0), marker='^', linestyle='None',
markersize=10, label='Input 1')
plt.legend(handles=[red_star, green_triangle, blue_square], bbox_to_anchor=(1.215, 1))
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffMass_3D(N, x, y, z, D, L, m, mark_print):
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
m_min = min(m)
m_max = max(m)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_aspect('equal')
sphes = []
m_all = []
for i in range(int(N/2)):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
z_now = z[i]%L[2]
r_now = 0.5*D[i]
#alpha_now = 0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3
alpha_now = 0.3
pos1 = 0
pos2 = 1
for j in range(pos1, pos2):
for k in range(pos1, pos2):
for l in range(pos1, pos2):
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x_plot = x_now+j*L[0]+r_now * np.outer(np.cos(u), np.sin(v))
y_plot = y_now+k*L[1]+r_now * np.outer(np.sin(u), np.sin(v))
z_plot = z_now+l*L[2]+r_now * np.outer(np.ones(np.size(u)), np.cos(v))
ymin = y_plot[y_plot>0].min()
ymax = y_plot[y_plot>0].max()
print (i, ymin, ymax)
ax.plot_surface(x_plot,y_plot,z_plot,rstride=4,cstride=4, color='C0',linewidth=0,alpha=alpha_now)
#sphes.append(e)
#m_all.append(m[i])
# i = 0
# for e in sphes:
# ax.add_artist(e)
# e.set_clip_box(ax.bbox)
# e.set_facecolor('C0')
# e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
#e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
# i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
ax.set_zlim(0, L[2])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
def ConfigPlot_YFixed_rec(N, x, y, D, Lx, y_top, y_bot, m, mark_order):
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse, Rectangle
mark_print = 0
m_min = min(m)
m_max = max(m)
if m_min == m_max:
m_max *= 1.001
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%Lx
y_now = y[i]
if mark_order==1:
plt.text(x_now, y_now, str(i))
for k in range(-1, 2):
e = Ellipse((x_now+k*Lx, y_now), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.3+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
#rect = Rectangle([0, y_top], Lx, 0.2*D[0], color='C0')
#ax.add_patch(rect)
for nn in np.arange(N):
x1 = x[nn]%Lx
d_up = y_top-y[nn]
d_bot = y[nn]-y_bot
r_now = 0.5*D[nn]
if d_up<r_now:
ax.plot([x1, x1], [y[nn], y[nn]+r_now], '-', color='w')
if d_bot<r_now:
ax.plot([x1, x1], [y[nn], y[nn]-r_now], '-', color='w')
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
x2 = x[mm]%Lx
if x2>x1:
xl = x1
xr = x2
yl = y[nn]
yr = y[mm]
else:
xl = x2
xr = x1
yl = y[mm]
yr = y[nn]
dx0 = xr-xl
dx = dx0-round(dx0/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
if dx0<Dmn:
ax.plot([xl, xr], [yl, yr], '-', color='w')
else:
ax.plot([xl, xr-Lx], [yl, yr], '-', color='w')
ax.plot([xl+Lx, xr], [yl, yr], '-', color='w')
ax.set_xlim(0, Lx)
ax.set_ylim(y_bot, y_top)
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/plot_test/fig'+str(int(ind_nt+1e4))+'.png', dpi = 150)
def ConfigPlot_DiffMass_SP(N, x, y, D, L, m, mark_print, ind_in, ind_out, ind_fix):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
width = 2
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m[i]-m_min)/(m_max-m_min)*0.3)
if i == ind_in:
e.set_edgecolor('r')
e.set_linewidth(width)
if i == ind_out:
e.set_edgecolor('b')
e.set_linewidth(width)
if i == ind_fix:
e.set_edgecolor('k')
e.set_linewidth(width)
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
def ConfigPlot_DiffMass_FixLx(N, x, y, D, L, m, mark_print, ind_wall):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
width = 2
for i in range(N):
x_now = x[i]
y_now = y[i]%L[1]
for l in range(-1, 2):
e = Ellipse((x_now, y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
if ind_wall[i] > 0:
e.set_edgecolor('k')
e.set_linewidth(width)
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
def ConfigPlot_DiffMass_SP_rec(N, x, y, D, L, m, mark_print, ind_in, ind_out, ind_fix):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
width = 2
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m[i]-m_min)/(m_max-m_min)*0.3)
if i == ind_in:
e.set_edgecolor('r')
e.set_linewidth(width)
if i == ind_out:
e.set_edgecolor('b')
e.set_linewidth(width)
if i == ind_fix:
e.set_edgecolor('k')
e.set_linewidth(width)
Lx = L[0]
Ly = L[1]
for nn in np.arange(N):
x1 = x[nn]%Lx
y1 = y[nn]%Ly
for mm in np.arange(nn+1, N):
x2 = x[mm]%Lx
y2 = y[mm]%Ly
if x2>x1:
xl = x1
xr = x2
yl = y1
yr = y2
else:
xl = x2
xr = x1
yl = y2
yr = y1
dx0 = xr-xl
dx = dx0-round(dx0/Lx)*Lx
if y2>y1:
xd = x1
xu = x2
yd = y1
yu = y2
else:
xd = x2
xu = x1
yd = y2
yu = y1
dy0 = yu-yd
dy = dy0-round(dy0/Ly)*Ly
Dmn = 0.5*(D[mm]+D[nn])
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
if dx0<Dmn and dy0<Dmn:
ax.plot([xl, xr], [yl, yr], '-', color='w')
else:
if dx0>Dmn and dy0>Dmn:
if yr>yl:
ax.plot([xl, xr-Lx], [yl, yr-Ly], '-', color='w')
ax.plot([xl+Lx, xr], [yl+Ly, yr], '-', color='w')
else:
ax.plot([xl, xr-Lx], [yl, yr+Ly], '-', color='w')
ax.plot([xl+Lx, xr], [yl-Ly, yr], '-', color='w')
else:
if dx0>Dmn:
ax.plot([xl, xr-Lx], [yl, yr], '-', color='w')
ax.plot([xl+Lx, xr], [yl, yr], '-', color='w')
if dy0>Dmn:
ax.plot([xd, xu], [yd, yu-Ly], '-', color='w')
ax.plot([xd, xu], [yd+Ly, yu], '-', color='w')
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
return fig
def ConfigPlot_EigenMode_DiffMass(N, x, y, D, L, m, em, mark_print, hn):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
if m_min == m_max:
m_max *= 1.001
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
r_now = D[0]*0.5
dr = np.zeros(N)
for i in range(N):
dr[i] = np.sqrt(em[2*i]**2+em[2*i+1]**2)
dr_max = max(dr)
for i in range(N):
ratio = dr[i]/dr_max*r_now/dr_max
plt.arrow(x[i], y[i],em[2*i]*ratio, em[2*i+1]*ratio, head_width=0.005)
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_YFixed_SelfAssembly(N, Nl, x, y, theta, n, d1, d2, Lx, y_top, y_bot):
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse, Rectangle
mark_order = 0
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
alpha_all = []
alpha1 = 0.6
alpha2 = 0.3
for i in range(N):
x_now = x[i]%Lx
y_now = y[i]
if mark_order==1:
plt.text(x_now, y_now, str(i))
alpha = alpha1 if i < Nl else alpha2
for k in range(-1, 2):
e = Ellipse((x_now+k*Lx, y_now), d1,d1,0)
ells.append(e)
alpha_all.append(alpha)
if i >= Nl:
for ind in range(n):
x_i = x_now+k*Lx+0.5*(d1+d2)*np.cos(theta[i]+ind*2*np.pi/n)
y_i = y_now+0.5*(d1+d2)*np.sin(theta[i]+ind*2*np.pi/n)
e = Ellipse((x_i, y_i), d2,d2,0)
ells.append(e)
alpha_all.append(alpha)
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(alpha_all[i])
i += 1
ax.set_xlim(0, Lx)
ax.set_ylim(y_bot, y_top)
plt.show()
def ConfigPlot_YFixed_SelfAssembly_BumpyBd(N, n_col, Nl, x, y, theta, n, d0, d1, d2, Lx, y_top, y_bot):
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse, Rectangle
mark_order = 0
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
alpha_all = []
alpha1 = 0.6
alpha2 = 0.3
for i in range(n_col+1):
x_now = i*d0
e1 = Ellipse((x_now, y_bot), d0,d0,0)
e2 = Ellipse((x_now, y_top), d0,d0,0)
ells.append(e1)
alpha_all.append(alpha1)
ells.append(e2)
alpha_all.append(alpha1)
for i in range(N):
x_now = x[i]%Lx
y_now = y[i]
if mark_order==1:
plt.text(x_now, y_now, str(i))
alpha = alpha1 if i < Nl else alpha2
for k in range(-1, 2):
e = Ellipse((x_now+k*Lx, y_now), d1,d1,0)
ells.append(e)
alpha_all.append(alpha)
if i >= Nl:
for ind in range(n):
x_i = x_now+k*Lx+0.5*(d1+d2)*np.cos(theta[i]+ind*2*np.pi/n)
y_i = y_now+0.5*(d1+d2)*np.sin(theta[i]+ind*2*np.pi/n)
e = Ellipse((x_i, y_i), d2,d2,0)
ells.append(e)
alpha_all.append(alpha)
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(alpha_all[i])
i += 1
ax.set_xlim(0, Lx)
ax.set_ylim(y_bot, y_top)
plt.show()
| 22,835 | 29.488652 | 117 |
py
|
gecco-2022
|
gecco-2022-main/AND-XOR/MOO2.py
|
# multi-objective optimization to evolve AND and XOR gates in the same material
# imports for DEAP
import time, array, random, copy, math
import numpy as np
from deap import algorithms, base, benchmarks, tools, creator
import matplotlib.pyplot as plt
import seaborn
#seaborn.set(style='whitegrid')
import pandas as pd
# imports for the simulator
from ConfigPlot import ConfigPlot_EigenMode_DiffMass, ConfigPlot_YFixed_rec, ConfigPlot_DiffMass_SP
from MD_functions import MD_VibrSP_ConstV_Yfixed_DiffK
from MD_functions import FIRE_YFixed_ConstV_DiffK
from DynamicalMatrix import DM_mass_DiffK_Yfixed
from plot_functions import Line_single, Line_multi
from ConfigPlot import ConfigPlot_DiffStiffness
import random
import matplotlib.pyplot as plt
import pickle
from os.path import exists
from scoop import futures
import multiprocessing
import os
def evaluate(indices):
#%% Initial Configuration
m1 = 1
m2 = 10
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# calculating the bandgap - no need to do this in this problem
#w, v = DM_mass_DiffK_Yfixed(N, x_ini, y_ini, D, mass, Lx, 0.0, Ly, k_list, k_type)
#w = np.real(w)
#v = np.real(v)
#freq = np.sqrt(np.absolute(w))
#ind_sort = np.argsort(freq)
#freq = freq[ind_sort]
#v = v[:, ind_sort]
#ind = freq > 1e-4
#eigen_freq = freq[ind]
#eigen_mode = v[:, ind]
#w_delta = eigen_freq[1:] - eigen_freq[0:-1]
#index = np.argmax(w_delta)
#F_low_exp = eigen_freq[index]
#F_high_exp = eigen_freq[index+1]
#print("specs:")
#print(F_low_exp)
#print(F_high_exp)
#print(max(w_delta))
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr = 7
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
andness = 2*gain1/(gain2+gain3)
# we are designing an and gait at this frequency
Freq_Vibr = 10
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
XOR = (gain2+gain3)/(2*gain1)
print("done eval", flush=True)
return andness, XOR
#cleaning up the data files
try:
os.remove("results.pickle")
except OSError:
pass
try:
os.remove("logs.pickle")
except OSError:
pass
try:
os.remove("hofs.pickle")
except OSError:
pass
try:
os.remove("hostfile")
except OSError:
pass
try:
os.remove("scoop-python.sh")
except OSError:
pass
# start of the optimization:
random.seed(a=42)
creator.create("FitnessMax", base.Fitness, weights=(1.0, 1.0))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 30)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", evaluate)
toolbox.register("mate", tools.cxOnePoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selNSGA2)
# parallelization?
toolbox.register("map", futures.map)
stats = tools.Statistics()
#stats.register("avg", np.mean, axis=0)
#stats.register("std", np.std, axis=0)
#stats.register("min", np.min, axis=0)
#stats.register("max", np.max, axis=0)
# also save the population of each generation
stats.register("pop", copy.deepcopy)
def main():
toolbox.pop_size = 50
toolbox.max_gen = 250
toolbox.mut_prob = 0.8
logbook = tools.Logbook()
logbook.header = ["gen", "evals"] + stats.fields
hof = tools.HallOfFame(1, similar=np.array_equal) #can change the size
def run_ea(toolbox, stats=stats, verbose=True, hof=hof):
pop = toolbox.population(n=toolbox.pop_size)
pop = toolbox.select(pop, len(pop))
return algorithms.eaMuPlusLambda(pop, toolbox, mu=toolbox.pop_size,
lambda_=toolbox.pop_size,
cxpb=1-toolbox.mut_prob, #: no cross-over?
mutpb=toolbox.mut_prob,
stats=stats,
ngen=toolbox.max_gen,
verbose=verbose,
halloffame=hof)
res,log = run_ea(toolbox, stats=stats, verbose=True, hof=hof)
return res, log, hof
if __name__ == '__main__':
print("starting")
res, log, hof = main()
print("done")
pickle.dump(res, open('results.pickle', 'wb'))
pickle.dump(log, open('logs.pickle', 'wb'))
pickle.dump(hof, open('hofs.pickle', 'wb'))
| 12,452 | 35.626471 | 248 |
py
|
gecco-2022
|
gecco-2022-main/AND-XOR/MOO.py
|
# multi-objective optimization to evolve AND and XOR gates in the same material
# imports for DEAP
import time, array, random, copy, math
import numpy as np
from deap import algorithms, base, benchmarks, tools, creator
import matplotlib.pyplot as plt
import seaborn
#seaborn.set(style='whitegrid')
import pandas as pd
# imports for the simulator
from ConfigPlot import ConfigPlot_EigenMode_DiffMass, ConfigPlot_YFixed_rec, ConfigPlot_DiffMass_SP
from MD_functions import MD_VibrSP_ConstV_Yfixed_DiffK
from MD_functions import FIRE_YFixed_ConstV_DiffK
from DynamicalMatrix import DM_mass_DiffK_Yfixed
from plot_functions import Line_single, Line_multi
from ConfigPlot import ConfigPlot_DiffStiffness
import random
import matplotlib.pyplot as plt
import pickle
from os.path import exists
from scoop import futures
import multiprocessing
import os
def evaluate(indices):
#%% Initial Configuration
m1 = 1
m2 = 10
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# calculating the bandgap - no need to do this in this problem
#w, v = DM_mass_DiffK_Yfixed(N, x_ini, y_ini, D, mass, Lx, 0.0, Ly, k_list, k_type)
#w = np.real(w)
#v = np.real(v)
#freq = np.sqrt(np.absolute(w))
#ind_sort = np.argsort(freq)
#freq = freq[ind_sort]
#v = v[:, ind_sort]
#ind = freq > 1e-4
#eigen_freq = freq[ind]
#eigen_mode = v[:, ind]
#w_delta = eigen_freq[1:] - eigen_freq[0:-1]
#index = np.argmax(w_delta)
#F_low_exp = eigen_freq[index]
#F_high_exp = eigen_freq[index+1]
#print("specs:")
#print(F_low_exp)
#print(F_high_exp)
#print(max(w_delta))
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr = 7
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
andness = 2*gain1/(gain2+gain3)
# we are designing an and gait at this frequency
Freq_Vibr = 10
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
XOR = (gain2+gain3)/(2*gain1)
print("done eval", flush=True)
return andness, XOR
#cleaning up the data files
try:
os.remove("results.pickle")
except OSError:
pass
try:
os.remove("logs.pickle")
except OSError:
pass
try:
os.remove("hofs.pickle")
except OSError:
pass
try:
os.remove("hostfile")
except OSError:
pass
try:
os.remove("scoop-python.sh")
except OSError:
pass
# start of the optimization:
random.seed(a=42)
creator.create("FitnessMax", base.Fitness, weights=(1.0, 1.0))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 30)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", evaluate)
toolbox.register("mate", tools.cxOnePoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selNSGA2)
# parallelization?
toolbox.register("map", futures.map)
stats = tools.Statistics(key=lambda ind: ind.fitness.values)
stats.register("avg", np.mean, axis=0)
stats.register("std", np.std, axis=0)
stats.register("min", np.min, axis=0)
stats.register("max", np.max, axis=0)
# also save the population of each generation
stats.register("pop", copy.deepcopy)
def main():
toolbox.pop_size = 50
toolbox.max_gen = 250
toolbox.mut_prob = 0.8
logbook = tools.Logbook()
logbook.header = ["gen", "evals"] + stats.fields
hof = tools.HallOfFame(1, similar=np.array_equal) #can change the size
def run_ea(toolbox, stats=stats, verbose=True, hof=hof):
pop = toolbox.population(n=toolbox.pop_size)
pop = toolbox.select(pop, len(pop))
return algorithms.eaMuPlusLambda(pop, toolbox, mu=toolbox.pop_size,
lambda_=toolbox.pop_size,
cxpb=1-toolbox.mut_prob, #: no cross-over?
mutpb=toolbox.mut_prob,
stats=stats,
ngen=toolbox.max_gen,
verbose=verbose,
halloffame=hof)
res,log = run_ea(toolbox, stats=stats, verbose=True, hof=hof)
return res, log, hof
if __name__ == '__main__':
print("starting")
res, log, hof = main()
print("done")
pickle.dump(res, open('results.pickle', 'wb'))
pickle.dump(log, open('logs.pickle', 'wb'))
pickle.dump(hof, open('hofs.pickle', 'wb'))
# print info for best solution found:
#print("-----")
#print(len(hof))
#best = hof.items[0]
#print("-- Best Individual = ", best)
#print("-- Best Fitness = ", best.fitness.values)
# print hall of fame members info:
#print("- Best solutions are:")
# for i in range(HALL_OF_FAME_SIZE):
# print(i, ": ", hof.items[i].fitness.values[0], " -> ", hof.items[i])
#print("Hall of Fame Individuals = ", *hof.items, sep="\n")
#fronts = tools.emo.sortLogNondominated(res, len(res))
#for i,inds in enumerate(fronts):
# counter = 0
# for ind in inds:
# counter += 1
# if counter == 1 or counter == 15 or counter==30:
# print("####")
# evaluateAndPlot(ind)
#logbook.record(gen=0, evals=30, **record)
avg = log.select("avg")
std = log.select("std")
avg_stack = np.stack(avg, axis=0)
avg_f1 = avg_stack[:, 0]
avg_f2 = avg_stack[:, 1]
std_stack = np.stack(std, axis=0)
std_f1 = std_stack[:, 0]
std_f2 = std_stack[:, 1]
plt.figure(figsize=(6.4,4.8))
plt.plot(avg_f1, color='blue')
plt.fill_between(list(range(0, toolbox.max_gen+1)), avg_f1-std_f1, avg_f1+std_f1, color='cornflowerblue', alpha=0.2)
plt.xlabel("Generations")
plt.ylabel("Average Fitness")
plt.title("Average Fitness of Individuals in the Population - F1", fontsize='small')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.tight_layout()
plt.show()
plt.savefig("avg_F1.jpg", dpi = 300)
plt.figure(figsize=(6.4,4.8))
plt.plot(avg_f2, color='blue')
plt.fill_between(list(range(0, toolbox.max_gen+1)), avg_f2-std_f2, avg_f2+std_f2, color='cornflowerblue', alpha=0.2)
plt.xlabel("Generations")
plt.ylabel("Average Fitness")
plt.title("Average Fitness of Individuals in the Population - F2", fontsize='small')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.tight_layout()
plt.show()
plt.savefig("avg_F2.jpg", dpi = 300)
seaborn.set(style='whitegrid')
plot_colors = seaborn.color_palette("Set1", n_colors=10)
fig, ax = plt.subplots(1, figsize=(4,4))
for i,inds in enumerate(fronts):
par = [toolbox.evaluate(ind) for ind in inds]
print("fronts:")
print(par)
df = pd.DataFrame(par)
df.plot(ax=ax, kind='scatter',
x=df.columns[0], y=df.columns[1],
color=plot_colors[i])
plt.xlabel('$f_1(\mathbf{x})$');plt.ylabel('$f_2(\mathbf{x})$');
plt.title("Pareto Front", fontsize='small')
plt.show()
plt.savefig("paretoFront.jpg", dpi = 300)
| 15,147 | 35.501205 | 248 |
py
|
gecco-2022
|
gecco-2022-main/AND-XOR/plotMOO3.py
|
## plot stuff after loading everything from the pickled files for MOO
import time, array, random, copy, math
import numpy as np
from deap import algorithms, base, benchmarks, tools, creator
import matplotlib.pyplot as plt
import seaborn
import pandas as pd
import random
import pickle
from os.path import exists
import os
from ConfigPlot import ConfigPlot_DiffStiffness2, ConfigPlot_DiffStiffness3
from MD_functions import MD_VibrSP_ConstV_Yfixed_DiffK, FIRE_YFixed_ConstV_DiffK, MD_VibrSP_ConstV_Yfixed_DiffK2
from MD_functions import MD_VibrSP_ConstV_Yfixed_DiffK_Freqs, MD_VibrSP_ConstV_Yfixed_DiffK2_Freqs
from DynamicalMatrix import DM_mass_DiffK_Yfixed
from joblib import Parallel, delayed
import multiprocessing
plt.rcParams['pdf.fonttype'] = 42
plt.rcParams['ps.fonttype'] = 42
def evaluate(indices):
#%% Initial Configuration
m1 = 1
m2 = 10
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# calculating the bandgap - no need to do this in this problem
#w, v = DM_mass_DiffK_Yfixed(N, x_ini, y_ini, D, mass, Lx, 0.0, Ly, k_list, k_type)
#w = np.real(w)
#v = np.real(v)
#freq = np.sqrt(np.absolute(w))
#ind_sort = np.argsort(freq)
#freq = freq[ind_sort]
#v = v[:, ind_sort]
#ind = freq > 1e-4
#eigen_freq = freq[ind]
#eigen_mode = v[:, ind]
#w_delta = eigen_freq[1:] - eigen_freq[0:-1]
#index = np.argmax(w_delta)
#F_low_exp = eigen_freq[index]
#F_high_exp = eigen_freq[index+1]
#print("specs:")
#print(F_low_exp)
#print(F_high_exp)
#print(max(w_delta))
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr = 7
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
andness = 2*gain1/(gain2+gain3)
# we are designing an and gait at this frequency
Freq_Vibr = 10
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
XOR = (gain2+gain3)/(2*gain1)
print("done eval", flush=True)
return andness, XOR
random.seed(a=42)
creator.create("FitnessMax", base.Fitness, weights=(1.0, 1.0))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 30)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", evaluate)
toolbox.register("mate", tools.cxOnePoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selNSGA2)
# parallelization?
#toolbox.register("map", futures.map)
stats = tools.Statistics(key=lambda ind: ind.fitness.values)
stats.register("avg", np.mean, axis=0)
stats.register("std", np.std, axis=0)
stats.register("min", np.min, axis=0)
stats.register("max", np.max, axis=0)
toolbox.pop_size = 50
toolbox.max_gen = 250
toolbox.mut_prob = 0.8
logbook = tools.Logbook()
logbook.header = ["gen", "evals"] + stats.fields
hof = tools.HallOfFame(1, similar=np.array_equal) #can change the size
inds = pickle.load(open('test.pickle', 'rb'))
indices = []
for i in inds:
indices.append(np.array(i))
# plot the pareto front
plt.figure(figsize=(4,4))
num_cores = multiprocessing.cpu_count()
outputs = Parallel(n_jobs=num_cores)(delayed(evaluate)(ind) for ind in indices)
print(type(outputs))
print(outputs)
print(inds)
for point in outputs:
plt.scatter(x=point[0], y=point[1], color='blue', marker='o', alpha=0.4)
plt.scatter(x=point[0], y=point[1], color='blue', marker='o', alpha=0.4, label='front')
plt.xlabel('$f_1(\mathbf{x})$'+' = AND-ness', fontsize=16)
plt.ylabel('$f_2(\mathbf{x})$'+' = XOR-ness', fontsize=16)
plt.title("Pareto Front", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.legend(bbox_to_anchor=(1.215, 1))
plt.tight_layout()
plt.show()
| 11,771 | 36.730769 | 248 |
py
|
gecco-2022
|
gecco-2022-main/AND-XOR/plot_functions.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 22 14:48:04 2017
@author: Hightoutou
"""
import matplotlib.pyplot as plt
#import matplotlib
#matplotlib.use('TkAgg')
def Line_single(xdata, ydata, line_spec, xlabel, ylabel, mark_print, fn = '', xscale='linear', yscale='linear'):
fig, ax1 = plt.subplots()
fig.set_size_inches(3.5,3.5*3/4)
pos1 = ax1.get_position()
pos2 = [pos1.x0 + 0.12, pos1.y0 + 0.05, pos1.width-0.1, pos1.height]
ax1.set_position(pos2)
#ax1.tick_params(labelsize=10)
for axis in ['top','bottom','left','right']:
ax1.spines[axis].set_linewidth(2)
plt.ylabel(ylabel, fontsize=12)
plt.xlabel(xlabel, fontsize=12)
plt.xscale(xscale), plt.yscale(yscale)
plt.style.use('default')
ax1.plot(xdata, ydata, line_spec)
if mark_print == 1:
fig.savefig(fn, dpi = 300)
fig.show()
def Line_multi(xdata, ydata, line_spec, xlabel, ylabel, xscale='linear', yscale='linear'):
fig, ax1 = plt.subplots()
fig.set_size_inches(3.5,3.5*3/4)
ax1.tick_params(labelsize=10)
for axis in ['top','bottom','left','right']:
ax1.spines[axis].set_linewidth(2)
ax1.set_ylabel(ylabel, fontsize=12)
plt.xlabel(xlabel, fontsize=12)
plt.xscale(xscale), plt.yscale(yscale)
plt.style.use('default')
for ii in range(len(xdata)):
ax1.plot(xdata[ii], ydata[ii], line_spec[ii])
plt.show()
def Line_yy(xdata, ydata, line_spec, xlabel, ylabel, xscale='linear', yscale='linear'):
fig, ax1 = plt.subplots()
fig.set_size_inches(3.5,3.5*3/4)
ax1.tick_params(labelsize=10)
for axis in ['top','bottom','left','right']:
ax1.spines[axis].set_linewidth(2)
ax1.set_ylabel(ylabel[0], fontsize=12)
plt.xlabel(xlabel, fontsize=12)
plt.xscale(xscale), plt.yscale(yscale)
plt.style.use('default')
ax1.plot(xdata[0], ydata[0], line_spec[0])
ax2 = ax1.twinx()
ax2.set_ylabel(ylabel[1], fontsize=12)
ax2.plot(xdata[1], ydata[1], line_spec[1])
plt.show()
| 2,062 | 33.966102 | 112 |
py
|
gecco-2022
|
gecco-2022-main/AND-XOR/FFT_functions.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 17 15:10:21 2017
@author: Hightoutou
"""
import numpy as np
import matplotlib.pyplot as plt
from plot_functions import Line_multi, Line_single
#from numba import jit
def FFT_Fup(Nt, F, dt, Freq_Vibr):
sampling_rate = 1/dt
t = np.arange(Nt)*dt
fft_size = Nt
xs = F[:fft_size]
xf = np.absolute(np.fft.rfft(xs)/fft_size)
freqs = (2*np.pi)*np.linspace(0, sampling_rate/2, fft_size//2+1)
ind = freqs<30
freqs = freqs[ind]
xf = xf[ind]
if 1 == 0:
Line_multi([freqs[1:], [Freq_Vibr, Freq_Vibr]], [xf[1:], [min(xf[1:]), max(xf[1:])]], ['o', 'r--'], 'Frequency', 'FFT', 'linear', 'log')
return freqs[1:], xf[1:]
def FFT_Fup_RealImag(Nt, F, dt, Freq_Vibr):
sampling_rate = 1/dt
t = np.arange(Nt)*dt
fft_size = Nt
xs = F[:fft_size]
xf = np.fft.rfft(xs)/fft_size
freqs = (2*np.pi)*np.linspace(0, sampling_rate/2, fft_size/2+1)
ind = freqs<30
freqs = freqs[ind]
xf = xf[ind]
xf_real = xf.real
xf_imag = xf.imag
if 1 == 0:
Line_multi([freqs[1:], [Freq_Vibr, Freq_Vibr]], [xf[1:], [min(xf[1:]), max(xf[1:])]], ['o', 'r--'], 'Frequency', 'FFT')
return freqs[1:], xf_real[1:], xf_imag[1:]
#@jit
def vCorr_Cal(fft_size, Nt, y_raw):
y_fft = np.zeros(fft_size)
for jj in np.arange(fft_size):
sum_vcf = 0
sum_tt = 0
count = 0
for kk in np.arange(Nt-jj):
count = count+1
sum_vcf += y_raw[kk]*y_raw[kk+jj];
sum_tt = sum_tt+y_raw[kk]*y_raw[kk];
y_fft[jj] = sum_vcf/sum_tt;
return y_fft
def FFT_vCorr(Nt, N, vx_rec, vy_rec, dt):
sampling_rate = 1/dt
fft_size = Nt-1
freqs = (2*np.pi)*np.linspace(0, sampling_rate/2, fft_size/2+1)
for ii in np.arange(2*N):
#for ii in [0,4]:
if np.mod(ii, 10) == 0:
print('ii=%d\n' % (ii))
if ii >= N:
y_raw = vy_rec[:, ii-N]
else:
y_raw = vx_rec[:, ii]
y_fft = vCorr_Cal(fft_size, Nt, y_raw)
if ii == 0:
xf = np.absolute(np.fft.rfft(y_fft)/fft_size)
else:
xf += np.absolute(np.fft.rfft(y_fft)/fft_size)
ind = freqs<30
freqs = freqs[ind]
xf = xf[ind]
if 1 == 1:
Line_single(freqs[1:], xf[1:], 'o', 'Frequency', 'FFT')
return freqs[1:], xf[1:]
def FFT_vCorr_3D(Nt, N, vx_rec, vy_rec, vz_rec, dt):
sampling_rate = 1/dt
fft_size = Nt-1
freqs = (2*np.pi)*np.linspace(0, sampling_rate/2, fft_size/2+1)
for ii in np.arange(3*N):
#for ii in [0,4]:
if np.mod(ii, 10) == 0:
print('ii=%d\n' % (ii))
if ii >= 2*N:
y_raw = vz_rec[:, ii-2*N]
elif ii < N:
y_raw = vx_rec[:, ii]
else:
y_raw = vy_rec[:, ii-N]
y_fft = vCorr_Cal(fft_size, Nt, y_raw)
if ii == 0:
xf = np.absolute(np.fft.rfft(y_fft)/fft_size)
else:
xf += np.absolute(np.fft.rfft(y_fft)/fft_size)
ind = freqs<30
freqs = freqs[ind]
xf = xf[ind]
if 1 == 1:
Line_single(freqs[1:], xf[1:], 'o', 'Frequency', 'FFT')
return freqs[1:], xf[1:]
| 3,487 | 25.225564 | 152 |
py
|
gecco-2022
|
gecco-2022-main/AND-XOR/plotMOO.py
|
## plot stuff after loading everything from the pickled files for MOO
import time, array, random, copy, math
import numpy as np
from deap import algorithms, base, benchmarks, tools, creator
import matplotlib.pyplot as plt
import seaborn
import pandas as pd
import random
import pickle
from os.path import exists
import os
from ConfigPlot import ConfigPlot_DiffStiffness2, ConfigPlot_DiffStiffness3
from MD_functions import MD_VibrSP_ConstV_Yfixed_DiffK, FIRE_YFixed_ConstV_DiffK, MD_VibrSP_ConstV_Yfixed_DiffK2
from MD_functions import MD_VibrSP_ConstV_Yfixed_DiffK_Freqs, MD_VibrSP_ConstV_Yfixed_DiffK2_Freqs
from DynamicalMatrix import DM_mass_DiffK_Yfixed
plt.rcParams['pdf.fonttype'] = 42
plt.rcParams['ps.fonttype'] = 42
def evaluate(indices):
#%% Initial Configuration
m1 = 1
m2 = 10
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# calculating the bandgap - no need to do this in this problem
#w, v = DM_mass_DiffK_Yfixed(N, x_ini, y_ini, D, mass, Lx, 0.0, Ly, k_list, k_type)
#w = np.real(w)
#v = np.real(v)
#freq = np.sqrt(np.absolute(w))
#ind_sort = np.argsort(freq)
#freq = freq[ind_sort]
#v = v[:, ind_sort]
#ind = freq > 1e-4
#eigen_freq = freq[ind]
#eigen_mode = v[:, ind]
#w_delta = eigen_freq[1:] - eigen_freq[0:-1]
#index = np.argmax(w_delta)
#F_low_exp = eigen_freq[index]
#F_high_exp = eigen_freq[index+1]
#print("specs:")
#print(F_low_exp)
#print(F_high_exp)
#print(max(w_delta))
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr = 7
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
andness = 2*gain1/(gain2+gain3)
# we are designing an and gait at this frequency
Freq_Vibr = 10
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
XOR = (gain2+gain3)/(2*gain1)
print("done eval", flush=True)
return andness, XOR
def showPacking(indices):
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
m1=1
m2=10
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
# show packing
ConfigPlot_DiffStiffness3(N, x0, y0, D, [Lx,Ly], k_type, 0, '/Users/atoosa/Desktop/results/packing.pdf', ind_in1, ind_in2, ind_out)
def plotInOut_and(indices):
#%% Initial Configuration
k1 = 1.
k2 = 10.
m1 = 1
m2 = 10
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# calculating the bandgap - no need to do this in this problem
w, v = DM_mass_DiffK_Yfixed(N, x_ini, y_ini, D, mass, Lx, 0.0, Ly, k_list, k_type)
w = np.real(w)
v = np.real(v)
freq = np.sqrt(np.absolute(w))
ind_sort = np.argsort(freq)
freq = freq[ind_sort]
v = v[:, ind_sort]
ind = freq > 1e-4
eigen_freq = freq[ind]
eigen_mode = v[:, ind]
w_delta = eigen_freq[1:] - eigen_freq[0:-1]
index = np.argmax(w_delta)
F_low_exp = eigen_freq[index]
F_high_exp = eigen_freq[index+1]
plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.scatter(np.arange(0, len(eigen_freq)), eigen_freq, marker='x', color='blue')
plt.xlabel(r"Index $(k)$", fontsize=16)
plt.ylabel(r"Frequency $(\omega)$", fontsize=16)
plt.title("Frequency Spectrum", fontsize=16, fontweight="bold")
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
props = dict(facecolor='green', alpha=0.1)
myText = r'$\omega_{low}=$'+"{:.2f}".format(F_low_exp)+"\n"+r'$\omega_{high}=$'+"{:.2f}".format(F_high_exp)+"\n"+r'$\Delta \omega=$'+"{:.2f}".format(max(w_delta))
#plt.text(0.78, 0.15, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=16, bbox=props)
plt.text(0.2, 0.8, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=16, bbox=props)
plt.hlines(y=7, xmin=0, xmax=50, linewidth=1, linestyle='dashdot', color='limegreen', alpha=0.9)
plt.hlines(y=10, xmin=0, xmax=50, linewidth=1, linestyle='dotted', color='brown', alpha=0.9)
plt.text(51, 5, '$\omega=7$', fontsize=12, color='limegreen', alpha=0.9)
plt.text(51, 12, '$\omega=10$', fontsize=12, color='brown', alpha=0.9)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.tight_layout()
plt.show()
print("specs:")
print(F_low_exp)
print(F_high_exp)
print(max(w_delta))
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr = 7
# case 0, input [0, 0]
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.hlines(y=0, xmin=0, xmax=30, color='green', label='Input1', linestyle='dotted')
plt.hlines(y=0, xmin=0, xmax=30, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.hlines(y=0, xmin=0, xmax=30, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency", fontsize=16)
plt.ylabel("Amplitude of FFT", fontsize=16)
plt.title("Logic Gate Response - input = 00", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.ylim(0, 0.005)
plt.tight_layout()
plt.show()
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.hlines(y=0, xmin=0, xmax=10000, color='green', label='Input1', linestyle='solid')
plt.hlines(y=0, xmin=0, xmax=10000, color='blue', label='Input2', linestyle='dotted')
plt.hlines(y=0, xmin=0, xmax=10000, color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps", fontsize=16)
plt.ylabel("Displacement", fontsize=16)
plt.title("Logic Gate Response - input = 00", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.ylim(-0.0100, 0.0100)
plt.tight_layout()
plt.show()
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='Input1', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency", fontsize=16)
plt.ylabel("Amplitude of FFT", fontsize=16)
plt.title("Logic Gate Response - input = 11", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
myText = 'Gain='+"{:.3f}".format(gain1)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='Input1', linestyle='solid')
plt.plot(x_in2, color='blue', label='Input2', linestyle='dotted')
plt.plot(x_out-np.mean(x_out, axis=0), color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps", fontsize=16)
plt.ylabel("Displacement", fontsize=16)
plt.title("Logic Gate Response - input = 11", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='Input1', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency", fontsize=16)
plt.ylabel("Amplitude of FFT", fontsize=16)
plt.title("Logic Gate Response - input = 10", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
myText = 'Gain='+"{:.3f}".format(gain2)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='Input1', linestyle='solid')
plt.plot(x_in2, color='blue', label='Input2', linestyle='dotted')
plt.plot(x_out-np.mean(x_out, axis=0), color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps", fontsize=16)
plt.ylabel("Displacement", fontsize=16)
plt.title("Logic Gate Response - input = 10", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='Input1', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency", fontsize=16)
plt.ylabel("Amplitude of FFT", fontsize=16)
plt.title("Logic Gate Response - input = 01", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
myText = 'Gain='+"{:.3f}".format(gain3)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='Input1', linestyle='solid')
plt.plot(x_in2, color='blue', label='Input2', linestyle='dotted')
plt.plot(x_out-np.mean(x_out, axis=0), color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps", fontsize=16)
plt.ylabel("Displacement", fontsize=16)
plt.title("Logic Gate Response - input = 01", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
print("gain1:")
print(gain1)
print("gain2:")
print(gain2)
print("gain3:")
print(gain3)
andness = 2*gain1/(gain2+gain3)
return andness
def plotInOut_xor(indices):
#%% Initial Configuration
k1 = 1.
k2 = 10.
m1 = 1
m2 = 10
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# calculating the bandgap - no need to do this in this problem
w, v = DM_mass_DiffK_Yfixed(N, x_ini, y_ini, D, mass, Lx, 0.0, Ly, k_list, k_type)
w = np.real(w)
v = np.real(v)
freq = np.sqrt(np.absolute(w))
ind_sort = np.argsort(freq)
freq = freq[ind_sort]
v = v[:, ind_sort]
ind = freq > 1e-4
eigen_freq = freq[ind]
eigen_mode = v[:, ind]
w_delta = eigen_freq[1:] - eigen_freq[0:-1]
index = np.argmax(w_delta)
F_low_exp = eigen_freq[index]
F_high_exp = eigen_freq[index+1]
plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.scatter(np.arange(0, len(eigen_freq)), eigen_freq, marker='x', color='blue')
plt.xlabel(r"Index $(k)$", fontsize=16)
plt.ylabel(r"Frequency $(\omega)$", fontsize=16)
plt.title("Frequency Spectrum", fontsize=16, fontweight="bold")
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
props = dict(facecolor='green', alpha=0.1)
myText = r'$\omega_{low}=$'+"{:.2f}".format(F_low_exp)+"\n"+r'$\omega_{high}=$'+"{:.2f}".format(F_high_exp)+"\n"+r'$\Delta \omega=$'+"{:.2f}".format(max(w_delta))
plt.text(0.78, 0.15, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=16, bbox=props)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.tight_layout()
plt.show()
print("specs:")
print(F_low_exp)
print(F_high_exp)
print(max(w_delta))
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr = 10
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='Input1', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency", fontsize=16)
plt.ylabel("Amplitude of FFT", fontsize=16)
plt.title("Logic Gate Response - input = 11", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
myText = 'Gain='+"{:.3f}".format(gain1)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='Input1', linestyle='solid')
plt.plot(x_in2, color='blue', label='Input2', linestyle='dotted')
plt.plot(x_out-np.mean(x_out, axis=0), color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps", fontsize=16)
plt.ylabel("Displacement", fontsize=16)
plt.title("Logic Gate Response - input = 11", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='Input1', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency", fontsize=16)
plt.ylabel("Amplitude of FFT", fontsize=16)
plt.title("Logic Gate Response - input = 10", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
myText = 'Gain='+"{:.3f}".format(gain2)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='Input1', linestyle='solid')
plt.plot(x_in2, color='blue', label='Input2', linestyle='dotted')
plt.plot(x_out-np.mean(x_out, axis=0), color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps", fontsize=16)
plt.ylabel("Displacement", fontsize=16)
plt.title("Logic Gate Response - input = 10", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='Input1', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency", fontsize=16)
plt.ylabel("Amplitude of FFT", fontsize=16)
plt.title("Logic Gate Response - input = 01", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
myText = 'Gain='+"{:.3f}".format(gain3)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='Input1', linestyle='solid')
plt.plot(x_in2, color='blue', label='Input2', linestyle='dotted')
plt.plot(x_out-np.mean(x_out, axis=0), color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps", fontsize=16)
plt.ylabel("Displacement", fontsize=16)
plt.title("Logic Gate Response - input = 01", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
print("gain1:")
print(gain1)
print("gain2:")
print(gain2)
print("gain3:")
print(gain3)
XOR = (gain2+gain3)/(2*gain1)
return XOR
def plotInOut_adder(indices):
#%% Initial Configuration
k1 = 1.
k2 = 10.
m1 = 1
m2 = 10
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr1 = 7
Freq_Vibr2 = 10
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK_Freqs(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr1, Freq_Vibr2, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='A', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='B', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='C/S', linestyle='dashed')
plt.xlabel("Frequency", fontsize=16)
plt.ylabel("Amplitude of FFT", fontsize=16)
plt.title("Logic Gate Response - input = 11", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
#myText = 'Gain='+"{:.3f}".format(gain1)
#plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2_Freqs(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr1, Freq_Vibr2, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
print(np.mean(x_out, axis=0))
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='A', linestyle='solid')
plt.plot(x_in2, color='blue', label='B', linestyle='dotted')
plt.plot(x_out, color='red', label='C/S', linestyle='solid')
plt.xlabel("Time Steps", fontsize=16)
plt.ylabel("Displacement", fontsize=16)
plt.title("Logic Gate Response - input = 11", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
B=1
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK_Freqs(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr1, Freq_Vibr2, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='A', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='B', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='C/S', linestyle='dashed')
plt.xlabel("Frequency", fontsize=16)
plt.ylabel("Amplitude of FFT", fontsize=16)
plt.title("Logic Gate Response - input = 10", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
#myText = 'Gain='+"{:.3f}".format(gain2)
#plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2_Freqs(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr1, Freq_Vibr2, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='A', linestyle='solid')
plt.plot(x_in2, color='blue', label='B', linestyle='dotted')
plt.plot(x_out-np.mean(x_out, axis=0), color='red', label='C/S', linestyle='solid')
plt.xlabel("Time Steps", fontsize=16)
plt.ylabel("Displacement", fontsize=16)
plt.title("Logic Gate Response - input = 10", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK_Freqs(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr1, Freq_Vibr2, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='A', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='B', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='C/S', linestyle='dashed')
plt.xlabel("Frequency", fontsize=16)
plt.ylabel("Amplitude of FFT", fontsize=16)
plt.title("Logic Gate Response - input = 01", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
#myText = 'Gain='+"{:.3f}".format(gain3)
#plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2_Freqs(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr1, Freq_Vibr2, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='A', linestyle='solid')
plt.plot(x_in2, color='blue', label='B', linestyle='dotted')
plt.plot(x_out-np.mean(x_out, axis=0), color='red', label='C/S', linestyle='solid')
plt.xlabel("Time Steps", fontsize=16)
plt.ylabel("Displacement", fontsize=16)
plt.title("Logic Gate Response - input = 01", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
return 0
#cleaning up the data files
#try:
# os.remove("indices.pickle")
#except OSError:
# pass
#try:
# os.remove("outputs.pickle")
#except OSError:
# pass
# deap setup:
random.seed(a=42)
creator.create("FitnessMax", base.Fitness, weights=(1.0, 1.0))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 30)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", evaluate)
toolbox.register("mate", tools.cxOnePoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selNSGA2)
# parallelization?
#toolbox.register("map", futures.map)
stats = tools.Statistics(key=lambda ind: ind.fitness.values)
stats.register("avg", np.mean, axis=0)
stats.register("std", np.std, axis=0)
stats.register("min", np.min, axis=0)
stats.register("max", np.max, axis=0)
toolbox.pop_size = 50
toolbox.max_gen = 250
toolbox.mut_prob = 0.8
logbook = tools.Logbook()
logbook.header = ["gen", "evals"] + stats.fields
hof = tools.HallOfFame(1, similar=np.array_equal) #can change the size
# load the results from the files
res = pickle.load(open('results.pickle', 'rb'))
hof = pickle.load(open('hofs.pickle', 'rb'))
log = pickle.load(open('logs.pickle', 'rb'))
# evaluate and plot an individual
#[0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0]
#showPacking([0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0])
#plotInOut_and([0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0])
#plotInOut_xor([0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0])
plotInOut_adder([0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0])
# plot average fitness vs generations
avg = log.select("avg")
std = log.select("std")
max_ = log.select("max")
min_ = log.select("min")
avg_stack = np.stack(avg, axis=0)
avg_f1 = avg_stack[:, 0]
avg_f2 = avg_stack[:, 1]
std_stack = np.stack(std, axis=0)
std_f1 = std_stack[:, 0]
std_f2 = std_stack[:, 1]
max_stack = np.stack(max_, axis=0)
max_f1 = max_stack[:, 0]
max_f2 = max_stack[:, 1]
min_stack = np.stack(min_, axis=0)
min_f1 = min_stack[:, 0]
min_f2 = min_stack[:, 1]
plt.figure(figsize=(6.4,4.8))
plt.plot(avg_f1, color='blue', label='Average', linestyle='solid')
plt.plot(max_f1, color='red', label='Maximum', linestyle='dashed')
plt.plot(min_f1, color='green', label='Minimum', linestyle='dashed')
plt.fill_between(list(range(0, toolbox.max_gen+1)), avg_f1-std_f1, avg_f1+std_f1, color='cornflowerblue', alpha=0.2, linestyle='dotted', label='STD')
plt.xlabel("Generations", fontsize=16)
plt.ylabel("Fitness", fontsize=16)
plt.title("Multi-objective Optimization, Fitness 1 = AND-ness", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper left', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
plt.figure(figsize=(6.4,4.8))
plt.plot(avg_f2, color='blue', label='Average', linestyle='solid')
plt.plot(max_f2, color='red', label='Maximum', linestyle='dashed')
plt.plot(min_f2, color='green', label='Minimum', linestyle='dashed')
plt.fill_between(list(range(0, toolbox.max_gen+1)), avg_f2-std_f2, avg_f2+std_f2, color='cornflowerblue', alpha=0.2, linestyle='dotted', label='STD')
plt.xlabel("Generations", fontsize=16)
plt.ylabel("Fitness", fontsize=16)
plt.title("Multi-objective Optimization, Fitness 2 = XOR-ness", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper left', fontsize=16)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
# print info for best solution found:
#print("-----")
#print(len(hof))
#best = hof.items[0]
#print("-- Best Individual = ", best)
#print("-- Best Fitness = ", best.fitness.values)
# print hall of fame members info:
#print("- Best solutions are:")
# for i in range(HALL_OF_FAME_SIZE):
# print(i, ": ", hof.items[i].fitness.values[0], " -> ", hof.items[i])
#print("Hall of Fame Individuals = ", *hof.items, sep="\n")
# get the pareto front from the results
fronts = tools.emo.sortLogNondominated(res, len(res))
# print(fronts[0][0]) # 50 indvs in fronts[0]
# plot the pareto front
plt.figure(figsize=(4,4))
counter = 1
outputs = []
indices = []
for i,inds in enumerate(fronts):
for ind in inds:
indices.append(ind)
print(str(counter)+': '+str(ind))
output = toolbox.evaluate(ind)
outputs.append(output)
print(output)
plt.scatter(x=output[0], y=output[1], color='blue')
plt.annotate(str(counter), (output[0]+0.1, output[1]+0.1))
counter = counter + 1
plt.xlabel('$f_1(\mathbf{x})$'+' = AND-ness', fontsize=16)
plt.ylabel('$f_2(\mathbf{x})$'+' = XOR-ness', fontsize=16)
plt.title("Pareto Front", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
pickle.dump(indices, open('indices.pickle', 'wb'))
pickle.dump(outputs, open('outputs.pickle', 'wb'))
# plot the pareto front again without annotation
plt.figure(figsize=(4,4))
for output in outputs:
plt.scatter(x=output[0], y=output[1], color='blue')
plt.xlabel('$f_1(\mathbf{x})$'+' = AND-ness', fontsize=16)
plt.ylabel('$f_2(\mathbf{x})$'+' = XOR-ness', fontsize=16)
plt.title("Pareto Front", fontsize=16)
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.tight_layout()
plt.show()
#seaborn.set(style='whitegrid')
#plot_colors = seaborn.color_palette("Set1", n_colors=10)
#fig, ax = plt.subplots(1, figsize=(4,4))
#for i,inds in enumerate(fronts):
# par = [toolbox.evaluate(ind) for ind in inds]
# print("fronts:")
# print(par)
# df = pd.DataFrame(par)
# df.plot(ax=ax, kind='scatter',
# x=df.columns[0], y=df.columns[1],
# color=plot_colors[i])
#plt.xlabel('$f_1(\mathbf{x})$');plt.ylabel('$f_2(\mathbf{x})$');
#plt.title("Pareto Front", fontsize='small')
#plt.show()
# simulate and plot all of the fronts
#for i,inds in enumerate(fronts):
# counter = 0
# for ind in inds:
# counter += 1
# if counter == 1 or counter == 15 or counter==30:
# print("####")
# plotInOut_and(ind)
# plotInOut_xor(ind)
| 51,850 | 38.281061 | 267 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/switch_binary.py
|
import numpy as np
from ConfigPlot import ConfigPlot_EigenMode_DiffMass, ConfigPlot_YFixed_rec, ConfigPlot_DiffMass_SP
from MD_functions import MD_VibrSP_ConstV_Yfixed_DiffK
from MD_functions import FIRE_YFixed_ConstV_DiffK
from DynamicalMatrix import DM_mass_DiffK_Yfixed
from plot_functions import Line_single, Line_multi
from ConfigPlot import ConfigPlot_DiffStiffness
import random
import matplotlib.pyplot as plt
import pickle
from os.path import exists
class switch():
def evaluate(m1, m2, N_light, indices):
#%% Initial Configuration
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# calculating the bandgap - no need to do this in this problem
#w, v = DM_mass_DiffK_Yfixed(N, x_ini, y_ini, D, mass, Lx, 0.0, Ly, k_list, k_type)
#w = np.real(w)
#v = np.real(v)
#freq = np.sqrt(np.absolute(w))
#ind_sort = np.argsort(freq)
#freq = freq[ind_sort]
#v = v[:, ind_sort]
#ind = freq > 1e-4
#eigen_freq = freq[ind]
#eigen_mode = v[:, ind]
#w_delta = eigen_freq[1:] - eigen_freq[0:-1]
#index = np.argmax(w_delta)
#F_low_exp = eigen_freq[index]
#F_high_exp = eigen_freq[index+1]
#print("specs:")
#print(F_low_exp)
#print(F_high_exp)
#print(max(w_delta))
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr = 7
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
andness = 2*gain1/(gain2+gain3)
return andness
def showPacking(m1, m2, N_light, indices):
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# show packing
ConfigPlot_DiffStiffness(N, x0, y0, D, [Lx,Ly], k_type, 0, '/Users/atoosa/Desktop/results/packing.pdf')
def evaluateAndPlot(m1, m2, N_light, indices):
#%% Initial Configuration
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# calculating the bandgap - no need to do this in this problem
w, v = DM_mass_DiffK_Yfixed(N, x_ini, y_ini, D, mass, Lx, 0.0, Ly, k_list, k_type)
w = np.real(w)
v = np.real(v)
freq = np.sqrt(np.absolute(w))
ind_sort = np.argsort(freq)
freq = freq[ind_sort]
v = v[:, ind_sort]
ind = freq > 1e-4
eigen_freq = freq[ind]
eigen_mode = v[:, ind]
w_delta = eigen_freq[1:] - eigen_freq[0:-1]
index = np.argmax(w_delta)
F_low_exp = eigen_freq[index]
F_high_exp = eigen_freq[index+1]
plt.figure(figsize=(6.4,4.8))
plt.scatter(np.arange(0, len(eigen_freq)), eigen_freq, marker='x', color='blue')
plt.xlabel("Number")
plt.ylabel("Frequency")
plt.title("Vibrational Reponse", fontsize='small')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.tight_layout()
plt.show()
print("specs:")
print(F_low_exp)
print(F_high_exp)
print(max(w_delta))
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr = 7
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
print("gain1:")
print(gain1)
print("gain2:")
print(gain2)
print("gain3:")
print(gain3)
andness = 2*gain1/(gain2+gain3)
return andness
| 14,736 | 36.594388 | 252 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/MD_functions.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 13 13:09:27 2017
@author: Hightoutou
"""
import numpy as np
import time
#from numba import jit
from FFT_functions import FFT_Fup, FFT_vCorr
from plot_functions import Line_multi, Line_yy, Line_single
from ConfigPlot import ConfigPlot_YFixed_rec
import matplotlib.pyplot as plt
#import IPython.core.debugger
#dbg = IPython.core.debugger.Pdb()
#@jit
def force_YFixed(Fx, Fy, N, x, y, D, Lx, y_bot, y_up):
Fup = 0
Fbot = 0
Ep = 0
cont = 0
cont_up = 0
p_now = 0
for nn in np.arange(N):
d_up = y_up-y[nn]
d_bot = y[nn]-y_bot
r_now = 0.5*D[nn]
if d_up<r_now:
F = -(1-d_up/r_now)/(r_now)
Fup -= F
Fy[nn] += F
Ep += (1/2)*(1-d_up/r_now)**2
cont_up += 1
cont += 1
#dbg.set_trace()
if d_bot<r_now:
F = -(1-d_bot/r_now)/(r_now)
Fbot += F
Fy[nn] -= F
Ep += (1/2)*(1-d_bot/r_now)**2
cont += 1
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
dx = x[mm]-x[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, Fup, Fbot, Ep, cont, p_now, cont_up
def force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D, Lx, y_bot, y_up, k_list, k_type, VL_list, VL_counter):
Fup = 0
Fbot = 0
Ep = 0
cont = 0
cont_up = 0
p_now = 0
for nn in np.arange(N):
d_up = y_up - y[nn]
d_bot = y[nn] - y_bot
r_now = 0.5 * D[nn]
if d_up < r_now:
F = -k_list[k_type[nn]] * (1 - d_up / r_now) / (r_now)
Fup -= F
Fy[nn] += F
Ep += 0.5 * k_list[k_type[nn]] * (1 - d_up / r_now)**2
cont_up += 1
cont += 1
#dbg.set_trace()
if d_bot < r_now:
F = -k_list[k_type[nn]] * (1 - d_bot / r_now) / (r_now)
Fbot += F
Fy[nn] -= F
Ep += 0.5 * k_list[k_type[nn]] * (1 - d_bot / r_now)**2
cont += 1
for vl_idx in np.arange(VL_counter):
nn = VL_list[vl_idx][0]
mm = VL_list[vl_idx][1]
dy = y[mm] - y[nn]
Dmn = 0.5 * (D[mm] + D[nn])
if abs(dy) < Dmn:
dx = x[mm] - x[nn]
dx = dx - round(dx / Lx) * Lx
if abs(dx) < Dmn:
dmn = np.sqrt(dx**2 + dy**2)
if dmn < Dmn:
k = k_list[(k_type[nn] ^ k_type[mm]) + np.maximum(k_type[nn], k_type[mm])]
F = -k * (1 - dmn / Dmn) / Dmn / dmn
Fx[nn] += F * dx
Fx[mm] -= F * dx
Fy[nn] += F * dy
Fy[mm] -= F * dy
Ep += 0.5 * k * (1 - dmn / Dmn)**2
cont += 1
p_now += (-F) * (dx**2 + dy**2)
return Fx, Fy, Fup, Fbot, Ep, cont, p_now, cont_up
def force_YFixed_upDS(Fx, Fy, N, x, y, D, Lx, y_bot, y_up, ind_up):
Fup = 0
Fbot = 0
Ep = 0
cont = 0
cont_up = 0
p_now = 0
for nn in np.arange(N):
d_up = y_up-y[nn]
d_bot = y[nn]-y_bot
r_now = 0.5*D[nn]
if ind_up[nn] == 1:
F = -(1-d_up/r_now)/(r_now)
Fup -= F
Fy[nn] += F
Ep += (1/2)*(1-d_up/r_now)**2
#dbg.set_trace()
if d_up<r_now:
cont_up = cont_up+1
cont += 1
if d_bot<r_now:
F = -(1-d_bot/r_now)/(r_now)
Fbot += F
Fy[nn] -= F
Ep += (1/2)*(1-d_bot/r_now)**2
cont += 1
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
dx = x[mm]-x[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, Fup, Fbot, Ep, cont, p_now, cont_up
#@jit
def force_Regular(Fx, Fy, N, x, y, D, Lx, Ly):
Ep = 0
cont = 0
p_now = 0
for nn in np.arange(N):
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
dy = dy-round(dy/Ly)*Ly
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
dx = x[mm]-x[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, Ep, cont, p_now
def MD_UpDownFixed_SD(N, x0, y0, D0, m0, L):
dt = min(D0)/40
Nt = int(1e4)
Ep = np.zeros(Nt)
F_up = np.zeros(Nt)
F_bot = np.zeros(Nt)
F_tot = np.zeros(Nt)
Fup_now = 0
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
#Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
F_up[nt] = Fup_now
F_bot[nt] = Fbot_now
Ep[nt] = Ep_now
vx = np.divide(Fx, m0)
vy = np.divide(Fy, m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
t_end = time.time()
print ("time=%.3e" %(t_end-t_start))
if 1 == 0:
# Plot the amplitide of F
Line_single(range(Nt), F_tot[0:Nt], '-', 't', 'Ftot', 'log', yscale='log')
return x, y
def MD_VibrBot_ForceUp(N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr):
dt = min(D0)/40
Nt = int(5e4)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
#y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))
vx = np.zeros(N)
vy = np.zeros(N)
if 1 == 0:
y_bot = np.zeros(Nt)
vx = np.random.rand(N)
vy = np.random.rand(N)
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
T_set = 1e-6
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now = force_YFixed(Fx, Fy, N, x, y, D0, L[0], y_bot[nt], L[1])
#Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
F_up[nt] = Fup_now
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
freq_now, fft_now = FFT_Fup(Nt, F_up[:Nt], dt, Freq_Vibr)
# Plot the amplitide of F
if 1 == 1:
Line_yy([dt*range(Nt), dt*range(Nt)], [F_up[0:Nt],y_bot[0:Nt]], ['-', ':'], 't', ['$F_{up}$', '$y_{bottom}$'])
Etot = Ep[1:Nt]+Ek[1:Nt]
xdata = [dt*range(Nt), dt*range(Nt), dt*range(Nt-1)]
ydata = [Ep[0:Nt], Ek[0:Nt], Etot]
line_spec = ['--', ':', 'r-']
Line_multi(xdata, ydata, line_spec, 't', '$E$', 'log')
print("std(Etot)=%e\n" %(np.std(Etot)))
#dt2 = 1e-3
#xx = np.arange(0, 5, dt2)
#yy = np.sin(50*xx)+np.sin(125*xx)
#print("dt=%e, w=%f\n" % (dt, Freq_Vibr))
FFT_Fup(Nt, F_up[:Nt], dt, Freq_Vibr)
#FFT_Fup(yy.size, yy, dt2, 50)
return freq_now, fft_now, np.mean(cont)
def MD_Periodic_equi(Nt, N, x0, y0, D0, m0, L, T_set, V_em, n_em):
dt = min(D0)/40
Nt = int(Nt)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
vx_rec = np.zeros([Nt, N])
vy_rec = np.zeros([Nt, N])
vx = np.zeros(N)
vy = np.zeros(N)
for ii in np.arange(n_em):
#for ii in [60]:
ind1 = 2*np.arange(N)
ind2 = ind1+1
vx += V_em[ind1, ii]
vy += V_em[ind2, ii]
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx_rec[nt] = vx
vy_rec[nt] = vy
t_end = time.time()
print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f\n" %(CB_ratio))
#Etot = Ep[1:Nt]+Ek[1:Nt]
#xdata = [dt*range(Nt), dt*range(Nt), dt*range(Nt-1)]
#ydata = [Ep[0:Nt], Ek[0:Nt], Etot]
#line_spec = ['--', ':', 'r-']
#Line_multi(xdata, ydata, line_spec, 't', '$E$', 'log', 'log')
freq_now, fft_now = FFT_vCorr(Nt, N, vx_rec, vy_rec, dt)
return freq_now, fft_now, np.mean(cont)
def MD_YFixed_ConstP_SD(Nt, N, x0, y0, D0, m0, L, F0_up):
dt = D0[0]/40
Nt = int(Nt)
#Nt = int(5e6)
#Nt = int(5e2)
Ep = np.zeros(Nt)
F_up = np.zeros(Nt)
F_bot = np.zeros(Nt)
F_tot = np.zeros(Nt)
Fup_now = 0
y_up = y0[N]
vx = np.zeros(N+1)
vy = np.zeros(N+1)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], 0, y[N])
F_up[nt] = Fup_now+F0_up
F_bot[nt] = Fbot_now
Ep[nt] = Ep_now+(y_up-y[N])*F0_up
vx = 0.1*np.divide(np.append(Fx,0), m0)
vy = 0.1*np.divide(np.append(Fy, F_up[nt]), m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
#print("nt=%d, Fup=%e, Fup_tot=%e\n" % (nt, Fup_now, F_up[nt]))
#dbg.set_trace()
t_end = time.time()
print ("F_tot=%.3e\n" %(F_tot[nt]))
print ("time=%.3e" %(t_end-t_start))
if 1 == 0:
# Plot the amplitide of F
Line_single(range(Nt), F_tot[0:Nt], '-', 't', 'Ftot', 'log', yscale='log')
#Line_single(range(Nt), -F_up[0:Nt], '-', 't', 'Fup', 'log', yscale='log')
#Line_single(range(Nt), Ep[0:Nt], '-', 't', 'Ep', 'log', yscale='linear')
return x, y, p_now
def MD_VibrBot_DispUp_ConstP(mark_upDS, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, F0_up):
dt = D0[0]/40
B = 0.1 # damping coefficient
Nt = int(5e7)
#Nt = int(5e2)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
y_up0 = y_ini[N]
y_up = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
cont_up = np.zeros(Nt)
p = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
#y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))
vx = np.zeros(N+1)
vy = np.zeros(N+1)
# for test
if 1 == 0:
y_bot = np.zeros(Nt)
vx = np.random.rand(N+1)
vx[N] = 0
vy = np.random.rand(N+1)
vy[N] = 0
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
T_set = 1e-6
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N+1)
ay_old = np.zeros(N+1)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
if mark_upDS == 1:
ind_up = np.zeros(N)
for ii in np.arange(N):
d_up = y[N]-y[ii]
r_now = 0.5*D0[ii]
if d_up<r_now:
ind_up[ii] = 1
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
y_up[nt] = y[N]
Fx = np.zeros(N)
Fy = np.zeros(N)
if mark_upDS == 0:
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], y_bot[nt], y[N])
elif mark_upDS == 1:
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed_upDS(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], y_bot[nt], y[N], ind_up)
F_up[nt] = Fup_now+F0_up
Ep[nt] = Ep_now+(y_up0-y[N])*F0_up
cont[nt] = cont_now
cont_up[nt] = cont_up_now
p[nt] = p_now
Fx_all = np.append(Fx,0)-B*vx
Fy_all = np.append(Fy, F_up[nt])-B*vy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
y_up = y_up-y_up0
freq_y, fft_y = FFT_Fup(int(Nt/2), y_up[int(Nt/2):Nt], dt, Freq_Vibr)
#freq_y, fft_y_real, fft_y_imag = FFT_Fup_RealImag(int(Nt/2), y_up[int(Nt/2):Nt], dt, Freq_Vibr)
freq_bot, fft_bot = FFT_Fup(int(Nt/2), y_bot[int(Nt/2):Nt], dt, Freq_Vibr)
# plot the energy to see when the system reaches steady state
if 1 == 0:
Etot = Ep+Ek
nt_start = int(1e3)
xdata = [range(nt_start, Nt), range(nt_start, Nt), range(Nt)]
ydata = [Ep[nt_start:Nt], Ek[nt_start:Nt], Etot]
line_spec = [':', ':', 'r-']
Line_multi(xdata, ydata, line_spec, 't', '$E$', 'linear', 'log')
# Plot the amplitide of F
if 1 == 0:
Line_yy([dt*range(Nt), dt*range(Nt)], [F_up[0:Nt],y_bot[0:Nt]], ['-', ':'], 't', ['$F_{up}$', '$y_{bottom}$'])
Line_yy([dt*range(Nt), dt*range(Nt)], [y_up[0:Nt],y_bot[0:Nt]], ['-', ':'], 't', ['$y_{up}$', '$y_{bottom}$'])
Line_single(range(Nt), p[0:Nt], '-', 't', 'p', 'log', 'linear')
Etot = Ep[1:Nt]+Ek[1:Nt]
xdata = [dt*range(Nt), dt*range(Nt), dt*range(Nt-1)]
ydata = [Ep[0:Nt], Ek[0:Nt], Etot]
line_spec = ['--', ':', 'r-']
#Line_multi(xdata, ydata, line_spec, 't', '$E$', 'log')
print("std(Etot)=%e\n" %(np.std(Etot)))
return freq_y, fft_y, freq_bot, fft_bot, np.mean(cont), np.mean(cont_up)
#return freq_y, fft_y_real, fft_y_imag, freq_bot, fft_bot, np.mean(cont)
def MD_VibrBot_DispUp_ConstP_ConfigRec(N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, F0_up, fn):
dt = D0[0]/40
B = 0.1 # damping coefficient
Nt = int(5e6)
nt_rec = np.linspace(Nt-5e4, Nt, 500)
#Nt = int(1e4)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
ind_nt = 0
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
y_up0 = y_ini[N]
y_up = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
cont_up = np.zeros(Nt)
p = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
#y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))
vx = np.zeros(N+1)
vy = np.zeros(N+1)
ax_old = np.zeros(N+1)
ay_old = np.zeros(N+1)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
if nt == nt_rec[ind_nt]:
ConfigPlot_YFixed_rec(N, x[0:N], y[0:N], D0[0:N], L[0], y[N], y_bot[nt], m0[0:N], ind_nt, fn)
ind_nt += 1
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
y_up[nt] = y[N]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], y_bot[nt], y[N])
F_up[nt] = Fup_now+F0_up
Ep[nt] = Ep_now+(y_up0-y[N])*F0_up
cont[nt] = cont_now
cont_up[nt] = cont_up_now
p[nt] = p_now
Fx_all = np.append(Fx,0)-B*vx
Fy_all = np.append(Fy, F_up[nt])-B*vy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
y_up = y_up-y_up0
freq_y, fft_y = FFT_Fup(int(Nt/2), y_up[int(Nt/2):Nt], dt, Freq_Vibr)
freq_bot, fft_bot = FFT_Fup(int(Nt/2), y_bot[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_y, fft_y, freq_bot, fft_bot, np.mean(cont), np.mean(cont_up)
def MD_VibrBot_DispUp_ConstP_EkCheck(Nt, mark_upDS, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, F0_up):
dt = D0[0]/40
B = 0.1 # damping coefficient
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
Ek_now = np.array(0)
Ek_up_now = np.array(0)
Ep_now = np.array(0)
Ep_up_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ep_up = np.zeros(Nt)
Ek = np.zeros(Nt)
Ek_up = np.zeros(Nt)
y_up0 = y_ini[N]
y_up = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
cont_up = np.zeros(Nt)
p = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vx = np.zeros(N+1)
vy = np.zeros(N+1)
ax_old = np.zeros(N+1)
ay_old = np.zeros(N+1)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
if mark_upDS == 1:
ind_up = np.zeros(N)
for ii in np.arange(N):
d_up = y[N]-y[ii]
r_now = 0.5*D0[ii]
if d_up<r_now:
ind_up[ii] = 1
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
y_up[nt] = y[N]
Fx = np.zeros(N)
Fy = np.zeros(N)
if mark_upDS == 0:
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], y_bot[nt], y[N])
elif mark_upDS == 1:
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed_upDS(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], y_bot[nt], y[N], ind_up)
F_up[nt] = Fup_now+F0_up
Ep[nt] = Ep_now+(y_up0-y[N])*F0_up
Ep_up[nt] = (y_up0-y[N])*F0_up
cont[nt] = cont_now
cont_up[nt] = cont_up_now
p[nt] = p_now
Fx_all = np.append(Fx,0)-B*vx
Fy_all = np.append(Fy, F_up[nt])-B*vy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_up[nt] = 0.5*m0[N]*(vx[N]**2+vy[N]**2)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ek_up_now = np.append(Ek_up_now, np.mean(Ek_up[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
Ep_up_now = np.append(Ep_up_now, np.mean(Ep_up[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
y_up = y_up-np.mean(y_up)
y_up = y_up/np.mean(np.absolute(y_up))
freq_y, fft_y = FFT_Fup(int(Nt/2), y_up[int(Nt/2):Nt], dt, Freq_Vibr)
freq_bot, fft_bot = FFT_Fup(int(Nt/2), y_bot[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_y, fft_y, freq_bot, fft_bot, np.mean(cont), np.mean(cont_up)
#@jit
def force_YFixed_collision_ConstP(beta, Fx, Fy, N, x, y, vx, vy, D, Lx, y_bot, v_bot, y_up):
Fup = 0
Fbot = 0
Ep = 0
cont = 0
cont_up = 0
p_now = 0
#betta = 1
for nn in np.arange(N):
d_up = y_up-y[nn]
d_bot = y[nn]-y_bot
r_now = 0.5*D[nn]
if d_up<r_now:
F = -(1-d_up/r_now)/(r_now)
Fup -= F
Fy[nn] += F
dvy = vy[N]-vy[nn]
FD = beta*dvy
#FD = np.absolute(FD)
Fy[nn] += FD
Fup -= FD
Ep += (1/2)*(1-d_up/r_now)**2
cont_up += 1
cont += 1
#dbg.set_trace()
if d_bot<r_now:
F = -(1-d_bot/r_now)/(r_now)
Fbot += F
Fy[nn] -= F
dvy = v_bot-vy[nn]
FD = beta*dvy
Fy[nn] += FD
Ep += (1/2)*(1-d_bot/r_now)**2
cont += 1
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
dx = x[mm]-x[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
dvx = vx[mm]-vx[nn]
dvy = vy[mm]-vy[nn]
FD = beta*(dvx*dx+dvy*dy)/dmn
#FD = np.absolute(FD)
Fx[nn] += FD*dx/dmn
Fx[mm] -= FD*dx/dmn
Fy[nn] += FD*dy/dmn
Fy[mm] -= FD*dy/dmn
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, Fup, Fbot, Ep, cont, p_now, cont_up
def MD_VibrBot_DispUp_ConstP_EkCheck_Collision(beta, Nt, mark_upDS, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, F0_up, mark_norm):
dt = D0[0]/40
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
Ek_now = np.array(0)
Ek_up_now = np.array(0)
Ep_now = np.array(0)
Ep_up_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ep_up = np.zeros(Nt)
Ek = np.zeros(Nt)
Ek_up = np.zeros(Nt)
y_up0 = y_ini[N]
y_up = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
cont_up = np.zeros(Nt)
p = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vy_bot = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)
vx = np.zeros(N+1)
vy = np.zeros(N+1)
ax_old = np.zeros(N+1)
ay_old = np.zeros(N+1)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
if mark_upDS == 1:
ind_up = np.zeros(N)
for ii in np.arange(N):
d_up = y[N]-y[ii]
r_now = 0.5*D0[ii]
if d_up<r_now:
ind_up[ii] = 1
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
y_up[nt] = y[N]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed_collision_ConstP(beta, Fx, Fy, N, x, y, vx, vy, D0[0:N], L[0], y_bot[nt], vy_bot[nt], y[N])
F_up[nt] = Fup_now+F0_up
Ep[nt] = Ep_now+(y_up0-y[N])*F0_up
Ep_up[nt] = (y_up0-y[N])*F0_up
cont[nt] = cont_now
cont_up[nt] = cont_up_now
p[nt] = p_now
Fx_all = np.append(Fx,0)
Fy_all = np.append(Fy, F_up[nt])
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_up[nt] = 0.5*m0[N]*(vx[N]**2+vy[N]**2)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ek_up_now = np.append(Ek_up_now, np.mean(Ek_up[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
Ep_up_now = np.append(Ep_up_now, np.mean(Ep_up[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
y_up = y_up-np.mean(y_up)
if mark_norm == 1:
y_up = y_up/np.mean(np.absolute(y_up))
freq_y, fft_y = FFT_Fup(int(Nt/2), y_up[int(Nt/2):Nt], dt, Freq_Vibr)
freq_bot, fft_bot = FFT_Fup(int(Nt/2), y_bot[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_y, fft_y, fft_bot, np.mean(cont), np.mean(cont_up), nt_rec[1:], Ek_now[1:],Ek_up_now[1:],Ep_now[1:],Ep_up_now[1:]
def MD_YFixed_ConstP_Gravity_SD(N, x0, y0, D0, m0, L, F0_up):
g = 1e-5
dt = D0[0]/40
Nt = int(5e6)
#Nt = int(1e4)
Ep = np.zeros(Nt)
F_up = np.zeros(Nt)
F_bot = np.zeros(Nt)
F_tot = np.zeros(Nt)
Fup_now = 0
y_up = y0[N]
vx = np.zeros(N+1)
vy = np.zeros(N+1)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], 0, y[N])
Fy -= g*m0[0:N]
F_up[nt] = Fup_now+F0_up-g*m0[N]
F_bot[nt] = Fbot_now
Ep[nt] = Ep_now+(y_up-y[N])*F0_up+sum(g*np.multiply(m0, y-y0))
vx = 0.1*np.divide(np.append(Fx,0), m0)
vy = 0.1*np.divide(np.append(Fy, F_up[nt]), m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
#print("nt=%d, Fup=%e, Fup_tot=%e\n" % (nt, Fup_now, F_up[nt]))
#dbg.set_trace()
t_end = time.time()
print ("F_tot=%.3e\n" %(F_tot[nt]))
print ("time=%.3e" %(t_end-t_start))
return x, y, p_now
def MD_VibrBot_DispUp_ConstP_EkCheck_Gravity(Nt, mark_upDS, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, F0_up):
dt = D0[0]/40
#B = 0.1 # damping coefficient
g = 1e-5
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
Ek_now = np.array(0)
Ek_up_now = np.array(0)
Ep_now = np.array(0)
Ep_up_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ep_up = np.zeros(Nt)
Ek = np.zeros(Nt)
Ek_up = np.zeros(Nt)
y_up0 = y_ini[N]
y_up = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
cont_up = np.zeros(Nt)
p = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vy_bot = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)
vx = np.zeros(N+1)
vy = np.zeros(N+1)
ax_old = np.zeros(N+1)
ay_old = np.zeros(N+1)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
if mark_upDS == 1:
ind_up = np.zeros(N)
for ii in np.arange(N):
d_up = y[N]-y[ii]
r_now = 0.5*D0[ii]
if d_up<r_now:
ind_up[ii] = 1
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
y_up[nt] = y[N]
Fx = np.zeros(N)
Fy = np.zeros(N)
#Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], y_bot[nt], y[N])
beta = 1
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed_collision_ConstP(beta, Fx, Fy, N, x, y, vx, vy, D0[0:N], L[0], y_bot[nt], vy_bot[nt], y[N])
F_up[nt] = Fup_now+F0_up
Ep[nt] = Ep_now+(y_up0-y[N])*F0_up+sum(g*np.multiply(m0, y-y_ini))
Ep_up[nt] = (y_up0-y[N])*F0_up
cont[nt] = cont_now
cont_up[nt] = cont_up_now
p[nt] = p_now
#Fx_all = np.append(Fx,0)-B*vx
#Fy_all = np.append(Fy, F_up[nt])-B*vy-g*m0
Fx_all = np.append(Fx,0)
Fy_all = np.append(Fy, F_up[nt])-g*m0
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_up[nt] = 0.5*m0[N]*(vx[N]**2+vy[N]**2)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ek_up_now = np.append(Ek_up_now, np.mean(Ek_up[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
Ep_up_now = np.append(Ep_up_now, np.mean(Ep_up[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
y_up = y_up-np.mean(y_up)
#y_up = y_up/np.mean(np.absolute(y_up))
freq_y, fft_y = FFT_Fup(int(Nt/2), y_up[int(Nt/2):Nt], dt, Freq_Vibr)
freq_bot, fft_bot = FFT_Fup(int(Nt/2), y_bot[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_y, fft_y, fft_bot, np.mean(cont), np.mean(cont_up), nt_rec[1:], Ek_now[1:],Ek_up_now[1:],Ep_now[1:],Ep_up_now[1:]
def MD_YFixed_ConstV_SP_SD(Nt, N, x0, y0, D0, m0, Lx, Ly):
dt = D0[0]/40
Nt = int(Nt)
Ep = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Ep[nt] = Ep_now
vx = 0.1*np.divide(Fx, m0)
vy = 0.1*np.divide(Fy, m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
t_end = time.time()
print ("F_tot=%.3e" %(F_tot[nt]))
print ("time=%.3e" %(t_end-t_start))
plt.figure(figsize=(6.4,4.8))
plt.plot(range(Nt), F_tot[0:Nt], color='blue')
ax = plt.gca()
ax.set_yscale('log')
plt.xlabel("t")
plt.ylabel("F_total")
plt.title("Finding the Equilibrium", fontsize='small')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.tight_layout()
plt.show()
return x, y, p_now
def MD_YFixed_ConstV_SP_SD_2(Nt, N, x0, y0, D0, m0, Lx, Ly):
dt = D0[0]/40
Nt = int(Nt)
Ep = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Ep[nt] = Ep_now
vx = 0.1*np.divide(Fx, m0)
vy = 0.1*np.divide(Fy, m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
# putting a threshold on total force
if (F_tot[nt]<1e-11):
break
t_end = time.time()
#print ("F_tot=%.3e" %(F_tot[nt]))
#print ("time=%.3e" %(t_end-t_start))
return x, y, p_now
#@jit
def force_YFixed_collision_ConstV(beta, Fx, Fy, N, x, y, vx, vy, D, Lx, y_bot, y_up):
Ep = 0
cont = 0
p_now = 0
for nn in np.arange(N):
d_up = y_up-y[nn]
d_bot = y[nn]-y_bot
r_now = 0.5*D[nn]
if d_up<r_now:
F = -(1-d_up/r_now)/(r_now)
Fy[nn] += F
dvy = -vy[nn]
FD = beta*dvy
Fy[nn] += FD
Ep += (1/2)*(1-d_up/r_now)**2
cont += 1
#dbg.set_trace()
if d_bot<r_now:
F = -(1-d_bot/r_now)/(r_now)
Fy[nn] -= F
dvy = -vy[nn]
FD = beta*dvy
Fy[nn] += FD
Ep += (1/2)*(1-d_bot/r_now)**2
cont += 1
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
dx = x[mm]-x[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
dvx = vx[mm]-vx[nn]
dvy = vy[mm]-vy[nn]
FD = beta*(dvx*dx+dvy*dy)/dmn
#FD = np.absolute(FD)
Fx[nn] += FD*dx/dmn
Fx[mm] -= FD*dx/dmn
Fy[nn] += FD*dy/dmn
Fy[mm] -= FD*dy/dmn
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, Ep, cont, p_now
def MD_VibrSP_ConstV_Collision(beta, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, ind_in, ind_out, mark_vibrY):
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in]
vx_in = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt))
elif mark_vibrY == 1:
y_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in]
vy_in = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt))
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 0:
x[ind_in] = x_in[nt]
y[ind_in] = y_ini[ind_in]
vx[ind_in] = vx_in[nt]
vy[ind_in] = 0
elif mark_vibrY == 1:
x[ind_in] = x_ini[ind_in]
y[ind_in] = y_in[nt]
vx[ind_in] = 0
vy[ind_in] = vy_in[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_YFixed_collision_ConstV(beta, Fx, Fy, N, x, y, vx, vy, D0, L[0], 0, L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx
Fy_all = Fy
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = np.array(0)
Ep_now = np.array(0)
cont_now = np.array(0)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now = np.append(cont_now, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
cont_now[0] = cont_now[1]
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
if mark_vibrY == 0:
freq_fft, fft_in = FFT_Fup(int(Nt/2), x_in[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in = FFT_Fup(int(Nt/2), y_in[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_fft, fft_in, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_VibrSP_ConstV(B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, ind_in, ind_out, mark_vibrY, mark_resonator):
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in]
elif mark_vibrY == 1:
y_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in]
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 0:
x[ind_in] = x_in[nt]
y[ind_in] = y_ini[ind_in]
elif mark_vibrY == 1:
x[ind_in] = x_ini[ind_in]
y[ind_in] = y_in[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx-B*vx
Fy_all = Fy-B*vy
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = np.array(0)
Ep_now = np.array(0)
cont_now = np.array(0)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now = np.append(cont_now, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
cont_now[0] = cont_now[1]
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
if mark_vibrY == 0:
freq_fft, fft_in = FFT_Fup(int(Nt/2), x_in[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in = FFT_Fup(int(Nt/2), y_in[int(Nt/2):Nt], dt, Freq_Vibr)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
if Nt == 5e5:
print(x[ind_out], y[ind_out])
print(fft_x_out[100], fft_y_out[100])
print(fft_in[100])
return freq_fft, fft_in, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_Periodic_ConstV_SP_SD(Nt, N, x0, y0, D0, m0, Lx, Ly):
dt = D0[0]/40
Nt = int(Nt)
Ep = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, Lx, Ly)
Ep[nt] = Ep_now
vx = 0.1*np.divide(Fx, m0)
vy = 0.1*np.divide(Fy, m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
t_end = time.time()
print ("F_tot=%.3e\n" %(F_tot[nt]))
print ("nt=%e, time=%.3e" %(nt, t_end-t_start))
return x, y, p_now
def MD_Periodic_equi_Ekcheck(Nt, N, x0, y0, D0, m0, L, T_set, V_em, n_em):
dt = min(D0)/40
Nt = int(Nt)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
vx_rec = np.zeros([Nt, N])
vy_rec = np.zeros([Nt, N])
nt_rec = np.linspace(0, Nt, int(Nt/1e3)+1)
#nt_rec = np.linspace(0, Nt, int(Nt/1e2)+1)
nt_rec = nt_rec.astype(int)
Ek_now = np.array(0)
Ep_now = np.array(0)
vx = np.zeros(N)
vy = np.zeros(N)
for ii in np.arange(n_em):
ind1 = 2*np.arange(N)
ind2 = ind1+1
vx += V_em[ind1, ii]
vy += V_em[ind2, ii]
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx_rec[nt] = vx
vy_rec[nt] = vy
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f\n" %(CB_ratio))
freq_now, fft_now = FFT_vCorr(int(Nt/2), N, vx_rec[int(Nt/2):Nt], vy_rec[int(Nt/2):Nt], dt)
return freq_now, fft_now, np.mean(cont), nt_rec, Ek_now, Ep_now
#@jit
def force_Xfixed(Fx, Fy, N, x, y, D, x_l, x_r, Ly, ind_wall):
F_l = 0
F_r = 0
Ep = 0
cont = 0
p_now = 0
for nn in np.arange(N):
d_l = x[nn]-x_l
d_r = x_r-x[nn]
r_now = 0.5*D[nn]
if (ind_wall[nn]==0) and (d_r<r_now):
F = -(1-d_r/r_now)/(r_now)
F_r -= F
Fx[nn] += F
Ep += (1/2)*(1-d_r/r_now)**2
cont += 1
#dbg.set_trace()
if (ind_wall[nn]==0) and (d_l<r_now):
F = -(1-d_l/r_now)/(r_now)
F_l += F
Fx[nn] -= F
Ep += (1/2)*(1-d_l/r_now)**2
cont += 1
for mm in np.arange(nn+1, N):
dx = x[mm]-x[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dx) < Dmn:
dy = y[mm]-y[nn]
dy = dy-round(dy/Ly)*Ly
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, F_l, F_r, Ep, cont, p_now
def MD_Xfixed_SD(Nt, N, x0, y0, D0, m0, Lx, Ly, ind_wall):
wall = np.where(ind_wall>0)
dt = D0[0]/40
Nt = int(Nt)
#Nt = int(5e6)
#Nt = int(5e2)
Ep = np.zeros(Nt)
F_l = np.zeros(Nt)
F_r = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fl_now, Fr_now, Ep_now, cont_now, p_now = force_Xfixed(Fx, Fy, N, x, y, D0, 0, Lx, Ly, ind_wall)
F_l[nt] = Fl_now
F_r[nt] = Fr_now
Ep[nt] = Ep_now
Fx[wall] = 0
Fy[wall] = 0
vx = 0.1*np.divide(Fx, m0)
vy = 0.1*np.divide(Fy, m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
#print("nt=%d, Fup=%e, Fup_tot=%e\n" % (nt, Fup_now, F_up[nt]))
#dbg.set_trace()
t_end = time.time()
print ("F_tot=%.3e" %(F_tot[nt]))
#print ("Ep_tot=%.3e\n" %(Ep[nt]))
print ("time=%.3e" %(t_end-t_start))
return x, y, p_now
def MD_VibrWall_DiffP_Xfixed(Nt, N, x_ini, y_ini,D0, m0, Lx, Ly, Freq_Vibr, Amp_Vibr, ind_wall, B):
dt = D0[0]/40
# B damping coefficient
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
Ek_now = np.array(0)
Ep_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
x_l = np.zeros(Nt)
F_r = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_l = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
wall_l = np.where(ind_wall==1)
wall_r = np.where(ind_wall==2)
wall = np.where(ind_wall>0)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
x[wall_l] = x_l[nt]
Fx, Fy, Fl_now, Fr_now, Ep_now, cont_now, p_now = force_Xfixed(Fx, Fy, N, x, y, D0, x_l[nt], Lx, Ly, ind_wall)
F_r[nt] = Fr_now+sum(Fx[wall_r])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx-B*vx
Fy_all = Fy-B*vy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax[wall] = 0
ay[wall] = 0
vx[wall] = 0
vy[wall] = 0
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
#for ii in np.arange(len(nt_rec)-1):
# Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
# Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
#CB_ratio = min(cont)/max(cont)
#print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
freq_fft, fft_receive = FFT_Fup(int(Nt/2), F_r[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_drive = FFT_Fup(int(Nt/2), x_l[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_fft, fft_receive, fft_drive, cont_now, nt_rec, Ek_now, Ep_now
#@jit
def force_XFixed_collision_VibrLx(beta, Fx, Fy, N, x, y, vx, vy, D, x_l, Lx, Ly, vx_l, ind_wall):
Fr = 0
Fl = 0
Ep = 0
cont = 0
p_now = 0
#betta = 1
for nn in np.arange(N):
if ind_wall[nn] == 0:
d_r = Lx-x[nn]
d_l = x[nn]-x_l
r_now = 0.5*D[nn]
if d_r<r_now:
F = -(1-d_r/r_now)/(r_now)
Fr -= F
Fx[nn] += F
dvx = -vx[nn]
FD = beta*dvx
Fx[nn] += FD
Fr -= FD
Ep += (1/2)*(1-d_r/r_now)**2
cont += 1
#dbg.set_trace()
if d_l<r_now:
F = -(1-d_l/r_now)/(r_now)
Fl += F
Fx[nn] -= F
dvx = vx_l-vx[nn]
FD = beta*dvx
Fx[nn] += FD
Ep += (1/2)*(1-d_l/r_now)**2
cont += 1
for mm in np.arange(nn+1, N):
dx = x[mm]-x[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dx) < Dmn:
dy = y[mm]-y[nn]
dy = dy-round(dy/Ly)*Ly
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
dvx = vx[mm]-vx[nn]
dvy = vy[mm]-vy[nn]
FD = beta*(dvx*dx+dvy*dy)/dmn
#FD = np.absolute(FD)
Fx[nn] += FD*dx/dmn
Fx[mm] -= FD*dx/dmn
Fy[nn] += FD*dy/dmn
Fy[mm] -= FD*dy/dmn
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, Fl, Fr, Ep, cont, p_now
def MD_VibrWall_DiffP_Xfixed_Collision(Nt, N, x_ini, y_ini,D0, m0, Lx, Ly, Freq_Vibr, Amp_Vibr, ind_wall, beta):
dt = D0[0]/40
# B damping coefficient
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
Ek_now = np.array(0)
Ep_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
x_l = np.zeros(Nt)
F_r = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_l = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vx_l = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)
wall_l = np.where(ind_wall==1)
wall_r = np.where(ind_wall==2)
wall = np.where(ind_wall>0)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
x[wall_l] = x_l[nt]
vx[wall_l] = vx_l[nt]
Fx, Fy, Fl_now, Fr_now, Ep_now, cont_now, p_now = force_XFixed_collision_VibrLx(beta, Fx, Fy, N, x, y, vx, vy, D0, x_l[nt], Lx, Ly, vx_l[nt], ind_wall)
F_r[nt] = Fr_now+sum(Fx[wall_r])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx
Fy_all = Fy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax[wall] = 0
ay[wall] = 0
vx[wall] = 0
vy[wall] = 0
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
freq_fft, fft_receive = FFT_Fup(int(Nt/2), F_r[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_drive = FFT_Fup(int(Nt/2), x_l[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_fft, fft_receive, fft_drive, cont_now, nt_rec, Ek_now, Ep_now
def MD_VibrWall_LySignal_Collision(Nt, N, x_ini, y_ini,D0, m0, Lx0, Ly0, Freq_Vibr, Amp_Vibr, ind_wall, beta, dLy_scheme, num_gap):
dt = D0[0]/40
# B damping coefficient
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
dLy_max = 0.1
nt_transition = int(Nt/num_gap/20)
dLy_inc = np.linspace(0, dLy_max, nt_transition)
dLy_dec = np.linspace(dLy_max, 0, nt_transition)
if dLy_scheme == 0:
dLy_all = np.zeros(Nt)
elif dLy_scheme == 1:
dLy_all = np.ones(Nt)*dLy_max
dLy_all[0:nt_transition] = dLy_inc
elif dLy_scheme == 2:
dLy_all = np.zeros(Nt)
nt_Ly = np.linspace(0, Nt, num_gap+1)
nt_Ly = nt_Ly.astype(int)
for ii in np.arange(1, num_gap):
nt1 = nt_Ly[ii]-int(nt_transition/2)
nt2 = nt_Ly[ii]+int(nt_transition/2)
if ii%2 == 1:
dLy_all[nt_Ly[ii]:nt_Ly[ii+1]] = dLy_max
dLy_all[nt1:nt2] = dLy_inc
else:
dLy_all[nt1:nt2] = dLy_dec
nt_rec = np.linspace(0, Nt, int(Nt/5e4*num_gap/5)+1)
Ek_now = np.array(0)
Ep_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
x_l = np.zeros(Nt)
F_r = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_l = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vx_l = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)
wall_l = np.where(ind_wall==1)
wall_r = np.where(ind_wall==2)
wall = np.where(ind_wall>0)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
for nt in np.arange(Nt):
Ly = Ly0+dLy_all[nt]
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
x[wall_l] = x_l[nt]
vx[wall_l] = vx_l[nt]
Fx, Fy, Fl_now, Fr_now, Ep_now, cont_now, p_now = force_XFixed_collision_VibrLx(beta, Fx, Fy, N, x, y, vx, vy, D0, x_l[nt], Lx0, Ly, vx_l[nt], ind_wall)
F_r[nt] = Fr_now+sum(Fx[wall_r])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx
Fy_all = Fy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax[wall] = 0
ay[wall] = 0
vx[wall] = 0
vy[wall] = 0
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
nt_dLy = np.arange(0, Nt, 100)
return nt_dLy, dLy_all[nt_dLy], F_r, nt_rec, Ek_now, Ep_now
def MD_VibrWall_LySignal(Nt, N, x_ini, y_ini,D0, m0, Lx0, Ly0, Freq_Vibr, Amp_Vibr, ind_wall, B, dLy_scheme, num_gap):
dt = D0[0]/40
# B damping coefficient
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
dLy_max = 0.1
nt_transition = int(Nt/num_gap/20)
dLy_inc = np.linspace(0, dLy_max, nt_transition)
dLy_dec = np.linspace(dLy_max, 0, nt_transition)
if dLy_scheme == 0:
dLy_all = np.zeros(Nt)
elif dLy_scheme == 1:
dLy_all = np.ones(Nt)*dLy_max
dLy_all[0:nt_transition] = dLy_inc
elif dLy_scheme == 2:
dLy_all = np.zeros(Nt)
nt_Ly = np.linspace(0, Nt, num_gap+1)
nt_Ly = nt_Ly.astype(int)
for ii in np.arange(1, num_gap):
nt1 = nt_Ly[ii]-int(nt_transition/2)
nt2 = nt_Ly[ii]+int(nt_transition/2)
if ii%2 == 1:
dLy_all[nt_Ly[ii]:nt_Ly[ii+1]] = dLy_max
dLy_all[nt1:nt2] = dLy_inc
else:
dLy_all[nt1:nt2] = dLy_dec
nt_rec = np.linspace(0, Nt, int(Nt/5e4*num_gap/5)+1)
Ek_now = np.array(0)
Ep_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
x_l = np.zeros(Nt)
F_r = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_l = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vx_l = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)
wall_l = np.where(ind_wall==1)
wall_r = np.where(ind_wall==2)
wall = np.where(ind_wall>0)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
for nt in np.arange(Nt):
Ly = Ly0+dLy_all[nt]
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
x[wall_l] = x_l[nt]
vx[wall_l] = vx_l[nt]
Fx, Fy, Fl_now, Fr_now, Ep_now, cont_now, p_now = force_Xfixed(Fx, Fy, N, x, y, D0, x_l[nt], Lx0, Ly, ind_wall)
F_r[nt] = Fr_now+sum(Fx[wall_r])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx-B*vx
Fy_all = Fy-B*vy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax[wall] = 0
ay[wall] = 0
vx[wall] = 0
vy[wall] = 0
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
nt_dLy = np.arange(0, Nt, 100)
return nt_dLy, dLy_all[nt_dLy], F_r, nt_rec, Ek_now, Ep_now
def MD_VibrBot_FSignal_Collision(beta, Nt, N, x_ini, y_ini, D0, m0, Lx, Freq_Vibr, Amp_Vibr, F_scheme, num_gap):
dt = D0[0]/40
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
F_max = 0.01
F_min = 1e-8
nt_transition = int(Nt/num_gap/20)
F_inc = np.linspace(F_min, F_max, nt_transition)
F_dec = np.linspace(F_max, F_min, nt_transition)
if F_scheme == 1:
F_all = np.ones(Nt)*F_max
elif F_scheme == 0:
F_all = np.ones(Nt)*F_min
F_all[0:nt_transition] = F_dec
elif F_scheme == 2:
F_all = np.ones(Nt)*F_max
nt_F = np.linspace(0, Nt, num_gap+1)
nt_F = nt_F.astype(int)
for ii in np.arange(1, num_gap):
nt1 = nt_F[ii]-int(nt_transition/2)
nt2 = nt_F[ii]+int(nt_transition/2)
if ii%2 == 1:
F_all[nt_F[ii]:nt_F[ii+1]] = F_min
F_all[nt1:nt2] = F_dec
else:
F_all[nt1:nt2] = F_inc
nt_rec = np.linspace(0, Nt, int(Nt/5e4*num_gap/5)+1)
Ek_now = np.array(0)
Ep_now = np.array(0)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
y_up = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vy_bot = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)
vx = np.zeros(N+1)
vy = np.zeros(N+1)
ax_old = np.zeros(N+1)
ay_old = np.zeros(N+1)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
y_up[nt] = y[N]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed_collision_ConstP(beta, Fx, Fy, N, x, y, vx, vy, D0[0:N], Lx, y_bot[nt], vy_bot[nt], y[N])
F_up[nt] = Fup_now-F_all[nt]
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = np.append(Fx,0)
Fy_all = np.append(Fy, F_up[nt])
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek_up = 0.5*m0[N]*(vx[N]**2+vy[N]**2)
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))-Ek_up
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
print ("freq=%f, cont_min=%d, cont_max=%d, cont_ave=%f\n" %(Freq_Vibr, min(cont), max(cont), np.mean(cont)))
nt_F = np.arange(0, Nt, 100)
return nt_F, F_all[nt_F], y_up, nt_rec, Ek_now, Ep_now
def MD_SPSignal(mark_collision, beta, Nt, N, x_ini, y_ini,D0, m0, Lx, Ly, Freq_Vibr, Amp_Vibr, ind_in, ind_out, ind_fix, dr_scheme, num_gap, mark_vibrY, dr_one, dr_two):
dt = D0[0]/40
Nt = int(Nt)
d_ini = D0[0]
d0 = 0.1
dr_all = np.zeros(Nt)+dr_one
if abs(dr_scheme) <= 2:
nt_dr = np.linspace(0, Nt, 3)
nt_dr = nt_dr.astype(int)
dr_all[nt_dr[1]:nt_dr[2]] = dr_two
num_gap = 5
elif dr_scheme == 3 or dr_scheme == 4:
nt_dr = np.linspace(0, Nt, num_gap+1)
nt_dr = nt_dr.astype(int)
for ii in np.arange(1, num_gap, 2):
dr_all[nt_dr[ii]:nt_dr[ii+1]] = dr_two
D_fix = d_ini+dr_all*d_ini
nt_rec = np.linspace(0, Nt, int(Nt/5e4*num_gap/5)+1)
Ek_rec = np.array(0)
Ep_rec = np.array(0)
cont_rec = np.array(0)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 1:
y_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in]
vy_in = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt))
else:
x_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in]
vx_in = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt))
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
D0[ind_fix] = D_fix[nt]
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 1:
y[ind_in] = y_in[nt]
x[ind_in] = x_ini[ind_in]
vy[ind_in] = vy_in[nt]
vx[ind_in] = 0
else:
x[ind_in] = x_in[nt]
y[ind_in] = y_ini[ind_in]
vx[ind_in] = vx_in[nt]
vy[ind_in] = 0
Fx = np.zeros(N)
Fy = np.zeros(N)
if mark_collision == 1:
Fx, Fy, Ep_now, cont_now, p_now = force_YFixed_collision_ConstV(beta, Fx, Fy, N, x, y, vx, vy, D0, Lx, 0, Ly)
Fx_all = Fx
Fy_all = Fy
else:
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Fx_all = Fx-beta*vx
Fy_all = Fy-beta*vy
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if nt % 2000 == 0:
print ("nt = %d, Ek = %.2e, cont = %.2e" %(nt, Ek[nt], cont[nt]))
for ii in np.arange(len(nt_rec)-1):
Ek_rec = np.append(Ek_rec, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec = np.append(Ep_rec, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec = np.append(cont_rec, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
print ("freq=%f, cont_min=%d, cont_max=%d, cont_ave=%f\n" %(Freq_Vibr, min(cont), max(cont), np.mean(cont)))
nt_dr = np.arange(0, Nt, 100)
if mark_vibrY == 1:
xy_out = y_out
else:
xy_out = x_out
return nt_dr, dr_all[nt_dr], xy_out, nt_rec, Ek_rec, Ep_rec, cont_rec
def MD_YFixed_equi_SP_modecheck(Nt, N, x0, y0, D0, m0, Lx, Ly, T_set, V_em, n_em, ind_out):
dt = min(D0)/40
Nt = int(Nt)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = []
Ep_rec = []
cont_rec = []
vx = np.zeros(N)
vy = np.zeros(N)
for ii in np.arange(n_em):
ind1 = 2*np.arange(N)
ind2 = ind1+1
vx += V_em[ind1, ii]
vy += V_em[ind2, ii]
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_rec.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[1:] + nt_rec[:-1]) / 2
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f\n" %(CB_ratio))
Freq_Vibr = 0
freq_x, fft_x = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_y, fft_y = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
ind1 = freq_x<30
ind2 = freq_y<30
return freq_x[ind1], freq_y[ind2], fft_x[ind1], fft_y[ind2], np.mean(cont), nt_rec, Ek_rec, Ep_rec, cont_rec
def MD_YFixed_SPVibr_SP_modecheck(Nt, N, x0, y0, D0, m0, Lx, Ly, T_set, ind_in, ind_out, mark_vibrY):
dt = min(D0)/40
Nt = int(Nt)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = np.array(0)
Ep_rec = np.array(0)
cont_rec = np.array(0)
vx = np.zeros(N)
vy = np.zeros(N)
if mark_vibrY == 1:
vy[ind_in] = 1
vy_mc = sum(np.multiply(vy,m0))/sum(m0)
vy = vy-vy_mc
else:
vx[ind_in] = 1
vx_mc = sum(np.multiply(vx,m0))/sum(m0)
vx = vx-vx_mc
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if mark_vibrY == 1:
vy = vy*np.sqrt(N*T_set/T_rd)
print("|vy|_Max=%.3e, |vy|_Min=%.3e" %(max(abs(vy)), min(abs(vy))))
else:
vx = vx*np.sqrt(N*T_set/T_rd)
print("|vx|_Max=%.3e, |vx|_Min=%.3e" %(max(abs(vx)), min(abs(vx))))
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
mark_CB = 0
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Ep[nt] = Ep_now
cont[nt] = cont_now
if mark_CB == 0 and cont_now<cont[0]:
print("nt_CB=%d" % nt)
mark_CB = 1
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_rec = np.append(Ek_rec, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec = np.append(Ep_rec, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec = np.append(cont_rec, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f\n" %(CB_ratio))
Freq_Vibr = 0
freq_x, fft_x = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_y, fft_y = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
ind1 = freq_x<30
ind2 = freq_y<30
return freq_x[ind1], freq_y[ind2], fft_x[ind1], fft_y[ind2], cont_rec, nt_rec, Ek_rec, Ep_rec
#181105
def MD_YFixed_SPVibr_vCorr_modecheck(Nt_MD, Nt_FFT, N, x0, y0, D0, m0, Lx, Ly, T_set, ind_in, ind_out, mark_vibrY):
N = int(N)
Nt_FFT = int(Nt_FFT)
Nt_MD = int(Nt_MD)
dt = min(D0)/40
Nt = Nt_MD+Nt_FFT
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
mark_FFT = np.zeros(Nt)
mark_FFT[Nt_MD:Nt] = 1
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = []
Ep_rec = []
cont_rec = []
vx = np.zeros(N)
vy = np.zeros(N)
if mark_vibrY == 1:
vy[ind_in] = 1
vy_mc = sum(np.multiply(vy,m0))/sum(m0)
vy = vy-vy_mc
else:
vx[ind_in] = 1
vx_mc = sum(np.multiply(vx,m0))/sum(m0)
vx = vx-vx_mc
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if mark_vibrY == 1:
vy = vy*np.sqrt(N*T_set/T_rd)
print("|vy|_Max=%.3e, |vy|_Min=%.3e" %(max(abs(vy)), min(abs(vy))))
else:
vx = vx*np.sqrt(N*T_set/T_rd)
print("|vx|_Max=%.3e, |vx|_Min=%.3e" %(max(abs(vx)), min(abs(vx))))
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if mark_FFT[nt] == 1:
if mark_FFT[nt-1] == 0:
nt_ref = nt
vx_rec = np.zeros([Nt_FFT, N])
vy_rec = np.zeros([Nt_FFT, N])
nt_delta = nt-nt_ref
vx_rec[nt_delta] = vx
vy_rec[nt_delta] = vy
if nt_delta == Nt_FFT-1:
freq_now, fft_now = FFT_vCorr(Nt_FFT, N, vx_rec, vy_rec, dt)
print ("Nt_End="+str(nt))
for ii in np.arange(len(nt_rec)-1):
Ek_rec.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f" %(CB_ratio))
return freq_now, fft_now, (nt_rec[:-1]+nt_rec[1:])/2, Ek_rec, Ep_rec, cont_rec
def MD_YFixed_ConstV(B, Nt, N, x0, y0, D0, m0, Lx, Ly):
dt = min(D0)/40
Nt = int(Nt)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/1e3)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = []
Ep_rec = []
cont_rec = []
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
mark_CB = 0
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Fx = Fx-B*vx
Fy = Fy-B*vy
Ep[nt] = Ep_now
cont[nt] = cont_now
if mark_CB == 0 and cont_now<cont[0]:
print("nt_CB=%d" % nt)
mark_CB = 1
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_rec.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[0:-1]+nt_rec[1:])/2
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f\n" %(CB_ratio))
print ("Ek_last=%.3e" % Ek[-1])
return x, y, nt_rec, Ek_rec, Ep_rec, cont_rec
def MD_Vibr3Part_ConstV(B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, ind_in_all, ind_out, mark_vibrY, eigen_mode_now):
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
num_in = ind_in_all.size
Phase_Vibr = np.sin(Freq_Vibr*dt*np.arange(Nt))
Amp_Vibr_all = np.zeros(num_in)
for i_in in np.arange(num_in):
ind_in = ind_in_all[i_in]
if mark_vibrY == 0:
Amp_Vibr_all[i_in] = eigen_mode_now[2*ind_in]
elif mark_vibrY == 1:
Amp_Vibr_all[i_in] = eigen_mode_now[2*ind_in+1]
print(ind_in_all)
print(Amp_Vibr_all)
Amp_Vibr_all = Amp_Vibr_all*Amp_Vibr/max(np.abs(Amp_Vibr_all))
print(Amp_Vibr_all)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
for i_in in np.arange(num_in):
ind_in = ind_in_all[i_in]
if mark_vibrY == 0:
x[ind_in] = Phase_Vibr[nt]*Amp_Vibr_all[i_in]+x_ini[ind_in]
y[ind_in] = y_ini[ind_in]
elif mark_vibrY == 1:
x[ind_in] = x_ini[ind_in]
y[ind_in] = Phase_Vibr[nt]*Amp_Vibr_all[i_in]+y_ini[ind_in]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx-B*vx
Fy_all = Fy-B*vy
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = np.array(0)
Ep_now = np.array(0)
cont_now = np.array(0)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now = np.append(cont_now, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
cont_now[0] = cont_now[1]
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
if mark_vibrY == 0:
x_in = Phase_Vibr*Amp_Vibr
freq_fft, fft_in = FFT_Fup(int(Nt/2), x_in[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
y_in = Phase_Vibr*Amp_Vibr
freq_fft, fft_in = FFT_Fup(int(Nt/2), y_in[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_fft, fft_in, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_dPhiSignal(mark_collision, beta, Nt, N, x_ini, y_ini, d0, phi0, m0, Lx, Ly, Freq_Vibr, Amp_Vibr, ind_in, ind_out, dphi_scheme, dphi_on, dphi_off, num_gap, mark_vibrY):
dt = d0/40
Nt = int(Nt)
if dphi_scheme == 1:
nt_dphi = np.linspace(0, Nt, 3)
nt_dphi = nt_dphi.astype(int)
dphi_all = np.zeros(Nt)+dphi_on
dphi_all[nt_dphi[1]:nt_dphi[2]] = dphi_off
elif dphi_scheme == -1:
nt_dphi = np.linspace(0, Nt, 3)
nt_dphi = nt_dphi.astype(int)
dphi_all = np.zeros(Nt)+dphi_off
dphi_all[nt_dphi[1]:nt_dphi[2]] = dphi_on
else:
dphi_all = np.zeros(Nt)+dphi_on
nt_dphi = np.linspace(0, Nt, num_gap+1)
nt_dphi = nt_dphi.astype(int)
for ii in np.arange(1, num_gap, 2):
dphi_all[nt_dphi[ii]:nt_dphi[ii+1]] = dphi_off
D_ini = np.zeros(N)+d0
nt_rec = np.linspace(0, Nt, int(Nt/5e4*num_gap/5)+1)
Ek_rec = np.array(0)
Ep_rec = np.array(0)
cont_rec = np.array(0)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 1:
y_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in]
vy_in = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt))
else:
x_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in]
vx_in = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt))
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
D0 = D_ini*np.sqrt(1+dphi_all[nt]/phi0)
#if np.mod(nt,100000) == 0:
#print(D0[3])
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 1:
y[ind_in] = y_in[nt]
x[ind_in] = x_ini[ind_in]
vy[ind_in] = vy_in[nt]
vx[ind_in] = 0
else:
x[ind_in] = x_in[nt]
y[ind_in] = y_ini[ind_in]
vx[ind_in] = vx_in[nt]
vy[ind_in] = 0
Fx = np.zeros(N)
Fy = np.zeros(N)
if mark_collision == 1:
Fx, Fy, Ep_now, cont_now, p_now = force_YFixed_collision_ConstV(beta, Fx, Fy, N, x, y, vx, vy, D0, Lx, 0, Ly)
Fx_all = Fx
Fy_all = Fy
else:
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Fx_all = Fx-beta*vx
Fy_all = Fy-beta*vy
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_rec = np.append(Ek_rec, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec = np.append(Ep_rec, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec = np.append(cont_rec, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
print ("freq=%f, cont_min=%d, cont_max=%d, cont_ave=%f\n" %(Freq_Vibr, min(cont), max(cont), np.mean(cont)))
nt_dphi = np.arange(0, Nt, 100)
if mark_vibrY == 1:
xy_out = y_out
else:
xy_out = x_out
return nt_dphi, dphi_all[nt_dphi], xy_out, nt_rec[1:], Ek_rec[1:], Ep_rec[1:], cont_rec[1:]
def Damping_calc(Damp_scheme, B, N, x, y, vx, vy, Lx, Ly):
Fx_damp = np.zeros(N)
Fy_damp = np.zeros(N)
if Damp_scheme == 1:
Fx_damp = -B*vx
Fy_damp = -B*vy
if Damp_scheme == 2:
Fx_damp = -B*vx*np.abs(vx)*5e5
Fy_damp = -B*vy*np.abs(vy)*5e5
if Damp_scheme == 3:
Fx_damp = -B*vx/np.sqrt(np.abs(vx))*np.sqrt(2e-6)
Fy_damp = -B*vy/np.sqrt(np.abs(vy))*np.sqrt(2e-6)
if Damp_scheme == 4:
Fx_damp = -B*vx*np.exp(-5e4*np.abs(vx)+1)*0.1
Fy_damp = -B*vy*np.exp(-5e4*np.abs(vy)+1)*0.1
if Damp_scheme == 5:
Fx_damp = -B*vx*np.exp(-5e5*np.abs(vx)+1)
Fy_damp = -B*vy*np.exp(-5e5*np.abs(vy)+1)
if Damp_scheme == 6:
Fx_damp = -B*vx*np.exp(-5e6*np.abs(vx)+1)*10
Fy_damp = -B*vy*np.exp(-5e6*np.abs(vy)+1)*10
if Damp_scheme == 7:
Fx_damp = -B*vx*np.exp(-5e7*np.abs(vx)+1)*100
Fy_damp = -B*vy*np.exp(-5e7*np.abs(vy)+1)*100
return Fx_damp, Fy_damp
def Force_FixedPos_calc(k, N, x, y, x0, y0, D0, vx, vy, Lx, Ly):
Fx_damp = np.zeros(N)
Fy_damp = np.zeros(N)
Ep = 0
for nn in np.arange(N):
dy = y[nn]-y0[nn]
dy = dy-round(dy/Ly)*Ly
Dmn = 0.5*D0[nn]
dx = x[nn]-x0[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if (dmn > 0):
F = -k*(dmn/Dmn/Dmn)/dmn
Fx_damp[nn] += F*dx
Fy_damp[nn] += F*dy
Ep += (1/2)*k*(dmn/Dmn)**2
return Fx_damp, Fy_damp, Ep
def MD_FilterCheck_Periodic_Equi_vCorr(Nt_damp, Nt_FFT, num_period, Damp_scheme, B, N, x0, y0, D0, m0, L, T_set, V_em, n_em):
if Damp_scheme < 0:
return
N = int(N)
Nt_FFT = int(Nt_FFT)
Nt_damp = int(Nt_damp)
dt = min(D0)/40
Nt_period = int(2*Nt_damp+Nt_FFT)
Nt = Nt_period*num_period
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
mark_damp = np.zeros(Nt)
mark_FFT = np.zeros(Nt)
for ii in np.arange(num_period):
if ii > 0:
t1 = ii*Nt_period
t2 = t1+Nt_damp
mark_damp[t1:t2] = 1
t3 = ii*Nt_period+2*Nt_damp
t4 = t3+Nt_FFT
mark_FFT[t3:t4] = 1
nt_rec = np.linspace(0, Nt, int(Nt/1e3)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = []
Ep_rec = []
cont_rec = []
num_FFT = 0
vx = np.zeros(N)
vy = np.zeros(N)
for ii in np.arange(n_em):
ind1 = 2*np.arange(N)
ind2 = ind1+1
vx += V_em[ind1, ii]
vy += V_em[ind2, ii]
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
if mark_damp[nt] == 1:
Fx_damp, Fy_damp = Damping_calc(Damp_scheme, B, N, x, y, vx, vy, L[0], L[1])
Fx = Fx + Fx_damp
Fy = Fy + Fy_damp
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if mark_FFT[nt] == 1:
if mark_FFT[nt-1] == 0:
nt_ref = nt
vx_rec = np.zeros([Nt_FFT, N])
vy_rec = np.zeros([Nt_FFT, N])
nt_delta = nt-nt_ref
vx_rec[nt_delta] = vx
vy_rec[nt_delta] = vy
if nt_delta == Nt_FFT-1:
num_FFT += 1
freq_now, fft_now = FFT_vCorr(Nt_FFT, N, vx_rec, vy_rec, dt)
if num_FFT == 1:
fft_all = np.array([fft_now])
freq_all = np.array([freq_now])
len_fft_ref = len(fft_now)
len_freq_ref = len(freq_now)
else:
fft_add = np.zeros(len_fft_ref)
freq_add = np.zeros(len_freq_ref)
len_fft_now = len(fft_now)
len_freq_now = len(freq_now)
if len_fft_now >= len_fft_ref:
fft_add[0:len_fft_ref] = fft_now[0:len_fft_ref]
else:
fft_add[0:len_fft_now] = fft_now[0:len_fft_now]
fft_add[len_fft_now:] = fft_now[len_fft_now]
if len_freq_now >= len_freq_ref:
freq_add[0:len_freq_ref] = freq_now[0:len_freq_ref]
else:
freq_add[0:len_freq_now] = freq_now[0:len_freq_now]
freq_add[len_freq_now:] = freq_now[len_freq_now]
fft_all = np.append(fft_all, [fft_add], axis=0)
freq_all = np.append(freq_all, [freq_add], axis=0)
print("FFT_iteration: %d" % num_FFT)
print("Ek_ave: %e" %(np.mean(Ek[nt_ref:nt])))
ind1 = m0>5
ind2 = m0<5
print("|vx|_ave(heavy):%e" % np.mean(np.abs(vx[ind1])))
print("|vx|_ave(light):%e" % np.mean(np.abs(vx[ind2])))
for ii in np.arange(len(nt_rec)-1):
Ek_rec.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f" %(CB_ratio))
return freq_all, fft_all, (nt_rec[:-1]+nt_rec[1:])/2, Ek_rec, Ep_rec, cont_rec
def MD_FilterCheck_Periodic_Equi_vCorr_Seperate(Nt_damp, Nt_FFT, num_period, Damp_scheme, k, B, N, x0, y0, D0, m0, L, T_set, V_em, n_em):
# for damping scheme = -1 (fixed spring at initial position)
if Damp_scheme != -1:
return
N = int(N)
Nt_FFT = int(Nt_FFT)
Nt_damp = int(Nt_damp)
dt = min(D0)/40
Nt = Nt_damp*num_period+Nt_FFT
if num_period == 0:
Nt = Nt_damp+Nt_FFT
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
mark_FFT = np.zeros(Nt)
t1 = Nt_damp * num_period
if num_period == 0:
t1 = Nt_damp
t2 = t1 + Nt_FFT
mark_FFT[t1:t2] = 1
nt_rec = np.linspace(0, Nt, int(Nt/1e3)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = []
Ep_rec = []
cont_rec = []
vx = np.zeros(N)
vy = np.zeros(N)
for ii in np.arange(n_em):
ind1 = 2*np.arange(N)
ind2 = ind1+1
vx += V_em[ind1, ii]
vy += V_em[ind2, ii]
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
# always have damping exceot num_period = 0
if num_period > 0:
Fx_damp, Fy_damp, Ep_fix = Force_FixedPos_calc(k, N, x, y, x0, y0, D0, vx, vy, L[0], L[1])
if (B > 0):
Fx_damp += -B*vx
Fy_damp += -B*vy
elif num_period == 0:
Fx_damp = 0
Fy_damp = 0
Ep_fix = 0
Ep_now += Ep_fix
Fx = Fx + Fx_damp
Fy = Fy + Fy_damp
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if mark_FFT[nt] == 1:
if mark_FFT[nt-1] == 0:
nt_ref = nt
vx_rec = np.zeros([Nt_FFT, N])
vy_rec = np.zeros([Nt_FFT, N])
nt_delta = nt-nt_ref
vx_rec[nt_delta] = vx
vy_rec[nt_delta] = vy
if nt_delta == Nt_FFT-1:
freq_now, fft_now = FFT_vCorr(Nt_FFT, N, vx_rec, vy_rec, dt)
print ("Nt_End="+str(nt))
for ii in np.arange(len(nt_rec)-1):
Ek_rec.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f" %(CB_ratio))
return freq_now, fft_now, (nt_rec[:-1]+nt_rec[1:])/2, Ek_rec, Ep_rec, cont_rec
def MD_Periodic_Equi_vDistr(Nt_MD, Nt_rec, N, x0, y0, D0, m0, L, T_set, V_em, n_em):
N = int(N)
Nt_MD = int(Nt_MD)
Nt_rec = int(Nt_rec)
dt = min(D0)/40
Nt = Nt_MD+Nt_rec
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/1e3)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = []
Ep_rec = []
cont_rec = []
ind1 = m0>5
ind2 = m0<5
vx_light = []
vx_heavy = []
vy_light = []
vy_heavy = []
vx = np.zeros(N)
vy = np.zeros(N)
for ii in np.arange(n_em):
ind1 = 2*np.arange(N)
ind2 = ind1+1
vx += V_em[ind1, ii]
vy += V_em[ind2, ii]
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if nt >= Nt_MD:
vx_light.extend(vx[ind2])
vy_light.extend(vy[ind2])
vx_heavy.extend(vx[ind1])
vy_heavy.extend(vy[ind1])
for ii in np.arange(len(nt_rec)-1):
Ek_rec.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f" %(CB_ratio))
return nt_rec, Ek_rec, Ep_rec, cont_rec, vx_light, vx_heavy, vy_light, vy_heavy
def Output_resonator_1D(Nt, x_drive, x0, m0, w0, dt):
dx = x_drive - x0
k = w0**2*m0
x = 0
vx = 0
ax_old = 0
Nt = int(Nt)
x_rec = np.zeros(Nt)
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
x_rec[nt] = x
Fx = k*(dx[nt]-x)
ax = Fx/m0;
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
ax_old = ax;
freq_fft, fft_x_rec = FFT_Fup(int(Nt/2), x_rec[int(Nt/2):Nt], dt, w0)
return freq_fft, fft_x_rec
def MD_Periodic_vCorr(Nt, N, x0, y0, D0, m0, vx0, vy0, L, T_set):
dt = min(D0)/40
Nt = int(Nt)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
vx_rec = np.zeros([int(Nt/2), N])
vy_rec = np.zeros([int(Nt/2), N])
vx = vx0
vy = vy0
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if (nt >= Nt/2):
vx_rec[int(nt-Nt/2)] = vx
vy_rec[int(nt-Nt/2)] = vy
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f\n" %(CB_ratio))
freq_now, fft_now = FFT_vCorr(int(Nt/2), N, vx_rec, vy_rec, dt)
return freq_now, fft_now, np.mean(cont)
def MD_Period_ConstV_SD(Nt, N, x0, y0, D0, m0, Lx, Ly):
dt = D0[0]/40
Nt = int(Nt)
Ep = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, Lx, Ly)
Ep[nt] = Ep_now
vx = 0.1*np.divide(Fx, m0)
vy = 0.1*np.divide(Fy, m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
#t_end = time.time()
print ("F_tot=%.3e" %(F_tot[nt]))
#print ("time=%.3e" %(t_end-t_start))
return x, y, p_now
def Force_FixedPos_YFixed_calc(k, N, x, y, x0, y0, D0, vx, vy, Lx, Ly):
Fx_damp = np.zeros(N)
Fy_damp = np.zeros(N)
Ep = 0
for nn in np.arange(N):
dy = y[nn]-y0[nn]
Dmn = 0.5*D0[nn]
dx = x[nn]-x0[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if (dmn > 0):
F = -k*(dmn/Dmn/Dmn)/dmn
Fx_damp[nn] += F*dx
Fy_damp[nn] += F*dy
Ep += (1/2)*k*(dmn/Dmn)**2
return Fx_damp, Fy_damp, Ep
def MD_VibrSP_ConstV_Yfixed_FixSpr(k, B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, ind_in, ind_out):
mark_vibrY = 0
mark_resonator = 1
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in]
elif mark_vibrY == 1:
y_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in]
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 0:
x[ind_in] = x_in[nt]
y[ind_in] = y_ini[ind_in]
elif mark_vibrY == 1:
x[ind_in] = x_ini[ind_in]
y[ind_in] = y_in[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Fx_damp, Fy_damp, Ep_fix = Force_FixedPos_YFixed_calc(k, N, x, y, x_ini, y_ini, D0, vx, vy, L[0], L[1])
#Fx_damp = 0; Fy_damp = 0; Ep_fix = 0
Fx_damp += -B*vx
Fy_damp += -B*vy
Ep[nt] = Ep_now + Ep_fix
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx+Fx_damp
Fy_all = Fy+Fy_damp
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = []
Ep_now = []
cont_now = []
for ii in np.arange(len(nt_rec)-1):
Ek_now.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[1:] + nt_rec[:-1]) / 2
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f, Ek_mean=%.3e, Ep_mean=%.3e\n" %(Freq_Vibr, CB_ratio, np.mean(Ek), np.mean(Ep)))
if mark_vibrY == 0:
freq_fft, fft_in = FFT_Fup(int(Nt/2), x_in[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in = FFT_Fup(int(Nt/2), y_in[int(Nt/2):Nt], dt, Freq_Vibr)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
return freq_fft, fft_in, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_VibrSP_ConstV_Yfixed_FixSpr2(k, B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out):
mark_vibrY = 0
mark_resonator = 0
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in1 = Amp_Vibr1*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in1]
x_in2 = Amp_Vibr2*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in2]
elif mark_vibrY == 1:
y_in1 = Amp_Vibr1*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in1]
y_in2 = Amp_Vibr2*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in2]
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 0:
x[ind_in1] = x_in1[nt]
y[ind_in1] = y_ini[ind_in1]
x[ind_in2] = x_in2[nt]
y[ind_in2] = y_ini[ind_in2]
elif mark_vibrY == 1:
x[ind_in1] = x_ini[ind_in1]
y[ind_in1] = y_in1[nt]
x[ind_in2] = x_ini[ind_in2]
y[ind_in2] = y_in2[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Fx_damp, Fy_damp, Ep_fix = Force_FixedPos_YFixed_calc(k, N, x, y, x_ini, y_ini, D0, vx, vy, L[0], L[1])
#Fx_damp = 0; Fy_damp = 0; Ep_fix = 0
Fx_damp += -B*vx
Fy_damp += -B*vy
Ep[nt] = Ep_now + Ep_fix
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx+Fx_damp
Fy_all = Fy+Fy_damp
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = []
Ep_now = []
cont_now = []
for ii in np.arange(len(nt_rec)-1):
Ek_now.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[1:] + nt_rec[:-1]) / 2
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
#print ("freq=%f, cont_min/cont_max=%f, Ek_mean=%.3e, Ep_mean=%.3e\n" %(Freq_Vibr, CB_ratio, np.mean(Ek), np.mean(Ep)))
if mark_vibrY == 0:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), x_in1[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), x_in2[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), y_in1[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), y_in2[int(Nt/2):Nt], dt, Freq_Vibr)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
return freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_VibrSP_ConstV_Yfixed_FixSpr3(k, B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr1, Amp_Vibr1, ind_in1, Freq_Vibr2, Amp_Vibr2, ind_in2, ind_out):
mark_vibrY = 0
mark_resonator = 0
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in1 = Amp_Vibr1*np.sin(Freq_Vibr1*dt*np.arange(Nt))+x_ini[ind_in1]
x_in2 = Amp_Vibr2*np.sin(Freq_Vibr2*dt*np.arange(Nt))+x_ini[ind_in2]
elif mark_vibrY == 1:
y_in1 = Amp_Vibr1*np.sin(Freq_Vibr1*dt*np.arange(Nt))+y_ini[ind_in1]
y_in2 = Amp_Vibr2*np.sin(Freq_Vibr2*dt*np.arange(Nt))+y_ini[ind_in2]
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 0:
x[ind_in1] = x_in1[nt]
y[ind_in1] = y_ini[ind_in1]
x[ind_in2] = x_in2[nt]
y[ind_in2] = y_ini[ind_in2]
elif mark_vibrY == 1:
x[ind_in1] = x_ini[ind_in1]
y[ind_in1] = y_in1[nt]
x[ind_in2] = x_ini[ind_in2]
y[ind_in2] = y_in2[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Fx_damp, Fy_damp, Ep_fix = Force_FixedPos_YFixed_calc(k, N, x, y, x_ini, y_ini, D0, vx, vy, L[0], L[1])
#Fx_damp = 0; Fy_damp = 0; Ep_fix = 0
Fx_damp += -B*vx
Fy_damp += -B*vy
Ep[nt] = Ep_now + Ep_fix
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx+Fx_damp
Fy_all = Fy+Fy_damp
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = []
Ep_now = []
cont_now = []
for ii in np.arange(len(nt_rec)-1):
Ek_now.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[1:] + nt_rec[:-1]) / 2
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f, Ek_mean=%.3e, Ep_mean=%.3e\n" %(Freq_Vibr1, CB_ratio, np.mean(Ek), np.mean(Ep)))
if mark_vibrY == 0:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), x_in1[int(Nt/2):Nt], dt, Freq_Vibr1)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), x_in2[int(Nt/2):Nt], dt, Freq_Vibr2)
elif mark_vibrY == 1:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), y_in1[int(Nt/2):Nt], dt, Freq_Vibr1)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), y_in2[int(Nt/2):Nt], dt, Freq_Vibr2)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr1)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr1)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr1, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr1, dt)
return freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_VibrSP_Force_ConstV(B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, ind_in, ind_out, mark_vibrY, mark_resonator):
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
x_in = np.zeros(Nt)
y_in = np.zeros(Nt)
if mark_vibrY == 0:
Fx_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))
elif mark_vibrY == 1:
Fy_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
x_in[nt] = x[ind_in]
y_in[nt] = y[ind_in]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx-B*vx
Fy_all = Fy-B*vy
if mark_vibrY == 0:
Fx_all[ind_in] += Fx_in[nt]
elif mark_vibrY == 1:
Fy_all[ind_in] += Fy_in[nt]
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = np.array(0)
Ep_now = np.array(0)
cont_now = np.array(0)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now = np.append(cont_now, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
cont_now[0] = cont_now[1]
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
if mark_vibrY == 0:
freq_fft, fft_in = FFT_Fup(int(Nt/2), x_in[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in = FFT_Fup(int(Nt/2), y_in[int(Nt/2):Nt], dt, Freq_Vibr)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
if Nt == 5e5:
print(x[ind_out], y[ind_out])
print(fft_x_out[100], fft_y_out[100])
print(fft_in[100])
return freq_fft, fft_in, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_VibrSP_ConstV_ConfigCB(B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, ind_in, ind_out, Nt_rec):
mark_vibrY = 0
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in]
elif mark_vibrY == 1:
y_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in]
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
if nt == Nt_rec:
x_rec = x[:]
y_rec = y[:]
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 0:
x[ind_in] = x_in[nt]
y[ind_in] = y_ini[ind_in]
elif mark_vibrY == 1:
x[ind_in] = x_ini[ind_in]
y[ind_in] = y_in[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx-B*vx
Fy_all = Fy-B*vy
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = np.array(0)
Ep_now = np.array(0)
cont_now = np.array(0)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now = np.append(cont_now, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
cont_now[0] = cont_now[1]
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
return x_rec, y_rec
def VL_YFixed_ConstV(N, x, y, D, Lx, VL_list, VL_counter_old, x_save, y_save, first_call):
r_factor = 1.2
r_cut = np.amax(D)
r_list = r_factor * r_cut
r_list_sq = r_list**2
r_skin_sq = ((r_factor - 1.0) * r_cut)**2
if first_call == 0:
dr_sq_max = 0.0
for nn in np.arange(N):
dy = y[nn] - y_save[nn]
dx = x[nn] - x_save[nn]
dx = dx - round(dx / Lx) * Lx
dr_sq = dx**2 + dy**2
if dr_sq > dr_sq_max:
dr_sq_max = dr_sq
if dr_sq_max < r_skin_sq:
return VL_list, VL_counter_old, x_save, y_save
VL_counter = 0
for nn in np.arange(N):
r_now = 0.5*D[nn]
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < r_list:
dx = x[mm]-x[nn]
dx = dx - round(dx / Lx) * Lx
if abs(dx) < r_list:
dmn_sq = dx**2 + dy**2
if dmn_sq < r_list_sq:
VL_list[VL_counter][0] = nn
VL_list[VL_counter][1] = mm
VL_counter += 1
return VL_list, VL_counter, x, y
def MD_YFixed_ConstV_SP_SD_DiffK(Nt, N, x0, y0, D0, m0, Lx, Ly, k_list, k_type):
dt = D0[0] * np.sqrt(k_list[2]) / 20.0
Nt = int(Nt)
Ep = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
x_save = np.array(x0)
y_save = np.array(y0)
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list = np.zeros((N * 10, 2), dtype=int)
VL_counter = 0
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 1)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 0)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
Ep[nt] = Ep_now
vx = 0.1 * Fx
vy = 0.1 * Fy
x += vx * dt
y += vy * dt
F_tot[nt] = sum(np.absolute(Fx) + np.absolute(Fy))
# putting a threshold on total force
if (F_tot[nt] < 1e-11):
break
print(nt)
print(F_tot[nt])
t_end = time.time()
#print ("F_tot=%.3e" %(F_tot[nt]))
#print ("time=%.3e" %(t_end-t_start))
return x, y, p_now
def FIRE_YFixed_ConstV_DiffK(Nt, N, x0, y0, D0, m0, Lx, Ly, k_list, k_type):
dt_md = 0.01 * D0[0] * np.sqrt(k_list[2])
N_delay = 20
N_pn_max = 2000
f_inc = 1.1
f_dec = 0.5
a_start = 0.15
f_a = 0.99
dt_max = 10.0 * dt_md
dt_min = 0.05 * dt_md
initialdelay = 1
Nt = int(Nt)
Ep = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
x_save = np.array(x0)
y_save = np.array(y0)
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list = np.zeros((N * 10, 2), dtype=int)
VL_counter = 0
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 1)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
a_fire = a_start
delta_a_fire = 1.0 - a_fire
dt = dt_md
dt_half = dt / 2.0
N_pp = 0 # number of P being positive
N_pn = 0 # number of P being negative
## FIRE
for nt in np.arange(Nt):
# FIRE update
P = np.dot(vx, Fx) + np.dot(vy, Fy)
if P > 0.0:
N_pp += 1
N_pn = 0
if N_pp > N_delay:
dt = min(f_inc * dt, dt_max)
dt_half = dt / 2.0
a_fire = f_a * a_fire
delta_a_fire = 1.0 - a_fire
else:
N_pp = 0
N_pn += 1
if N_pn > N_pn_max:
break
if (initialdelay < 0.5) or (nt >= N_delay):
if f_dec * dt > dt_min:
dt = f_dec * dt
dt_half = dt / 2.0
a_fire = a_start
delta_a_fire = 1.0 - a_fire
x -= vx * dt_half
y -= vy * dt_half
vx = np.zeros(N)
vy = np.zeros(N)
# MD using Verlet method
vx += Fx * dt_half
vy += Fy * dt_half
rsc_fire = np.sqrt(np.sum(vx**2 + vy**2)) / np.sqrt(np.sum(Fx**2 + Fy**2))
vx = delta_a_fire * vx + a_fire * rsc_fire * Fx
vy = delta_a_fire * vy + a_fire * rsc_fire * Fy
x += vx * dt
y += vy * dt
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 0)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
Ep[nt] = Ep_now
F_tot[nt] = sum(np.absolute(Fx) + np.absolute(Fy))
# putting a threshold on total force
if (F_tot[nt] < 1e-11):
break
vx += Fx * dt_half
vy += Fy * dt_half
#print(nt)
#print(F_tot[nt])
t_end = time.time()
#print ("F_tot=%.3e" %(F_tot[nt]))
#print ("time=%.3e" %(t_end-t_start))
return x, y, p_now
def MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out):
Lx = L[0]
Ly = L[1]
mark_vibrY = 0
mark_resonator = 0
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
F_tot = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in1 = Amp_Vibr1*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in1]
x_in2 = Amp_Vibr2*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in2]
elif mark_vibrY == 1:
y_in1 = Amp_Vibr1*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in1]
y_in2 = Amp_Vibr2*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in2]
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
x_save = np.array(x_ini)
y_save = np.array(y_ini)
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list = np.zeros((N * 10, 2), dtype=int)
VL_counter = 0
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 1)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2 # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2
if mark_vibrY == 0:
x[ind_in1] = x_in1[nt]
y[ind_in1] = y_ini[ind_in1]
x[ind_in2] = x_in2[nt]
y[ind_in2] = y_ini[ind_in2]
elif mark_vibrY == 1:
x[ind_in1] = x_ini[ind_in1]
y[ind_in1] = y_in1[nt]
x[ind_in2] = x_ini[ind_in2]
y[ind_in2] = y_in2[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 0)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx - B*vx
Fy_all = Fy - B*vy
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2 # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2
ax_old = ax
ay_old = ay
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = []
Ep_now = []
cont_now = []
for ii in np.arange(len(nt_rec)-1):
Ek_now.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[1:] + nt_rec[:-1]) / 2
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
#print ("freq=%f, cont_min/cont_max=%f, Ek_mean=%.3e, Ep_mean=%.3e\n" %(Freq_Vibr, CB_ratio, np.mean(Ek), np.mean(Ep)))
if mark_vibrY == 0:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), x_in1[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), x_in2[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), y_in1[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), y_in2[int(Nt/2):Nt], dt, Freq_Vibr)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
return freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out):
Lx = L[0]
Ly = L[1]
mark_vibrY = 0
mark_resonator = 0
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
F_tot = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in1 = Amp_Vibr1*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in1]
x_in2 = Amp_Vibr2*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in2]
elif mark_vibrY == 1:
y_in1 = Amp_Vibr1*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in1]
y_in2 = Amp_Vibr2*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in2]
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
x_save = np.array(x_ini)
y_save = np.array(y_ini)
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list = np.zeros((N * 10, 2), dtype=int)
VL_counter = 0
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 1)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2 # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2
if mark_vibrY == 0:
x[ind_in1] = x_in1[nt]
y[ind_in1] = y_ini[ind_in1]
x[ind_in2] = x_in2[nt]
y[ind_in2] = y_ini[ind_in2]
elif mark_vibrY == 1:
x[ind_in1] = x_ini[ind_in1]
y[ind_in1] = y_in1[nt]
x[ind_in2] = x_ini[ind_in2]
y[ind_in2] = y_in2[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 0)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx - B*vx
Fy_all = Fy - B*vy
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2 # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2
ax_old = ax
ay_old = ay
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = []
Ep_now = []
cont_now = []
for ii in np.arange(len(nt_rec)-1):
Ek_now.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[1:] + nt_rec[:-1]) / 2
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
#print ("freq=%f, cont_min/cont_max=%f, Ek_mean=%.3e, Ep_mean=%.3e\n" %(Freq_Vibr, CB_ratio, np.mean(Ek), np.mean(Ep)))
if mark_vibrY == 0:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), x_in1[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), x_in2[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), y_in1[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), y_in2[int(Nt/2):Nt], dt, Freq_Vibr)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
return x_in1-x_ini[ind_in1], x_in2-x_ini[ind_in2], x_out-x_ini[ind_out]
| 133,858 | 30.675106 | 178 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/constants.py
|
# number of runs
RUNS = 3
worstFitness = +1000000
# population size
popSize = 50
# number of generations
numGenerations = 200
| 129 | 10.818182 | 23 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/afpo_seed_binary.py
|
import constants as c
import copy
import numpy as np
import operator
import statistics
import pickle
from joblib import Parallel, delayed
import multiprocessing
from genome_seed_binary import GENOME
class AFPO:
def __init__(self,randomSeed):
self.randomSeed = randomSeed
self.currentGeneration = 0
self.nextAvailableID = 0
self.genomes = {}
for populationPosition in range(c.popSize):
self.genomes[populationPosition] = GENOME(self.nextAvailableID)
self.nextAvailableID = self.nextAvailableID + 1
def Evolve(self):
self.Perform_First_Generation()
for self.currentGeneration in range(1,c.numGenerations):
self.Perform_One_Generation()
self.SaveLastGen()
# -------------------------- Private methods ----------------------
def Age(self):
for genome in self.genomes:
self.genomes[genome].Age()
def Aggressor_Dominates_Defender(self,aggressor,defender):
return self.genomes[aggressor].Dominates(self.genomes[defender])
def Choose_Aggressor(self):
return np.random.randint(c.popSize)
def Choose_Defender(self,aggressor):
defender = np.random.randint(c.popSize)
while defender == aggressor:
defender = np.random.randint(c.popSize)
return defender
def Contract(self):
while len(self.genomes) > c.popSize:
aggressorDominatesDefender = False
while not aggressorDominatesDefender:
aggressor = self.Choose_Aggressor()
defender = self.Choose_Defender(aggressor)
aggressorDominatesDefender = self.Aggressor_Dominates_Defender(aggressor,defender)
for genomeToMove in range(defender,len(self.genomes)-1):
self.genomes[genomeToMove] = self.genomes.pop(genomeToMove+1)
def process(self, i):
return i*i
def Evaluate_Genomes(self):
num_cores = multiprocessing.cpu_count()
print("we have")
print(num_cores)
print("cores")
outs = Parallel(n_jobs=num_cores)(delayed(self.genomes[genome].Evaluate)() for genome in self.genomes)
#print("done")
#print(type(outs))
#self.genomes = copy.deepcopy(np.array(outs))
#self.genomes = dict(zip(list(range(0, c.popSize)), outs))
#print(type(self.genomes))
for genome in self.genomes:
# print(genome)
#print(self.genomes[genome].indv.fitness)
# print(outs[genome])
self.genomes[genome].fitness = outs[genome]
self.genomes[genome].indv.fitness = -outs[genome]
def Expand(self):
popSize = len(self.genomes)
for newGenome in range( popSize , 2 * popSize - 1 ):
spawner = self.Choose_Aggressor()
self.genomes[newGenome] = copy.deepcopy(self.genomes[spawner])
self.genomes[newGenome].Set_ID(self.nextAvailableID)
self.nextAvailableID = self.nextAvailableID + 1
self.genomes[newGenome].Mutate()
def Find_Best_Genome(self):
genomesSortedByFitness = sorted(self.genomes.values(), key=operator.attrgetter('fitness'),reverse=False)
return genomesSortedByFitness[0]
def Find_Avg_Fitness(self):
add = 0
for g in self.genomes:
add += self.genomes[g].fitness
return add/c.popSize
def Inject(self):
popSize = len(self.genomes)
self.genomes[popSize-1] = GENOME(self.nextAvailableID)
self.nextAvailableID = self.nextAvailableID + 1
def Perform_First_Generation(self):
self.Evaluate_Genomes()
self.Print()
self.Save_Best()
self.Save_Avg()
def Perform_One_Generation(self):
self.Expand()
self.Age()
self.Inject()
self.Evaluate_Genomes()
self.Contract()
self.Print()
self.Save_Best()
self.Save_Avg()
def Print(self):
print('Generation ', end='', flush=True)
print(self.currentGeneration, end='', flush=True)
print(' of ', end='', flush=True)
print(str(c.numGenerations), end='', flush=True)
print(': ', end='', flush=True)
bestGenome = self.Find_Best_Genome()
bestGenome.Print()
def Save_Best(self):
bestGenome = self.Find_Best_Genome()
bestGenome.Save(self.randomSeed)
def SaveLastGen(self):
genomesSortedByFitness = sorted(self.genomes.values(), key=operator.attrgetter('fitness'),reverse=False)
f = open('savedRobotsLastGenAfpoSeed.dat', 'ab')
pickle.dump(genomesSortedByFitness, f)
f.close()
def Save_Avg(self):
f = open('avgFitnessAfpoSeed.dat', 'ab')
avg = self.Find_Avg_Fitness()
print('Average ' + str(avg))
print()
#f.write("%.3f\n" % avg)
pickle.dump(avg, f)
f.close()
def Show_Best_Genome(self):
bestGenome = self.Find_Best_Genome()
bestGenome.Show()
| 5,048 | 30.955696 | 112 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/DynamicalMatrix.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 22:09:09 2017
@author: Hightoutou
"""
def DM_mass(N, x0, y0, D0, m0, L):
import numpy as np
Lx = L[0]
Ly = L[1]
M = np.zeros((2*N, 2*N))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
rijsq = dx**2+dy**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0],[0,1]])/rij/dij
Mij = Mij1+Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
m_sqrt = np.zeros((2*N, 2*N))
m_inv = np.zeros((2*N, 2*N))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_3D(N, x0, y0, z0, D0, m0, L):
import numpy as np
Lx = L[0]
Ly = L[1]
Lz = L[2]
M = np.zeros((3*N, 3*N))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
dz = z0[i]-z0[j]
dz = dz-round(dz/Lz)*Lz
rijsq = dx**2+dy**2+dz**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy, dx*dz], [dy*dx, dy*dy, dy*dz], [dz*dx, dz*dy, dz*dz]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0,0],[0,1,0],[0,0,1]])/rij/dij
Mij = Mij1+Mij2
M[3*i:3*i+3,3*j:3*j+3] = Mij
M[3*j:3*j+3,3*i:3*i+3] = Mij
M[3*i:3*i+3,3*i:3*i+3] = M[3*i:3*i+3,3*i:3*i+3] - Mij
M[3*j:3*j+3,3*j:3*j+3] = M[3*j:3*j+3,3*j:3*j+3] - Mij
m_sqrt = np.zeros((3*N, 3*N))
m_inv = np.zeros((3*N, 3*N))
for i in range(N):
m_sqrt[3*i, 3*i] = 1/np.sqrt(m0[i])
m_sqrt[3*i+1, 3*i+1] = 1/np.sqrt(m0[i])
m_sqrt[3*i+2, 3*i+2] = 1/np.sqrt(m0[i])
m_inv[3*i, 3*i] = 1/m0[i]
m_inv[3*i+1, 3*i+1] = 1/m0[i]
m_inv[3*i+2, 3*i+2] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_Yfixed(N, x0, y0, D0, m0, Lx, y_bot, y_top, k):
import numpy as np
M = np.zeros((2*N, 2*N))
contactNum = 0
for i in range(N):
r_now = 0.5*D0[i]
if y0[i]-y_bot<r_now or y_top-y0[i]<r_now:
M[2*i+1, 2*i+1] = M[2*i+1, 2*i+1]+1/r_now/r_now
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
rijsq = dx**2+dy**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0],[0,1]])/rij/dij
Mij = Mij1+Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
M = k*M
m_sqrt = np.zeros((2*N, 2*N))
m_inv = np.zeros((2*N, 2*N))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_Xfixed(N, x0, y0, D0, m0, Ly):
import numpy as np
M = np.zeros((2*N, 2*N))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
rijsq = dx**2+dy**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0],[0,1]])/rij/dij
Mij = Mij1+Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
m_sqrt = np.zeros((2*N, 2*N))
m_inv = np.zeros((2*N, 2*N))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_DiffK_Yfixed(N, x0, y0, D0, m0, Lx, y_bot, y_top, k_list, k_type):
import numpy as np
M = np.zeros((2*N, 2*N))
contactNum = 0
for i in range(N):
r_now = 0.5*D0[i]
if y0[i]-y_bot<r_now or y_top-y0[i]<r_now:
M[2*i+1, 2*i+1] = M[2*i+1, 2*i+1] + k_list[k_type[i]] / r_now / r_now
for j in range(i):
dij = 0.5 * (D0[i] + D0[j])
dijsq = dij**2
dx = x0[i] - x0[j]
dx = dx - round(dx / Lx) * Lx
dy = y0[i] - y0[j]
rijsq = dx**2 + dy**2
if rijsq < dijsq:
contactNum += 1
k = k_list[(k_type[i] ^ k_type[j]) + np.maximum(k_type[i], k_type[j])]
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -k * rijmat / rijsq / dijsq
Mij2 = -k * (1.0 - rij / dij) * (rijmat / rijsq - [[1,0],[0,1]]) / rij / dij
Mij = Mij1 + Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
m_sqrt = np.zeros((2*N, 2*N))
m_inv = np.zeros((2*N, 2*N))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_Zfixed_3D(N, x0, y0, z0, D0, m0, L):
import numpy as np
Lx = L[0]
Ly = L[1]
Lz = L[2]
M = np.zeros((3*N, 3*N))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
dz = z0[i]-z0[j]
rijsq = dx**2+dy**2+dz**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy, dx*dz], [dy*dx, dy*dy, dy*dz], [dz*dz, dz*dy, dz*dz]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0,0],[0,1,0],[0,0,1]])/rij/dij
Mij = Mij1+Mij2
M[3*i:3*i+3,3*j:3*j+3] = Mij
M[3*j:3*j+3,3*i:3*i+3] = Mij
M[3*i:3*i+3,3*i:3*i+3] = M[3*i:3*i+3,3*i:3*i+3] - Mij
M[3*j:3*j+3,3*j:3*j+3] = M[3*j:3*j+3,3*j:3*j+3] - Mij
m_sqrt = np.zeros((3*N, 3*N))
m_inv = np.zeros((3*N, 3*N))
for i in range(N):
m_sqrt[3*i, 3*i] = 1/np.sqrt(m0[i])
m_sqrt[3*i+1, 3*i+1] = 1/np.sqrt(m0[i])
m_sqrt[3*i+2, 3*i+2] = 1/np.sqrt(m0[i])
m_inv[3*i, 3*i] = 1/m0[i]
m_inv[3*i+1, 3*i+1] = 1/m0[i]
m_inv[3*i+2, 3*i+2] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_UpPlate(N, x0, y0, D0, m0, Lx, y_up, m_up):
import numpy as np
M = np.zeros((2*N+1, 2*N+1))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
rijsq = dx**2+dy**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0],[0,1]])/rij/dij
Mij = Mij1+Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
for i in range(N):
r_now = 0.5*D0[i]
if y0[i]<r_now:
M[2*i+1, 2*i+1] = M[2*i+1, 2*i+1]+1/r_now**2
if y_up-y0[i]<r_now:
M[2*i+1, 2*i+1] = M[2*i+1, 2*i+1]+1/r_now**2
M[2*N, 2*N] = M[2*N, 2*N]+1/r_now**2
M[2*i+1, 2*N] = M[2*i+1, 2*N]-1/r_now**2
M[2*N, 2*i+1] = M[2*N, 2*i+1]-1/r_now**2
m_sqrt = np.zeros((2*N+1, 2*N+1))
m_inv = np.zeros((2*N+1, 2*N+1))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
m_sqrt[2*N, 2*N] = 1/np.sqrt(m_up)
m_inv[2*N, 2*N] = 1/m_up
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_UpPlate_3D(N, x0, y0, z0, D0, m0, Lx, Ly, z_up, m_up):
import numpy as np
M = np.zeros((3*N+1, 3*N+1))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
dz = z0[i]-z0[j]
rijsq = dx**2+dy**2+dz**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy, dx*dz], [dy*dx, dy*dy, dy*dz], [dz*dz, dz*dy, dz*dz]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0,0],[0,1,0],[0,0,1]])/rij/dij
Mij = Mij1+Mij2
M[3*i:3*i+3,3*j:3*j+3] = Mij
M[3*j:3*j+3,3*i:3*i+3] = Mij
M[3*i:3*i+3,3*i:3*i+3] = M[3*i:3*i+3,3*i:3*i+3] - Mij
M[3*j:3*j+3,3*j:3*j+3] = M[3*j:3*j+3,3*j:3*j+3] - Mij
for i in range(N):
r_now = 0.5*D0[i]
if z0[i]<r_now:
M[3*i+2, 3*i+2] = M[3*i+2, 3*i+2]+1/r_now**2
if z_up-z0[i]<r_now:
M[3*i+2, 3*i+2] = M[3*i+2, 3*i+2]+1/r_now**2
M[3*N, 3*N] = M[3*N, 3*N]+1/r_now**2
M[3*i+2, 3*N] = M[3*i+2, 3*N]-1/r_now**2
M[3*N, 3*i+2] = M[3*N, 3*i+2]-1/r_now**2
m_sqrt = np.zeros((3*N+1, 3*N+1))
m_inv = np.zeros((3*N+1, 3*N+1))
for i in range(N):
m_sqrt[3*i, 3*i] = 1/np.sqrt(m0[i])
m_sqrt[3*i+1, 3*i+1] = 1/np.sqrt(m0[i])
m_sqrt[3*i+2, 3*i+2] = 1/np.sqrt(m0[i])
m_inv[3*i, 3*i] = 1/m0[i]
m_inv[3*i+1, 3*i+1] = 1/m0[i]
m_inv[3*i+2, 3*i+2] = 1/m0[i]
m_sqrt[3*N, 3*N] = 1/np.sqrt(m_up)
m_inv[3*N, 3*N] = 1/m_up
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
| 12,537 | 30.423559 | 104 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/ConfigPlot.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 21:01:26 2017
@author: Hightoutou
"""
import numpy as np
def ConfigPlot_DiffSize(N, x, y, D, L, mark_print):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
Dmin = min(D)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
D_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
D_all.append(D[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_alpha(0.3)
if D_all[i] > Dmin:
e.set_facecolor('C1')
else:
e.set_facecolor('C0')
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
def ConfigPlot_DiffMass(N, x, y, D, L, m, mark_print, hn):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffMass2(N, x, y, D, L, m, mark_print, hn, in1, in2, out):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
if i==in1:
e.set_edgecolor((0, 1, 0))
e.set_linewidth(4)
elif i==in2:
e.set_edgecolor((0, 0, 1))
e.set_linewidth(4)
elif i==out:
e.set_edgecolor((1, 0, 0))
e.set_linewidth(4)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffStiffness(N, x, y, D, L, m, mark_print, hn):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C2')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffStiffness2(N, x, y, D, L, m, mark_print, hn, in1, in2, out):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
if i==in1:
e.set_edgecolor((0, 1, 0))
e.set_linewidth(4)
elif i==in2:
e.set_edgecolor((0, 0, 1))
e.set_linewidth(4)
elif i==out:
e.set_edgecolor((1, 0, 0))
e.set_linewidth(4)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C2')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffStiffness3(N, x, y, D, L, m, mark_print, hn, in1, in2, out):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
if i==in1:
e.set_edgecolor((0, 1, 0))
e.set_linewidth(4)
plt.scatter(x_now, y_now, marker='^', s=80, color=(0, 1, 0, 1))
elif i==in2:
e.set_edgecolor((0, 0, 1))
e.set_linewidth(4)
plt.scatter(x_now, y_now, marker='s', s=80, color=(0, 0, 1, 1))
elif i==out:
e.set_edgecolor((1, 0, 0))
e.set_linewidth(4)
plt.scatter(x_now, y_now, marker='*', s=100, color=(1, 0, 0, 1))
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('k')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
import matplotlib.lines as mlines
red_star = mlines.Line2D([], [], color=(1, 0, 0), marker='*', linestyle='None',
markersize=10, label='Output')
blue_square = mlines.Line2D([], [], color=(0, 0, 1), marker='s', linestyle='None',
markersize=10, label='Input 2')
green_triangle = mlines.Line2D([], [], color=(0, 1, 0), marker='^', linestyle='None',
markersize=10, label='Input 1')
plt.legend(handles=[red_star, green_triangle, blue_square], bbox_to_anchor=(1.215, 1))
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffMass_3D(N, x, y, z, D, L, m, mark_print):
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
m_min = min(m)
m_max = max(m)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_aspect('equal')
sphes = []
m_all = []
for i in range(int(N/2)):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
z_now = z[i]%L[2]
r_now = 0.5*D[i]
#alpha_now = 0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3
alpha_now = 0.3
pos1 = 0
pos2 = 1
for j in range(pos1, pos2):
for k in range(pos1, pos2):
for l in range(pos1, pos2):
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x_plot = x_now+j*L[0]+r_now * np.outer(np.cos(u), np.sin(v))
y_plot = y_now+k*L[1]+r_now * np.outer(np.sin(u), np.sin(v))
z_plot = z_now+l*L[2]+r_now * np.outer(np.ones(np.size(u)), np.cos(v))
ymin = y_plot[y_plot>0].min()
ymax = y_plot[y_plot>0].max()
print (i, ymin, ymax)
ax.plot_surface(x_plot,y_plot,z_plot,rstride=4,cstride=4, color='C0',linewidth=0,alpha=alpha_now)
#sphes.append(e)
#m_all.append(m[i])
# i = 0
# for e in sphes:
# ax.add_artist(e)
# e.set_clip_box(ax.bbox)
# e.set_facecolor('C0')
# e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
#e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
# i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
ax.set_zlim(0, L[2])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
def ConfigPlot_YFixed_rec(N, x, y, D, Lx, y_top, y_bot, m, mark_order):
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse, Rectangle
mark_print = 0
m_min = min(m)
m_max = max(m)
if m_min == m_max:
m_max *= 1.001
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%Lx
y_now = y[i]
if mark_order==1:
plt.text(x_now, y_now, str(i))
for k in range(-1, 2):
e = Ellipse((x_now+k*Lx, y_now), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.3+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
#rect = Rectangle([0, y_top], Lx, 0.2*D[0], color='C0')
#ax.add_patch(rect)
for nn in np.arange(N):
x1 = x[nn]%Lx
d_up = y_top-y[nn]
d_bot = y[nn]-y_bot
r_now = 0.5*D[nn]
if d_up<r_now:
ax.plot([x1, x1], [y[nn], y[nn]+r_now], '-', color='w')
if d_bot<r_now:
ax.plot([x1, x1], [y[nn], y[nn]-r_now], '-', color='w')
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
x2 = x[mm]%Lx
if x2>x1:
xl = x1
xr = x2
yl = y[nn]
yr = y[mm]
else:
xl = x2
xr = x1
yl = y[mm]
yr = y[nn]
dx0 = xr-xl
dx = dx0-round(dx0/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
if dx0<Dmn:
ax.plot([xl, xr], [yl, yr], '-', color='w')
else:
ax.plot([xl, xr-Lx], [yl, yr], '-', color='w')
ax.plot([xl+Lx, xr], [yl, yr], '-', color='w')
ax.set_xlim(0, Lx)
ax.set_ylim(y_bot, y_top)
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/plot_test/fig'+str(int(ind_nt+1e4))+'.png', dpi = 150)
def ConfigPlot_DiffMass_SP(N, x, y, D, L, m, mark_print, ind_in, ind_out, ind_fix):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
width = 2
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m[i]-m_min)/(m_max-m_min)*0.3)
if i == ind_in:
e.set_edgecolor('r')
e.set_linewidth(width)
if i == ind_out:
e.set_edgecolor('b')
e.set_linewidth(width)
if i == ind_fix:
e.set_edgecolor('k')
e.set_linewidth(width)
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
def ConfigPlot_DiffMass_FixLx(N, x, y, D, L, m, mark_print, ind_wall):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
width = 2
for i in range(N):
x_now = x[i]
y_now = y[i]%L[1]
for l in range(-1, 2):
e = Ellipse((x_now, y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
if ind_wall[i] > 0:
e.set_edgecolor('k')
e.set_linewidth(width)
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
def ConfigPlot_DiffMass_SP_rec(N, x, y, D, L, m, mark_print, ind_in, ind_out, ind_fix):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
width = 2
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m[i]-m_min)/(m_max-m_min)*0.3)
if i == ind_in:
e.set_edgecolor('r')
e.set_linewidth(width)
if i == ind_out:
e.set_edgecolor('b')
e.set_linewidth(width)
if i == ind_fix:
e.set_edgecolor('k')
e.set_linewidth(width)
Lx = L[0]
Ly = L[1]
for nn in np.arange(N):
x1 = x[nn]%Lx
y1 = y[nn]%Ly
for mm in np.arange(nn+1, N):
x2 = x[mm]%Lx
y2 = y[mm]%Ly
if x2>x1:
xl = x1
xr = x2
yl = y1
yr = y2
else:
xl = x2
xr = x1
yl = y2
yr = y1
dx0 = xr-xl
dx = dx0-round(dx0/Lx)*Lx
if y2>y1:
xd = x1
xu = x2
yd = y1
yu = y2
else:
xd = x2
xu = x1
yd = y2
yu = y1
dy0 = yu-yd
dy = dy0-round(dy0/Ly)*Ly
Dmn = 0.5*(D[mm]+D[nn])
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
if dx0<Dmn and dy0<Dmn:
ax.plot([xl, xr], [yl, yr], '-', color='w')
else:
if dx0>Dmn and dy0>Dmn:
if yr>yl:
ax.plot([xl, xr-Lx], [yl, yr-Ly], '-', color='w')
ax.plot([xl+Lx, xr], [yl+Ly, yr], '-', color='w')
else:
ax.plot([xl, xr-Lx], [yl, yr+Ly], '-', color='w')
ax.plot([xl+Lx, xr], [yl-Ly, yr], '-', color='w')
else:
if dx0>Dmn:
ax.plot([xl, xr-Lx], [yl, yr], '-', color='w')
ax.plot([xl+Lx, xr], [yl, yr], '-', color='w')
if dy0>Dmn:
ax.plot([xd, xu], [yd, yu-Ly], '-', color='w')
ax.plot([xd, xu], [yd+Ly, yu], '-', color='w')
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
return fig
def ConfigPlot_EigenMode_DiffMass(N, x, y, D, L, m, em, mark_print, hn):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
if m_min == m_max:
m_max *= 1.001
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
r_now = D[0]*0.5
dr = np.zeros(N)
for i in range(N):
dr[i] = np.sqrt(em[2*i]**2+em[2*i+1]**2)
dr_max = max(dr)
for i in range(N):
ratio = dr[i]/dr_max*r_now/dr_max
plt.arrow(x[i], y[i],em[2*i]*ratio, em[2*i+1]*ratio, head_width=0.005)
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_YFixed_SelfAssembly(N, Nl, x, y, theta, n, d1, d2, Lx, y_top, y_bot):
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse, Rectangle
mark_order = 0
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
alpha_all = []
alpha1 = 0.6
alpha2 = 0.3
for i in range(N):
x_now = x[i]%Lx
y_now = y[i]
if mark_order==1:
plt.text(x_now, y_now, str(i))
alpha = alpha1 if i < Nl else alpha2
for k in range(-1, 2):
e = Ellipse((x_now+k*Lx, y_now), d1,d1,0)
ells.append(e)
alpha_all.append(alpha)
if i >= Nl:
for ind in range(n):
x_i = x_now+k*Lx+0.5*(d1+d2)*np.cos(theta[i]+ind*2*np.pi/n)
y_i = y_now+0.5*(d1+d2)*np.sin(theta[i]+ind*2*np.pi/n)
e = Ellipse((x_i, y_i), d2,d2,0)
ells.append(e)
alpha_all.append(alpha)
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(alpha_all[i])
i += 1
ax.set_xlim(0, Lx)
ax.set_ylim(y_bot, y_top)
plt.show()
def ConfigPlot_YFixed_SelfAssembly_BumpyBd(N, n_col, Nl, x, y, theta, n, d0, d1, d2, Lx, y_top, y_bot):
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse, Rectangle
mark_order = 0
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
alpha_all = []
alpha1 = 0.6
alpha2 = 0.3
for i in range(n_col+1):
x_now = i*d0
e1 = Ellipse((x_now, y_bot), d0,d0,0)
e2 = Ellipse((x_now, y_top), d0,d0,0)
ells.append(e1)
alpha_all.append(alpha1)
ells.append(e2)
alpha_all.append(alpha1)
for i in range(N):
x_now = x[i]%Lx
y_now = y[i]
if mark_order==1:
plt.text(x_now, y_now, str(i))
alpha = alpha1 if i < Nl else alpha2
for k in range(-1, 2):
e = Ellipse((x_now+k*Lx, y_now), d1,d1,0)
ells.append(e)
alpha_all.append(alpha)
if i >= Nl:
for ind in range(n):
x_i = x_now+k*Lx+0.5*(d1+d2)*np.cos(theta[i]+ind*2*np.pi/n)
y_i = y_now+0.5*(d1+d2)*np.sin(theta[i]+ind*2*np.pi/n)
e = Ellipse((x_i, y_i), d2,d2,0)
ells.append(e)
alpha_all.append(alpha)
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(alpha_all[i])
i += 1
ax.set_xlim(0, Lx)
ax.set_ylim(y_bot, y_top)
plt.show()
| 22,835 | 29.488652 | 117 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/genome_seed_binary.py
|
import constants as c
from individual_seed_binary import INDIVIDUAL
import pickle
class GENOME:
def __init__(self,ID,fitness=c.worstFitness):
self.Set_ID(ID)
self.indv = INDIVIDUAL(ID)
self.age = 0
self.fitness = fitness
def Age(self):
self.age = self.age + 1
def Dominates(self,other):
if self.Get_Fitness() <= other.Get_Fitness():
if self.Get_Age() <= other.Get_Age():
equalFitnesses = self.Get_Fitness() == other.Get_Fitness()
equalAges = self.Get_Age() == other.Get_Age()
if not equalFitnesses and equalAges:
return True
else:
return self.Is_Newer_Than(other)
else:
return False
else:
return False
def Evaluate(self):
#self.indv.Start_Evaluation(True)
f = self.indv.Compute_Fitness()
# if f < 0:
# self.fitness = c.worstFitness
# else:
# self.fitness = 1/(1+f)
self.fitness = -f
#print(f)
#print(self.indv.genome)
return self.fitness
def Get_Age(self):
return self.age
def Get_Fitness(self):
return self.fitness
def Mutate(self):
self.indv.Mutate()
def Print(self):
print(' fitness: ' , end = '' )
print(self.fitness , end = '' )
print(' age: ' , end = '' )
print(self.age , end = '' )
print()
def Save(self,randomSeed):
f = open('savedRobotsAfpoSeed.dat', 'ab')
pickle.dump(self.indv , f)
f.close()
pass
def Set_ID(self,ID):
self.ID = ID
def Show(self):
#self.indv.Start_Evaluation(False, 40)
self.indv.Compute_Fitness(True)
# def __add__(self, other):
# total_fitness = self.fitness + other.fitness
# print("I've been called")
# return GENOME(1, total_fitness)
# def __radd__(self, other):
# if other == 0:
# return self
# else:
# return self.__add__(other)
# -------------------- Private methods ----------------------
def Get_ID(self):
return self.ID
def Is_Newer_Than(self,other):
return self.Get_ID() > other.Get_ID()
| 2,336 | 24.681319 | 74 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/afpoPlots_seed_binary.py
|
import pickle
import matplotlib.pyplot as plt
from switch_binary import switch
import constants as c
import numpy
runs = c.RUNS
gens = c.numGenerations
fitnesses = numpy.zeros([runs, gens])
temp = []
individuals = []
with open('savedRobotsAfpoSeed.dat', "rb") as f:
for r in range(1, runs+1):
for g in range(1, gens+1):
try:
temp.append(pickle.load(f).fitness)
except EOFError:
break
fitnesses[r-1] = temp
temp = []
f.close()
mean_f = numpy.mean(fitnesses, axis=0)
std_f = numpy.std(fitnesses, axis=0)
plt.figure(figsize=(6.4,4.8))
plt.plot(list(range(1, gens+1)), mean_f, color='blue')
plt.fill_between(list(range(1, gens+1)), mean_f-std_f, mean_f+std_f, color='cornflowerblue', alpha=0.2)
plt.xlabel("Generations")
plt.ylabel("Best Fitness")
plt.title("Fitness of the Best Individual in the Population - AFPO", fontsize='small')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.tight_layout()
#plt.legend(['two robot', 'three robots'], loc='upper left')
#plt.savefig("compare.pdf")
plt.show()
# running the best individuals
m1 = 1
m2 = 10
N_light = 9
N = 30
bests = numpy.zeros([runs, gens])
temp = []
rubish = []
with open('savedRobotsLastGenAfpoSeed.dat', "rb") as f:
for r in range(1, runs+1):
# population of the last generation
temp = pickle.load(f)
# best individual of last generation
best = temp[0]
switch.showPacking(m1, m2, N_light, best.indv.genome)
print(switch.evaluate(m1, m2, N_light, best.indv.genome))
print(switch.evaluateAndPlot(m1, m2, N_light, best.indv.genome))
temp = []
f.close()
# running all of the individuals of the last generation of each of the runs
bests = numpy.zeros([runs, gens])
temp = []
rubish = []
with open('savedRobotsLastGenAfpoSeed.dat', "rb") as f:
for r in range(1, runs+1):
print("run:")
print(r)
# population of the last generation
temp = pickle.load(f)
for g in range(0, gens):
switch.showPacking(m1, m2, N_light, temp[g].indv.genome)
print(switch.evaluateAndPlot(m1, m2, N_light, temp[g].indv.genome))
temp = []
f.close()
| 2,217 | 28.972973 | 103 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/evolveAfpo_seed_binary.py
|
from afpo_seed_binary import AFPO
import os
import constants as c
import random
#cleaning up the data files
try:
os.remove("savedRobotsLastGenAfpoSeed.dat")
except OSError:
pass
try:
os.remove("avgFitnessAfpoSeed.dat")
except OSError:
pass
try:
os.remove("savedRobotsAfpoSeed.dat")
except OSError:
pass
runs = c.RUNS
for r in range(1, runs+1):
print("*********************************************************", flush=True)
print("run: "+str(r), flush=True)
randomSeed = r
random.seed(r)
afpo = AFPO(randomSeed)
afpo.Evolve()
#afpo.Show_Best_Genome()
| 616 | 18.28125 | 82 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/individual_seed_binary.py
|
from switch_binary import switch
import constants as c
import random
import math
import numpy as np
import sys
import pickle
class INDIVIDUAL:
def __init__(self, i):
# assuming curves have one control point, [Sx, Ex, Cx, Cy] for each fiber
# assuming we have two planes, each with c.FIBERS of fibers on them
self.m1 = 1
self.m2 = 10 #[2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000] #10 is what is in fig2 of the paper
self.N_light = 9 #[25, 50, 75] #[9, 15, 21]
self.N = 30
#self.low = 7
#self.high = 12
#indices = random.sample(range(0, N), N_light)
self.genome = np.random.randint(low=0, high=2, size=self.N)#random.sample(range(0, self.N), self.N_light) #np.random.randint(0, high=c.GRID_SIZE-1, size=(c.FIBERS*2, 4), dtype='int')
self.fitness = 0
self.ID = i
def Compute_Fitness(self, show=False):
# wait for the simulation to end and get the fitness
self.fitness = switch.evaluate(self.m1, self.m2, self.N_light, self.genome)#, self.low, self.high)
if show:
switch.showPacking(self.m1, self.m2, self.N_light, self.genome)#, self.low, self.high)
print("fitness is:")
print(self.fitness)
return self.fitness
def Mutate(self):
mutationRate = 0.05
probToMutate = np.random.choice([False, True], size=self.genome.shape, p=[1-mutationRate, mutationRate])
candidate = np.where(probToMutate, 1-self.genome, self.genome)
self.genome = candidate
def Print(self):
print('[', self.ID, self.fitness, ']', end=' ')
def Save(self):
f = open('savedFitnessSeed.dat', 'ab')
pickle.dump(self.fitness , f)
f.close()
def SaveBest(self):
f = open('savedBestsSeed.dat', 'ab')
pickle.dump(self.genome , f)
f.close()
| 1,936 | 35.54717 | 190 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/randomSearch2.py
|
from switch_binary import switch
import matplotlib.pyplot as plt
import random
import numpy as np
from joblib import Parallel, delayed
import multiprocessing
import pickle
from scipy.stats import norm
import operator
from ConfigPlot import ConfigPlot_DiffStiffness3
with open('outs.dat', "rb") as f:
outs = pickle.load(f)
f.close()
with open('samples.dat', "rb") as f:
samples = pickle.load(f)
f.close()
# compute the cumulative sum
#Nk_cum = np.cumsum(Nk)
# go to log scale
#log_Nk_cum = np.log10(Nk_cum)
#log_k = np.log10(k)
# plot the original data
#fig = plt.figure()
#ax = plt.gca()
#ax.scatter(log_k, log_Nk_cum, s=5, alpha=0.3)
#ax.set_title('CCDF in log-log scale')
#ax.set_xlabel('$Log_{10}(k)$')
#ax.set_ylabel('$Log_{10}(Nk_{>k})$')
def showPacking(indices):
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
m1=1
m2=10
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
# show packing
ConfigPlot_DiffStiffness3(N, x0, y0, D, [Lx,Ly], k_type, 0, '/Users/atoosa/Desktop/results/packing.pdf', ind_in1, ind_in2, ind_out)
print("done", flush=True)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
n, bins, patches = plt.hist(x=outs, bins='auto', color='#0504aa', alpha=0.7, cumulative=False)#, grid=True)
# fitting a normal distribution
mu, std = norm.fit(outs)
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 1000)
p = norm.pdf(x, mu, std)
#plt.plot(x, p, linewidth=2)
myText = "Mean={:.3f}, STD={:.3f}".format(mu, std)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize='medium', color='g')
plt.xlabel('AND-Ness')
plt.ylabel('Counts')
plt.title('Random Search', fontsize='medium')
#plt.xlim([0, 8])
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
#plt.show()
plt.savefig("histogram2.jpg", dpi=300)
sortedList = list(zip(*sorted(zip(samples,outs), key=operator.itemgetter(1))))
showPacking(sortedList[0][0])
print(sortedList[1][0])
showPacking(sortedList[0][-1])
print(sortedList[1][-1])
| 3,115 | 24.966667 | 138 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/plot_functions.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 22 14:48:04 2017
@author: Hightoutou
"""
import matplotlib.pyplot as plt
#import matplotlib
#matplotlib.use('TkAgg')
def Line_single(xdata, ydata, line_spec, xlabel, ylabel, mark_print, fn = '', xscale='linear', yscale='linear'):
fig, ax1 = plt.subplots()
fig.set_size_inches(3.5,3.5*3/4)
pos1 = ax1.get_position()
pos2 = [pos1.x0 + 0.12, pos1.y0 + 0.05, pos1.width-0.1, pos1.height]
ax1.set_position(pos2)
#ax1.tick_params(labelsize=10)
for axis in ['top','bottom','left','right']:
ax1.spines[axis].set_linewidth(2)
plt.ylabel(ylabel, fontsize=12)
plt.xlabel(xlabel, fontsize=12)
plt.xscale(xscale), plt.yscale(yscale)
plt.style.use('default')
ax1.plot(xdata, ydata, line_spec)
if mark_print == 1:
fig.savefig(fn, dpi = 300)
fig.show()
def Line_multi(xdata, ydata, line_spec, xlabel, ylabel, xscale='linear', yscale='linear'):
fig, ax1 = plt.subplots()
fig.set_size_inches(3.5,3.5*3/4)
ax1.tick_params(labelsize=10)
for axis in ['top','bottom','left','right']:
ax1.spines[axis].set_linewidth(2)
ax1.set_ylabel(ylabel, fontsize=12)
plt.xlabel(xlabel, fontsize=12)
plt.xscale(xscale), plt.yscale(yscale)
plt.style.use('default')
for ii in range(len(xdata)):
ax1.plot(xdata[ii], ydata[ii], line_spec[ii])
plt.show()
def Line_yy(xdata, ydata, line_spec, xlabel, ylabel, xscale='linear', yscale='linear'):
fig, ax1 = plt.subplots()
fig.set_size_inches(3.5,3.5*3/4)
ax1.tick_params(labelsize=10)
for axis in ['top','bottom','left','right']:
ax1.spines[axis].set_linewidth(2)
ax1.set_ylabel(ylabel[0], fontsize=12)
plt.xlabel(xlabel, fontsize=12)
plt.xscale(xscale), plt.yscale(yscale)
plt.style.use('default')
ax1.plot(xdata[0], ydata[0], line_spec[0])
ax2 = ax1.twinx()
ax2.set_ylabel(ylabel[1], fontsize=12)
ax2.plot(xdata[1], ydata[1], line_spec[1])
plt.show()
| 2,062 | 33.966102 | 112 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/FFT_functions.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 17 15:10:21 2017
@author: Hightoutou
"""
import numpy as np
import matplotlib.pyplot as plt
from plot_functions import Line_multi, Line_single
#from numba import jit
def FFT_Fup(Nt, F, dt, Freq_Vibr):
sampling_rate = 1/dt
t = np.arange(Nt)*dt
fft_size = Nt
xs = F[:fft_size]
xf = np.absolute(np.fft.rfft(xs)/fft_size)
freqs = (2*np.pi)*np.linspace(0, sampling_rate/2, fft_size//2+1)
ind = freqs<30
freqs = freqs[ind]
xf = xf[ind]
if 1 == 0:
Line_multi([freqs[1:], [Freq_Vibr, Freq_Vibr]], [xf[1:], [min(xf[1:]), max(xf[1:])]], ['o', 'r--'], 'Frequency', 'FFT', 'linear', 'log')
return freqs[1:], xf[1:]
def FFT_Fup_RealImag(Nt, F, dt, Freq_Vibr):
sampling_rate = 1/dt
t = np.arange(Nt)*dt
fft_size = Nt
xs = F[:fft_size]
xf = np.fft.rfft(xs)/fft_size
freqs = (2*np.pi)*np.linspace(0, sampling_rate/2, fft_size/2+1)
ind = freqs<30
freqs = freqs[ind]
xf = xf[ind]
xf_real = xf.real
xf_imag = xf.imag
if 1 == 0:
Line_multi([freqs[1:], [Freq_Vibr, Freq_Vibr]], [xf[1:], [min(xf[1:]), max(xf[1:])]], ['o', 'r--'], 'Frequency', 'FFT')
return freqs[1:], xf_real[1:], xf_imag[1:]
#@jit
def vCorr_Cal(fft_size, Nt, y_raw):
y_fft = np.zeros(fft_size)
for jj in np.arange(fft_size):
sum_vcf = 0
sum_tt = 0
count = 0
for kk in np.arange(Nt-jj):
count = count+1
sum_vcf += y_raw[kk]*y_raw[kk+jj];
sum_tt = sum_tt+y_raw[kk]*y_raw[kk];
y_fft[jj] = sum_vcf/sum_tt;
return y_fft
def FFT_vCorr(Nt, N, vx_rec, vy_rec, dt):
sampling_rate = 1/dt
fft_size = Nt-1
freqs = (2*np.pi)*np.linspace(0, sampling_rate/2, fft_size/2+1)
for ii in np.arange(2*N):
#for ii in [0,4]:
if np.mod(ii, 10) == 0:
print('ii=%d\n' % (ii))
if ii >= N:
y_raw = vy_rec[:, ii-N]
else:
y_raw = vx_rec[:, ii]
y_fft = vCorr_Cal(fft_size, Nt, y_raw)
if ii == 0:
xf = np.absolute(np.fft.rfft(y_fft)/fft_size)
else:
xf += np.absolute(np.fft.rfft(y_fft)/fft_size)
ind = freqs<30
freqs = freqs[ind]
xf = xf[ind]
if 1 == 1:
Line_single(freqs[1:], xf[1:], 'o', 'Frequency', 'FFT')
return freqs[1:], xf[1:]
def FFT_vCorr_3D(Nt, N, vx_rec, vy_rec, vz_rec, dt):
sampling_rate = 1/dt
fft_size = Nt-1
freqs = (2*np.pi)*np.linspace(0, sampling_rate/2, fft_size/2+1)
for ii in np.arange(3*N):
#for ii in [0,4]:
if np.mod(ii, 10) == 0:
print('ii=%d\n' % (ii))
if ii >= 2*N:
y_raw = vz_rec[:, ii-2*N]
elif ii < N:
y_raw = vx_rec[:, ii]
else:
y_raw = vy_rec[:, ii-N]
y_fft = vCorr_Cal(fft_size, Nt, y_raw)
if ii == 0:
xf = np.absolute(np.fft.rfft(y_fft)/fft_size)
else:
xf += np.absolute(np.fft.rfft(y_fft)/fft_size)
ind = freqs<30
freqs = freqs[ind]
xf = xf[ind]
if 1 == 1:
Line_single(freqs[1:], xf[1:], 'o', 'Frequency', 'FFT')
return freqs[1:], xf[1:]
| 3,487 | 25.225564 | 152 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/randomSearch.py
|
from switch_binary import switch
import matplotlib.pyplot as plt
import random
import numpy as np
from joblib import Parallel, delayed
import multiprocessing
import pickle
m1 = 1
m2 = 10
N = 30
N_light = 9
samples = []
print("sampling", flush=True)
for i in range(0, 5001):
samples.append(np.random.randint(low=0, high=2, size=N))
print("sampling done", flush=True)
num_cores = multiprocessing.cpu_count()
outs = Parallel(n_jobs=num_cores)(delayed(switch.evaluate)(m1, m2, N_light, samples[i]) for i in range(0, 5001))
print("done", flush=True)
f = open('outs.dat', 'ab')
pickle.dump(outs , f)
f.close()
f = open('samples.dat', 'ab')
pickle.dump(samples , f)
f.close()
n, bins, patches = plt.hist(x=outs, bins='auto', color='#0504aa', alpha=0.7, rwidth=0.85)#, grid=True)
plt.xlabel('Andness')
plt.ylabel('Counts')
plt.title('Random Search')
#plt.xlim([0, 8])
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.show()
plt.savefig("histogram.jpg", dpi=300)
| 978 | 21.767442 | 112 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/AND-NESS/plotInOut.py
|
import constants as c
import numpy as np
from ConfigPlot import ConfigPlot_DiffStiffness2
from MD_functions import MD_VibrSP_ConstV_Yfixed_DiffK, FIRE_YFixed_ConstV_DiffK, MD_VibrSP_ConstV_Yfixed_DiffK2
from DynamicalMatrix import DM_mass_DiffK_Yfixed
import random
import matplotlib.pyplot as plt
import pickle
from os.path import exists
from switch_binary import switch
def showPacking(indices):
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
m1=1
m2=10
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
# show packing
ConfigPlot_DiffStiffness2(N, x0, y0, D, [Lx,Ly], k_type, 0, '/Users/atoosa/Desktop/results/packing.pdf', ind_in1, ind_in2, ind_out)
def plotInOut(indices):
#%% Initial Configuration
k1 = 1.
k2 = 10.
m1 = 1
m2 = 10
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# calculating the bandgap - no need to do this in this problem
w, v = DM_mass_DiffK_Yfixed(N, x_ini, y_ini, D, mass, Lx, 0.0, Ly, k_list, k_type)
w = np.real(w)
v = np.real(v)
freq = np.sqrt(np.absolute(w))
ind_sort = np.argsort(freq)
freq = freq[ind_sort]
v = v[:, ind_sort]
ind = freq > 1e-4
eigen_freq = freq[ind]
eigen_mode = v[:, ind]
w_delta = eigen_freq[1:] - eigen_freq[0:-1]
index = np.argmax(w_delta)
F_low_exp = eigen_freq[index]
F_high_exp = eigen_freq[index+1]
plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.scatter(np.arange(0, len(eigen_freq)), eigen_freq, marker='x', color='blue')
plt.xlabel("Number")
plt.ylabel("Frequency")
plt.title("Vibrational Response", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
props = dict(facecolor='green', alpha=0.1)
myText = 'f_low='+"{:.2f}".format(F_low_exp)+"\n"+'f_high='+"{:.2f}".format(F_high_exp)+"\n"+'band gap='+"{:.2f}".format(max(w_delta))
plt.text(0.85, 0.1, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize='large', bbox=props)
plt.tight_layout()
plt.show()
print("specs:")
print(F_low_exp)
print(F_high_exp)
print(max(w_delta))
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr = 7
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='Input1', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency")
plt.ylabel("Amplitude of FFT")
plt.title("Logic Gate Response - input = 11", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right')
plt.tight_layout()
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
myText = 'Gain='+"{:.3f}".format(gain1)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize='medium')
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='Input1', linestyle='solid')
plt.plot(x_in2, color='blue', label='Input2', linestyle='solid')
plt.plot(x_out, color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps")
plt.ylabel("Amplitude of Displacement")
plt.title("Logic Gate Response - input = 11", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right')
plt.tight_layout()
plt.show()
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='Input1', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency")
plt.ylabel("Amplitude of FFT")
plt.title("Logic Gate Response - input = 10", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right')
plt.tight_layout()
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
myText = 'Gain='+"{:.3f}".format(gain2)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize='medium')
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='Input1', linestyle='solid')
plt.plot(x_in2, color='blue', label='Input2', linestyle='solid')
plt.plot(x_out, color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps")
plt.ylabel("Amplitude of Displacement")
plt.title("Logic Gate Response - input = 10", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right')
plt.tight_layout()
plt.show()
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='Input1', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency")
plt.ylabel("Amplitude of FFT")
plt.title("Logic Gate Response - input = 01", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right')
plt.tight_layout()
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
myText = 'Gain='+"{:.3f}".format(gain3)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize='medium')
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='Input1', linestyle='solid')
plt.plot(x_in2, color='blue', label='Input2', linestyle='solid')
plt.plot(x_out, color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps")
plt.ylabel("Amplitude of Displacement")
plt.title("Logic Gate Response - input = 01", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right')
plt.tight_layout()
plt.show()
print("gain1:")
print(gain1)
print("gain2:")
print(gain2)
print("gain3:")
print(gain3)
andness = 2*gain1/(gain2+gain3)
return andness
runs = c.RUNS
gens = c.numGenerations
# running the best individuals
temp = []
rubish = []
with open('savedRobotsLastGenAfpoSeed.dat', "rb") as f:
for r in range(1, runs+1):
# population of the last generation
temp = pickle.load(f)
# best individual of last generation
best = temp[0]
showPacking(best.indv.genome)
print(plotInOut(best.indv.genome))
temp = []
f.close()
| 13,392 | 35.997238 | 248 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/switch_binary.py
|
import numpy as np
from ConfigPlot import ConfigPlot_EigenMode_DiffMass, ConfigPlot_YFixed_rec, ConfigPlot_DiffMass_SP
from MD_functions import MD_VibrSP_ConstV_Yfixed_DiffK
from MD_functions import FIRE_YFixed_ConstV_DiffK
from DynamicalMatrix import DM_mass_DiffK_Yfixed
from plot_functions import Line_single, Line_multi
from ConfigPlot import ConfigPlot_DiffStiffness
import random
import matplotlib.pyplot as plt
import pickle
from os.path import exists
class switch():
def evaluate(m1, m2, N_light, indices):
#%% Initial Configuration
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# calculating the bandgap - no need to do this in this problem
#w, v = DM_mass_DiffK_Yfixed(N, x_ini, y_ini, D, mass, Lx, 0.0, Ly, k_list, k_type)
#w = np.real(w)
#v = np.real(v)
#freq = np.sqrt(np.absolute(w))
#ind_sort = np.argsort(freq)
#freq = freq[ind_sort]
#v = v[:, ind_sort]
#ind = freq > 1e-4
#eigen_freq = freq[ind]
#eigen_mode = v[:, ind]
#w_delta = eigen_freq[1:] - eigen_freq[0:-1]
#index = np.argmax(w_delta)
#F_low_exp = eigen_freq[index]
#F_high_exp = eigen_freq[index+1]
#print("specs:")
#print(F_low_exp)
#print(F_high_exp)
#print(max(w_delta))
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr = 7
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
XOR = (gain2+gain3)/(2*gain1)
return XOR
def showPacking(m1, m2, N_light, indices):
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# show packing
ConfigPlot_DiffStiffness(N, x0, y0, D, [Lx,Ly], k_type, 0, '/Users/atoosa/Desktop/results/packing.pdf')
def evaluateAndPlot(m1, m2, N_light, indices):
#%% Initial Configuration
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# calculating the bandgap - no need to do this in this problem
w, v = DM_mass_DiffK_Yfixed(N, x_ini, y_ini, D, mass, Lx, 0.0, Ly, k_list, k_type)
w = np.real(w)
v = np.real(v)
freq = np.sqrt(np.absolute(w))
ind_sort = np.argsort(freq)
freq = freq[ind_sort]
v = v[:, ind_sort]
ind = freq > 1e-4
eigen_freq = freq[ind]
eigen_mode = v[:, ind]
w_delta = eigen_freq[1:] - eigen_freq[0:-1]
index = np.argmax(w_delta)
F_low_exp = eigen_freq[index]
F_high_exp = eigen_freq[index+1]
plt.figure(figsize=(6.4,4.8))
plt.scatter(np.arange(0, len(eigen_freq)), eigen_freq, marker='x', color='blue')
plt.xlabel("Number")
plt.ylabel("Frequency")
plt.title("Vibrational Reponse", fontsize='small')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.tight_layout()
plt.show()
print("specs:")
print(F_low_exp)
print(F_high_exp)
print(max(w_delta))
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr = 7
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
print("gain1:")
print(gain1)
print("gain2:")
print(gain2)
print("gain3:")
print(gain3)
XOR = (gain2+gain3)/(2*gain1)
return XOR
| 14,724 | 36.563776 | 252 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/MD_functions.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 13 13:09:27 2017
@author: Hightoutou
"""
import numpy as np
import time
#from numba import jit
from FFT_functions import FFT_Fup, FFT_vCorr
from plot_functions import Line_multi, Line_yy, Line_single
from ConfigPlot import ConfigPlot_YFixed_rec
import matplotlib.pyplot as plt
#import IPython.core.debugger
#dbg = IPython.core.debugger.Pdb()
#@jit
def force_YFixed(Fx, Fy, N, x, y, D, Lx, y_bot, y_up):
Fup = 0
Fbot = 0
Ep = 0
cont = 0
cont_up = 0
p_now = 0
for nn in np.arange(N):
d_up = y_up-y[nn]
d_bot = y[nn]-y_bot
r_now = 0.5*D[nn]
if d_up<r_now:
F = -(1-d_up/r_now)/(r_now)
Fup -= F
Fy[nn] += F
Ep += (1/2)*(1-d_up/r_now)**2
cont_up += 1
cont += 1
#dbg.set_trace()
if d_bot<r_now:
F = -(1-d_bot/r_now)/(r_now)
Fbot += F
Fy[nn] -= F
Ep += (1/2)*(1-d_bot/r_now)**2
cont += 1
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
dx = x[mm]-x[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, Fup, Fbot, Ep, cont, p_now, cont_up
def force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D, Lx, y_bot, y_up, k_list, k_type, VL_list, VL_counter):
Fup = 0
Fbot = 0
Ep = 0
cont = 0
cont_up = 0
p_now = 0
for nn in np.arange(N):
d_up = y_up - y[nn]
d_bot = y[nn] - y_bot
r_now = 0.5 * D[nn]
if d_up < r_now:
F = -k_list[k_type[nn]] * (1 - d_up / r_now) / (r_now)
Fup -= F
Fy[nn] += F
Ep += 0.5 * k_list[k_type[nn]] * (1 - d_up / r_now)**2
cont_up += 1
cont += 1
#dbg.set_trace()
if d_bot < r_now:
F = -k_list[k_type[nn]] * (1 - d_bot / r_now) / (r_now)
Fbot += F
Fy[nn] -= F
Ep += 0.5 * k_list[k_type[nn]] * (1 - d_bot / r_now)**2
cont += 1
for vl_idx in np.arange(VL_counter):
nn = VL_list[vl_idx][0]
mm = VL_list[vl_idx][1]
dy = y[mm] - y[nn]
Dmn = 0.5 * (D[mm] + D[nn])
if abs(dy) < Dmn:
dx = x[mm] - x[nn]
dx = dx - round(dx / Lx) * Lx
if abs(dx) < Dmn:
dmn = np.sqrt(dx**2 + dy**2)
if dmn < Dmn:
k = k_list[(k_type[nn] ^ k_type[mm]) + np.maximum(k_type[nn], k_type[mm])]
F = -k * (1 - dmn / Dmn) / Dmn / dmn
Fx[nn] += F * dx
Fx[mm] -= F * dx
Fy[nn] += F * dy
Fy[mm] -= F * dy
Ep += 0.5 * k * (1 - dmn / Dmn)**2
cont += 1
p_now += (-F) * (dx**2 + dy**2)
return Fx, Fy, Fup, Fbot, Ep, cont, p_now, cont_up
def force_YFixed_upDS(Fx, Fy, N, x, y, D, Lx, y_bot, y_up, ind_up):
Fup = 0
Fbot = 0
Ep = 0
cont = 0
cont_up = 0
p_now = 0
for nn in np.arange(N):
d_up = y_up-y[nn]
d_bot = y[nn]-y_bot
r_now = 0.5*D[nn]
if ind_up[nn] == 1:
F = -(1-d_up/r_now)/(r_now)
Fup -= F
Fy[nn] += F
Ep += (1/2)*(1-d_up/r_now)**2
#dbg.set_trace()
if d_up<r_now:
cont_up = cont_up+1
cont += 1
if d_bot<r_now:
F = -(1-d_bot/r_now)/(r_now)
Fbot += F
Fy[nn] -= F
Ep += (1/2)*(1-d_bot/r_now)**2
cont += 1
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
dx = x[mm]-x[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, Fup, Fbot, Ep, cont, p_now, cont_up
#@jit
def force_Regular(Fx, Fy, N, x, y, D, Lx, Ly):
Ep = 0
cont = 0
p_now = 0
for nn in np.arange(N):
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
dy = dy-round(dy/Ly)*Ly
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
dx = x[mm]-x[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, Ep, cont, p_now
def MD_UpDownFixed_SD(N, x0, y0, D0, m0, L):
dt = min(D0)/40
Nt = int(1e4)
Ep = np.zeros(Nt)
F_up = np.zeros(Nt)
F_bot = np.zeros(Nt)
F_tot = np.zeros(Nt)
Fup_now = 0
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
#Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
F_up[nt] = Fup_now
F_bot[nt] = Fbot_now
Ep[nt] = Ep_now
vx = np.divide(Fx, m0)
vy = np.divide(Fy, m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
t_end = time.time()
print ("time=%.3e" %(t_end-t_start))
if 1 == 0:
# Plot the amplitide of F
Line_single(range(Nt), F_tot[0:Nt], '-', 't', 'Ftot', 'log', yscale='log')
return x, y
def MD_VibrBot_ForceUp(N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr):
dt = min(D0)/40
Nt = int(5e4)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
#y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))
vx = np.zeros(N)
vy = np.zeros(N)
if 1 == 0:
y_bot = np.zeros(Nt)
vx = np.random.rand(N)
vy = np.random.rand(N)
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
T_set = 1e-6
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now = force_YFixed(Fx, Fy, N, x, y, D0, L[0], y_bot[nt], L[1])
#Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
F_up[nt] = Fup_now
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
freq_now, fft_now = FFT_Fup(Nt, F_up[:Nt], dt, Freq_Vibr)
# Plot the amplitide of F
if 1 == 1:
Line_yy([dt*range(Nt), dt*range(Nt)], [F_up[0:Nt],y_bot[0:Nt]], ['-', ':'], 't', ['$F_{up}$', '$y_{bottom}$'])
Etot = Ep[1:Nt]+Ek[1:Nt]
xdata = [dt*range(Nt), dt*range(Nt), dt*range(Nt-1)]
ydata = [Ep[0:Nt], Ek[0:Nt], Etot]
line_spec = ['--', ':', 'r-']
Line_multi(xdata, ydata, line_spec, 't', '$E$', 'log')
print("std(Etot)=%e\n" %(np.std(Etot)))
#dt2 = 1e-3
#xx = np.arange(0, 5, dt2)
#yy = np.sin(50*xx)+np.sin(125*xx)
#print("dt=%e, w=%f\n" % (dt, Freq_Vibr))
FFT_Fup(Nt, F_up[:Nt], dt, Freq_Vibr)
#FFT_Fup(yy.size, yy, dt2, 50)
return freq_now, fft_now, np.mean(cont)
def MD_Periodic_equi(Nt, N, x0, y0, D0, m0, L, T_set, V_em, n_em):
dt = min(D0)/40
Nt = int(Nt)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
vx_rec = np.zeros([Nt, N])
vy_rec = np.zeros([Nt, N])
vx = np.zeros(N)
vy = np.zeros(N)
for ii in np.arange(n_em):
#for ii in [60]:
ind1 = 2*np.arange(N)
ind2 = ind1+1
vx += V_em[ind1, ii]
vy += V_em[ind2, ii]
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx_rec[nt] = vx
vy_rec[nt] = vy
t_end = time.time()
print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f\n" %(CB_ratio))
#Etot = Ep[1:Nt]+Ek[1:Nt]
#xdata = [dt*range(Nt), dt*range(Nt), dt*range(Nt-1)]
#ydata = [Ep[0:Nt], Ek[0:Nt], Etot]
#line_spec = ['--', ':', 'r-']
#Line_multi(xdata, ydata, line_spec, 't', '$E$', 'log', 'log')
freq_now, fft_now = FFT_vCorr(Nt, N, vx_rec, vy_rec, dt)
return freq_now, fft_now, np.mean(cont)
def MD_YFixed_ConstP_SD(Nt, N, x0, y0, D0, m0, L, F0_up):
dt = D0[0]/40
Nt = int(Nt)
#Nt = int(5e6)
#Nt = int(5e2)
Ep = np.zeros(Nt)
F_up = np.zeros(Nt)
F_bot = np.zeros(Nt)
F_tot = np.zeros(Nt)
Fup_now = 0
y_up = y0[N]
vx = np.zeros(N+1)
vy = np.zeros(N+1)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], 0, y[N])
F_up[nt] = Fup_now+F0_up
F_bot[nt] = Fbot_now
Ep[nt] = Ep_now+(y_up-y[N])*F0_up
vx = 0.1*np.divide(np.append(Fx,0), m0)
vy = 0.1*np.divide(np.append(Fy, F_up[nt]), m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
#print("nt=%d, Fup=%e, Fup_tot=%e\n" % (nt, Fup_now, F_up[nt]))
#dbg.set_trace()
t_end = time.time()
print ("F_tot=%.3e\n" %(F_tot[nt]))
print ("time=%.3e" %(t_end-t_start))
if 1 == 0:
# Plot the amplitide of F
Line_single(range(Nt), F_tot[0:Nt], '-', 't', 'Ftot', 'log', yscale='log')
#Line_single(range(Nt), -F_up[0:Nt], '-', 't', 'Fup', 'log', yscale='log')
#Line_single(range(Nt), Ep[0:Nt], '-', 't', 'Ep', 'log', yscale='linear')
return x, y, p_now
def MD_VibrBot_DispUp_ConstP(mark_upDS, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, F0_up):
dt = D0[0]/40
B = 0.1 # damping coefficient
Nt = int(5e7)
#Nt = int(5e2)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
y_up0 = y_ini[N]
y_up = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
cont_up = np.zeros(Nt)
p = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
#y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))
vx = np.zeros(N+1)
vy = np.zeros(N+1)
# for test
if 1 == 0:
y_bot = np.zeros(Nt)
vx = np.random.rand(N+1)
vx[N] = 0
vy = np.random.rand(N+1)
vy[N] = 0
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
T_set = 1e-6
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N+1)
ay_old = np.zeros(N+1)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
if mark_upDS == 1:
ind_up = np.zeros(N)
for ii in np.arange(N):
d_up = y[N]-y[ii]
r_now = 0.5*D0[ii]
if d_up<r_now:
ind_up[ii] = 1
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
y_up[nt] = y[N]
Fx = np.zeros(N)
Fy = np.zeros(N)
if mark_upDS == 0:
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], y_bot[nt], y[N])
elif mark_upDS == 1:
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed_upDS(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], y_bot[nt], y[N], ind_up)
F_up[nt] = Fup_now+F0_up
Ep[nt] = Ep_now+(y_up0-y[N])*F0_up
cont[nt] = cont_now
cont_up[nt] = cont_up_now
p[nt] = p_now
Fx_all = np.append(Fx,0)-B*vx
Fy_all = np.append(Fy, F_up[nt])-B*vy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
y_up = y_up-y_up0
freq_y, fft_y = FFT_Fup(int(Nt/2), y_up[int(Nt/2):Nt], dt, Freq_Vibr)
#freq_y, fft_y_real, fft_y_imag = FFT_Fup_RealImag(int(Nt/2), y_up[int(Nt/2):Nt], dt, Freq_Vibr)
freq_bot, fft_bot = FFT_Fup(int(Nt/2), y_bot[int(Nt/2):Nt], dt, Freq_Vibr)
# plot the energy to see when the system reaches steady state
if 1 == 0:
Etot = Ep+Ek
nt_start = int(1e3)
xdata = [range(nt_start, Nt), range(nt_start, Nt), range(Nt)]
ydata = [Ep[nt_start:Nt], Ek[nt_start:Nt], Etot]
line_spec = [':', ':', 'r-']
Line_multi(xdata, ydata, line_spec, 't', '$E$', 'linear', 'log')
# Plot the amplitide of F
if 1 == 0:
Line_yy([dt*range(Nt), dt*range(Nt)], [F_up[0:Nt],y_bot[0:Nt]], ['-', ':'], 't', ['$F_{up}$', '$y_{bottom}$'])
Line_yy([dt*range(Nt), dt*range(Nt)], [y_up[0:Nt],y_bot[0:Nt]], ['-', ':'], 't', ['$y_{up}$', '$y_{bottom}$'])
Line_single(range(Nt), p[0:Nt], '-', 't', 'p', 'log', 'linear')
Etot = Ep[1:Nt]+Ek[1:Nt]
xdata = [dt*range(Nt), dt*range(Nt), dt*range(Nt-1)]
ydata = [Ep[0:Nt], Ek[0:Nt], Etot]
line_spec = ['--', ':', 'r-']
#Line_multi(xdata, ydata, line_spec, 't', '$E$', 'log')
print("std(Etot)=%e\n" %(np.std(Etot)))
return freq_y, fft_y, freq_bot, fft_bot, np.mean(cont), np.mean(cont_up)
#return freq_y, fft_y_real, fft_y_imag, freq_bot, fft_bot, np.mean(cont)
def MD_VibrBot_DispUp_ConstP_ConfigRec(N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, F0_up, fn):
dt = D0[0]/40
B = 0.1 # damping coefficient
Nt = int(5e6)
nt_rec = np.linspace(Nt-5e4, Nt, 500)
#Nt = int(1e4)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
ind_nt = 0
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
y_up0 = y_ini[N]
y_up = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
cont_up = np.zeros(Nt)
p = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
#y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))
vx = np.zeros(N+1)
vy = np.zeros(N+1)
ax_old = np.zeros(N+1)
ay_old = np.zeros(N+1)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
if nt == nt_rec[ind_nt]:
ConfigPlot_YFixed_rec(N, x[0:N], y[0:N], D0[0:N], L[0], y[N], y_bot[nt], m0[0:N], ind_nt, fn)
ind_nt += 1
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
y_up[nt] = y[N]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], y_bot[nt], y[N])
F_up[nt] = Fup_now+F0_up
Ep[nt] = Ep_now+(y_up0-y[N])*F0_up
cont[nt] = cont_now
cont_up[nt] = cont_up_now
p[nt] = p_now
Fx_all = np.append(Fx,0)-B*vx
Fy_all = np.append(Fy, F_up[nt])-B*vy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
y_up = y_up-y_up0
freq_y, fft_y = FFT_Fup(int(Nt/2), y_up[int(Nt/2):Nt], dt, Freq_Vibr)
freq_bot, fft_bot = FFT_Fup(int(Nt/2), y_bot[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_y, fft_y, freq_bot, fft_bot, np.mean(cont), np.mean(cont_up)
def MD_VibrBot_DispUp_ConstP_EkCheck(Nt, mark_upDS, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, F0_up):
dt = D0[0]/40
B = 0.1 # damping coefficient
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
Ek_now = np.array(0)
Ek_up_now = np.array(0)
Ep_now = np.array(0)
Ep_up_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ep_up = np.zeros(Nt)
Ek = np.zeros(Nt)
Ek_up = np.zeros(Nt)
y_up0 = y_ini[N]
y_up = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
cont_up = np.zeros(Nt)
p = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vx = np.zeros(N+1)
vy = np.zeros(N+1)
ax_old = np.zeros(N+1)
ay_old = np.zeros(N+1)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
if mark_upDS == 1:
ind_up = np.zeros(N)
for ii in np.arange(N):
d_up = y[N]-y[ii]
r_now = 0.5*D0[ii]
if d_up<r_now:
ind_up[ii] = 1
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
y_up[nt] = y[N]
Fx = np.zeros(N)
Fy = np.zeros(N)
if mark_upDS == 0:
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], y_bot[nt], y[N])
elif mark_upDS == 1:
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed_upDS(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], y_bot[nt], y[N], ind_up)
F_up[nt] = Fup_now+F0_up
Ep[nt] = Ep_now+(y_up0-y[N])*F0_up
Ep_up[nt] = (y_up0-y[N])*F0_up
cont[nt] = cont_now
cont_up[nt] = cont_up_now
p[nt] = p_now
Fx_all = np.append(Fx,0)-B*vx
Fy_all = np.append(Fy, F_up[nt])-B*vy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_up[nt] = 0.5*m0[N]*(vx[N]**2+vy[N]**2)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ek_up_now = np.append(Ek_up_now, np.mean(Ek_up[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
Ep_up_now = np.append(Ep_up_now, np.mean(Ep_up[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
y_up = y_up-np.mean(y_up)
y_up = y_up/np.mean(np.absolute(y_up))
freq_y, fft_y = FFT_Fup(int(Nt/2), y_up[int(Nt/2):Nt], dt, Freq_Vibr)
freq_bot, fft_bot = FFT_Fup(int(Nt/2), y_bot[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_y, fft_y, freq_bot, fft_bot, np.mean(cont), np.mean(cont_up)
#@jit
def force_YFixed_collision_ConstP(beta, Fx, Fy, N, x, y, vx, vy, D, Lx, y_bot, v_bot, y_up):
Fup = 0
Fbot = 0
Ep = 0
cont = 0
cont_up = 0
p_now = 0
#betta = 1
for nn in np.arange(N):
d_up = y_up-y[nn]
d_bot = y[nn]-y_bot
r_now = 0.5*D[nn]
if d_up<r_now:
F = -(1-d_up/r_now)/(r_now)
Fup -= F
Fy[nn] += F
dvy = vy[N]-vy[nn]
FD = beta*dvy
#FD = np.absolute(FD)
Fy[nn] += FD
Fup -= FD
Ep += (1/2)*(1-d_up/r_now)**2
cont_up += 1
cont += 1
#dbg.set_trace()
if d_bot<r_now:
F = -(1-d_bot/r_now)/(r_now)
Fbot += F
Fy[nn] -= F
dvy = v_bot-vy[nn]
FD = beta*dvy
Fy[nn] += FD
Ep += (1/2)*(1-d_bot/r_now)**2
cont += 1
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
dx = x[mm]-x[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
dvx = vx[mm]-vx[nn]
dvy = vy[mm]-vy[nn]
FD = beta*(dvx*dx+dvy*dy)/dmn
#FD = np.absolute(FD)
Fx[nn] += FD*dx/dmn
Fx[mm] -= FD*dx/dmn
Fy[nn] += FD*dy/dmn
Fy[mm] -= FD*dy/dmn
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, Fup, Fbot, Ep, cont, p_now, cont_up
def MD_VibrBot_DispUp_ConstP_EkCheck_Collision(beta, Nt, mark_upDS, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, F0_up, mark_norm):
dt = D0[0]/40
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
Ek_now = np.array(0)
Ek_up_now = np.array(0)
Ep_now = np.array(0)
Ep_up_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ep_up = np.zeros(Nt)
Ek = np.zeros(Nt)
Ek_up = np.zeros(Nt)
y_up0 = y_ini[N]
y_up = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
cont_up = np.zeros(Nt)
p = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vy_bot = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)
vx = np.zeros(N+1)
vy = np.zeros(N+1)
ax_old = np.zeros(N+1)
ay_old = np.zeros(N+1)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
if mark_upDS == 1:
ind_up = np.zeros(N)
for ii in np.arange(N):
d_up = y[N]-y[ii]
r_now = 0.5*D0[ii]
if d_up<r_now:
ind_up[ii] = 1
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
y_up[nt] = y[N]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed_collision_ConstP(beta, Fx, Fy, N, x, y, vx, vy, D0[0:N], L[0], y_bot[nt], vy_bot[nt], y[N])
F_up[nt] = Fup_now+F0_up
Ep[nt] = Ep_now+(y_up0-y[N])*F0_up
Ep_up[nt] = (y_up0-y[N])*F0_up
cont[nt] = cont_now
cont_up[nt] = cont_up_now
p[nt] = p_now
Fx_all = np.append(Fx,0)
Fy_all = np.append(Fy, F_up[nt])
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_up[nt] = 0.5*m0[N]*(vx[N]**2+vy[N]**2)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ek_up_now = np.append(Ek_up_now, np.mean(Ek_up[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
Ep_up_now = np.append(Ep_up_now, np.mean(Ep_up[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
y_up = y_up-np.mean(y_up)
if mark_norm == 1:
y_up = y_up/np.mean(np.absolute(y_up))
freq_y, fft_y = FFT_Fup(int(Nt/2), y_up[int(Nt/2):Nt], dt, Freq_Vibr)
freq_bot, fft_bot = FFT_Fup(int(Nt/2), y_bot[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_y, fft_y, fft_bot, np.mean(cont), np.mean(cont_up), nt_rec[1:], Ek_now[1:],Ek_up_now[1:],Ep_now[1:],Ep_up_now[1:]
def MD_YFixed_ConstP_Gravity_SD(N, x0, y0, D0, m0, L, F0_up):
g = 1e-5
dt = D0[0]/40
Nt = int(5e6)
#Nt = int(1e4)
Ep = np.zeros(Nt)
F_up = np.zeros(Nt)
F_bot = np.zeros(Nt)
F_tot = np.zeros(Nt)
Fup_now = 0
y_up = y0[N]
vx = np.zeros(N+1)
vy = np.zeros(N+1)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], 0, y[N])
Fy -= g*m0[0:N]
F_up[nt] = Fup_now+F0_up-g*m0[N]
F_bot[nt] = Fbot_now
Ep[nt] = Ep_now+(y_up-y[N])*F0_up+sum(g*np.multiply(m0, y-y0))
vx = 0.1*np.divide(np.append(Fx,0), m0)
vy = 0.1*np.divide(np.append(Fy, F_up[nt]), m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
#print("nt=%d, Fup=%e, Fup_tot=%e\n" % (nt, Fup_now, F_up[nt]))
#dbg.set_trace()
t_end = time.time()
print ("F_tot=%.3e\n" %(F_tot[nt]))
print ("time=%.3e" %(t_end-t_start))
return x, y, p_now
def MD_VibrBot_DispUp_ConstP_EkCheck_Gravity(Nt, mark_upDS, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, F0_up):
dt = D0[0]/40
#B = 0.1 # damping coefficient
g = 1e-5
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
Ek_now = np.array(0)
Ek_up_now = np.array(0)
Ep_now = np.array(0)
Ep_up_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ep_up = np.zeros(Nt)
Ek = np.zeros(Nt)
Ek_up = np.zeros(Nt)
y_up0 = y_ini[N]
y_up = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
cont_up = np.zeros(Nt)
p = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vy_bot = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)
vx = np.zeros(N+1)
vy = np.zeros(N+1)
ax_old = np.zeros(N+1)
ay_old = np.zeros(N+1)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
if mark_upDS == 1:
ind_up = np.zeros(N)
for ii in np.arange(N):
d_up = y[N]-y[ii]
r_now = 0.5*D0[ii]
if d_up<r_now:
ind_up[ii] = 1
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
y_up[nt] = y[N]
Fx = np.zeros(N)
Fy = np.zeros(N)
#Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed(Fx, Fy, N, x[0:N], y[0:N], D0[0:N], L[0], y_bot[nt], y[N])
beta = 1
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed_collision_ConstP(beta, Fx, Fy, N, x, y, vx, vy, D0[0:N], L[0], y_bot[nt], vy_bot[nt], y[N])
F_up[nt] = Fup_now+F0_up
Ep[nt] = Ep_now+(y_up0-y[N])*F0_up+sum(g*np.multiply(m0, y-y_ini))
Ep_up[nt] = (y_up0-y[N])*F0_up
cont[nt] = cont_now
cont_up[nt] = cont_up_now
p[nt] = p_now
#Fx_all = np.append(Fx,0)-B*vx
#Fy_all = np.append(Fy, F_up[nt])-B*vy-g*m0
Fx_all = np.append(Fx,0)
Fy_all = np.append(Fy, F_up[nt])-g*m0
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_up[nt] = 0.5*m0[N]*(vx[N]**2+vy[N]**2)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ek_up_now = np.append(Ek_up_now, np.mean(Ek_up[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
Ep_up_now = np.append(Ep_up_now, np.mean(Ep_up[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
y_up = y_up-np.mean(y_up)
#y_up = y_up/np.mean(np.absolute(y_up))
freq_y, fft_y = FFT_Fup(int(Nt/2), y_up[int(Nt/2):Nt], dt, Freq_Vibr)
freq_bot, fft_bot = FFT_Fup(int(Nt/2), y_bot[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_y, fft_y, fft_bot, np.mean(cont), np.mean(cont_up), nt_rec[1:], Ek_now[1:],Ek_up_now[1:],Ep_now[1:],Ep_up_now[1:]
def MD_YFixed_ConstV_SP_SD(Nt, N, x0, y0, D0, m0, Lx, Ly):
dt = D0[0]/40
Nt = int(Nt)
Ep = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Ep[nt] = Ep_now
vx = 0.1*np.divide(Fx, m0)
vy = 0.1*np.divide(Fy, m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
t_end = time.time()
print ("F_tot=%.3e" %(F_tot[nt]))
print ("time=%.3e" %(t_end-t_start))
plt.figure(figsize=(6.4,4.8))
plt.plot(range(Nt), F_tot[0:Nt], color='blue')
ax = plt.gca()
ax.set_yscale('log')
plt.xlabel("t")
plt.ylabel("F_total")
plt.title("Finding the Equilibrium", fontsize='small')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.tight_layout()
plt.show()
return x, y, p_now
def MD_YFixed_ConstV_SP_SD_2(Nt, N, x0, y0, D0, m0, Lx, Ly):
dt = D0[0]/40
Nt = int(Nt)
Ep = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Ep[nt] = Ep_now
vx = 0.1*np.divide(Fx, m0)
vy = 0.1*np.divide(Fy, m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
# putting a threshold on total force
if (F_tot[nt]<1e-11):
break
t_end = time.time()
#print ("F_tot=%.3e" %(F_tot[nt]))
#print ("time=%.3e" %(t_end-t_start))
return x, y, p_now
#@jit
def force_YFixed_collision_ConstV(beta, Fx, Fy, N, x, y, vx, vy, D, Lx, y_bot, y_up):
Ep = 0
cont = 0
p_now = 0
for nn in np.arange(N):
d_up = y_up-y[nn]
d_bot = y[nn]-y_bot
r_now = 0.5*D[nn]
if d_up<r_now:
F = -(1-d_up/r_now)/(r_now)
Fy[nn] += F
dvy = -vy[nn]
FD = beta*dvy
Fy[nn] += FD
Ep += (1/2)*(1-d_up/r_now)**2
cont += 1
#dbg.set_trace()
if d_bot<r_now:
F = -(1-d_bot/r_now)/(r_now)
Fy[nn] -= F
dvy = -vy[nn]
FD = beta*dvy
Fy[nn] += FD
Ep += (1/2)*(1-d_bot/r_now)**2
cont += 1
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
dx = x[mm]-x[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
dvx = vx[mm]-vx[nn]
dvy = vy[mm]-vy[nn]
FD = beta*(dvx*dx+dvy*dy)/dmn
#FD = np.absolute(FD)
Fx[nn] += FD*dx/dmn
Fx[mm] -= FD*dx/dmn
Fy[nn] += FD*dy/dmn
Fy[mm] -= FD*dy/dmn
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, Ep, cont, p_now
def MD_VibrSP_ConstV_Collision(beta, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, ind_in, ind_out, mark_vibrY):
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in]
vx_in = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt))
elif mark_vibrY == 1:
y_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in]
vy_in = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt))
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 0:
x[ind_in] = x_in[nt]
y[ind_in] = y_ini[ind_in]
vx[ind_in] = vx_in[nt]
vy[ind_in] = 0
elif mark_vibrY == 1:
x[ind_in] = x_ini[ind_in]
y[ind_in] = y_in[nt]
vx[ind_in] = 0
vy[ind_in] = vy_in[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_YFixed_collision_ConstV(beta, Fx, Fy, N, x, y, vx, vy, D0, L[0], 0, L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx
Fy_all = Fy
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = np.array(0)
Ep_now = np.array(0)
cont_now = np.array(0)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now = np.append(cont_now, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
cont_now[0] = cont_now[1]
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
if mark_vibrY == 0:
freq_fft, fft_in = FFT_Fup(int(Nt/2), x_in[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in = FFT_Fup(int(Nt/2), y_in[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_fft, fft_in, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_VibrSP_ConstV(B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, ind_in, ind_out, mark_vibrY, mark_resonator):
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in]
elif mark_vibrY == 1:
y_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in]
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 0:
x[ind_in] = x_in[nt]
y[ind_in] = y_ini[ind_in]
elif mark_vibrY == 1:
x[ind_in] = x_ini[ind_in]
y[ind_in] = y_in[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx-B*vx
Fy_all = Fy-B*vy
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = np.array(0)
Ep_now = np.array(0)
cont_now = np.array(0)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now = np.append(cont_now, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
cont_now[0] = cont_now[1]
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
if mark_vibrY == 0:
freq_fft, fft_in = FFT_Fup(int(Nt/2), x_in[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in = FFT_Fup(int(Nt/2), y_in[int(Nt/2):Nt], dt, Freq_Vibr)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
if Nt == 5e5:
print(x[ind_out], y[ind_out])
print(fft_x_out[100], fft_y_out[100])
print(fft_in[100])
return freq_fft, fft_in, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_Periodic_ConstV_SP_SD(Nt, N, x0, y0, D0, m0, Lx, Ly):
dt = D0[0]/40
Nt = int(Nt)
Ep = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, Lx, Ly)
Ep[nt] = Ep_now
vx = 0.1*np.divide(Fx, m0)
vy = 0.1*np.divide(Fy, m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
t_end = time.time()
print ("F_tot=%.3e\n" %(F_tot[nt]))
print ("nt=%e, time=%.3e" %(nt, t_end-t_start))
return x, y, p_now
def MD_Periodic_equi_Ekcheck(Nt, N, x0, y0, D0, m0, L, T_set, V_em, n_em):
dt = min(D0)/40
Nt = int(Nt)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
vx_rec = np.zeros([Nt, N])
vy_rec = np.zeros([Nt, N])
nt_rec = np.linspace(0, Nt, int(Nt/1e3)+1)
#nt_rec = np.linspace(0, Nt, int(Nt/1e2)+1)
nt_rec = nt_rec.astype(int)
Ek_now = np.array(0)
Ep_now = np.array(0)
vx = np.zeros(N)
vy = np.zeros(N)
for ii in np.arange(n_em):
ind1 = 2*np.arange(N)
ind2 = ind1+1
vx += V_em[ind1, ii]
vy += V_em[ind2, ii]
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx_rec[nt] = vx
vy_rec[nt] = vy
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f\n" %(CB_ratio))
freq_now, fft_now = FFT_vCorr(int(Nt/2), N, vx_rec[int(Nt/2):Nt], vy_rec[int(Nt/2):Nt], dt)
return freq_now, fft_now, np.mean(cont), nt_rec, Ek_now, Ep_now
#@jit
def force_Xfixed(Fx, Fy, N, x, y, D, x_l, x_r, Ly, ind_wall):
F_l = 0
F_r = 0
Ep = 0
cont = 0
p_now = 0
for nn in np.arange(N):
d_l = x[nn]-x_l
d_r = x_r-x[nn]
r_now = 0.5*D[nn]
if (ind_wall[nn]==0) and (d_r<r_now):
F = -(1-d_r/r_now)/(r_now)
F_r -= F
Fx[nn] += F
Ep += (1/2)*(1-d_r/r_now)**2
cont += 1
#dbg.set_trace()
if (ind_wall[nn]==0) and (d_l<r_now):
F = -(1-d_l/r_now)/(r_now)
F_l += F
Fx[nn] -= F
Ep += (1/2)*(1-d_l/r_now)**2
cont += 1
for mm in np.arange(nn+1, N):
dx = x[mm]-x[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dx) < Dmn:
dy = y[mm]-y[nn]
dy = dy-round(dy/Ly)*Ly
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, F_l, F_r, Ep, cont, p_now
def MD_Xfixed_SD(Nt, N, x0, y0, D0, m0, Lx, Ly, ind_wall):
wall = np.where(ind_wall>0)
dt = D0[0]/40
Nt = int(Nt)
#Nt = int(5e6)
#Nt = int(5e2)
Ep = np.zeros(Nt)
F_l = np.zeros(Nt)
F_r = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fl_now, Fr_now, Ep_now, cont_now, p_now = force_Xfixed(Fx, Fy, N, x, y, D0, 0, Lx, Ly, ind_wall)
F_l[nt] = Fl_now
F_r[nt] = Fr_now
Ep[nt] = Ep_now
Fx[wall] = 0
Fy[wall] = 0
vx = 0.1*np.divide(Fx, m0)
vy = 0.1*np.divide(Fy, m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
#print("nt=%d, Fup=%e, Fup_tot=%e\n" % (nt, Fup_now, F_up[nt]))
#dbg.set_trace()
t_end = time.time()
print ("F_tot=%.3e" %(F_tot[nt]))
#print ("Ep_tot=%.3e\n" %(Ep[nt]))
print ("time=%.3e" %(t_end-t_start))
return x, y, p_now
def MD_VibrWall_DiffP_Xfixed(Nt, N, x_ini, y_ini,D0, m0, Lx, Ly, Freq_Vibr, Amp_Vibr, ind_wall, B):
dt = D0[0]/40
# B damping coefficient
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
Ek_now = np.array(0)
Ep_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
x_l = np.zeros(Nt)
F_r = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_l = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
wall_l = np.where(ind_wall==1)
wall_r = np.where(ind_wall==2)
wall = np.where(ind_wall>0)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
x[wall_l] = x_l[nt]
Fx, Fy, Fl_now, Fr_now, Ep_now, cont_now, p_now = force_Xfixed(Fx, Fy, N, x, y, D0, x_l[nt], Lx, Ly, ind_wall)
F_r[nt] = Fr_now+sum(Fx[wall_r])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx-B*vx
Fy_all = Fy-B*vy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax[wall] = 0
ay[wall] = 0
vx[wall] = 0
vy[wall] = 0
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
#for ii in np.arange(len(nt_rec)-1):
# Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
# Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
#CB_ratio = min(cont)/max(cont)
#print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
freq_fft, fft_receive = FFT_Fup(int(Nt/2), F_r[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_drive = FFT_Fup(int(Nt/2), x_l[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_fft, fft_receive, fft_drive, cont_now, nt_rec, Ek_now, Ep_now
#@jit
def force_XFixed_collision_VibrLx(beta, Fx, Fy, N, x, y, vx, vy, D, x_l, Lx, Ly, vx_l, ind_wall):
Fr = 0
Fl = 0
Ep = 0
cont = 0
p_now = 0
#betta = 1
for nn in np.arange(N):
if ind_wall[nn] == 0:
d_r = Lx-x[nn]
d_l = x[nn]-x_l
r_now = 0.5*D[nn]
if d_r<r_now:
F = -(1-d_r/r_now)/(r_now)
Fr -= F
Fx[nn] += F
dvx = -vx[nn]
FD = beta*dvx
Fx[nn] += FD
Fr -= FD
Ep += (1/2)*(1-d_r/r_now)**2
cont += 1
#dbg.set_trace()
if d_l<r_now:
F = -(1-d_l/r_now)/(r_now)
Fl += F
Fx[nn] -= F
dvx = vx_l-vx[nn]
FD = beta*dvx
Fx[nn] += FD
Ep += (1/2)*(1-d_l/r_now)**2
cont += 1
for mm in np.arange(nn+1, N):
dx = x[mm]-x[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dx) < Dmn:
dy = y[mm]-y[nn]
dy = dy-round(dy/Ly)*Ly
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
F = -(1-dmn/Dmn)/Dmn/dmn
Fx[nn] += F*dx
Fx[mm] -= F*dx
Fy[nn] += F*dy
Fy[mm] -= F*dy
dvx = vx[mm]-vx[nn]
dvy = vy[mm]-vy[nn]
FD = beta*(dvx*dx+dvy*dy)/dmn
#FD = np.absolute(FD)
Fx[nn] += FD*dx/dmn
Fx[mm] -= FD*dx/dmn
Fy[nn] += FD*dy/dmn
Fy[mm] -= FD*dy/dmn
Ep += (1/2)*(1-dmn/Dmn)**2
cont += 1
p_now += (-F)*(dx**2+dy**2)
return Fx, Fy, Fl, Fr, Ep, cont, p_now
def MD_VibrWall_DiffP_Xfixed_Collision(Nt, N, x_ini, y_ini,D0, m0, Lx, Ly, Freq_Vibr, Amp_Vibr, ind_wall, beta):
dt = D0[0]/40
# B damping coefficient
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
Ek_now = np.array(0)
Ep_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
x_l = np.zeros(Nt)
F_r = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_l = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vx_l = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)
wall_l = np.where(ind_wall==1)
wall_r = np.where(ind_wall==2)
wall = np.where(ind_wall>0)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
x[wall_l] = x_l[nt]
vx[wall_l] = vx_l[nt]
Fx, Fy, Fl_now, Fr_now, Ep_now, cont_now, p_now = force_XFixed_collision_VibrLx(beta, Fx, Fy, N, x, y, vx, vy, D0, x_l[nt], Lx, Ly, vx_l[nt], ind_wall)
F_r[nt] = Fr_now+sum(Fx[wall_r])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx
Fy_all = Fy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax[wall] = 0
ay[wall] = 0
vx[wall] = 0
vy[wall] = 0
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
freq_fft, fft_receive = FFT_Fup(int(Nt/2), F_r[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_drive = FFT_Fup(int(Nt/2), x_l[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_fft, fft_receive, fft_drive, cont_now, nt_rec, Ek_now, Ep_now
def MD_VibrWall_LySignal_Collision(Nt, N, x_ini, y_ini,D0, m0, Lx0, Ly0, Freq_Vibr, Amp_Vibr, ind_wall, beta, dLy_scheme, num_gap):
dt = D0[0]/40
# B damping coefficient
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
dLy_max = 0.1
nt_transition = int(Nt/num_gap/20)
dLy_inc = np.linspace(0, dLy_max, nt_transition)
dLy_dec = np.linspace(dLy_max, 0, nt_transition)
if dLy_scheme == 0:
dLy_all = np.zeros(Nt)
elif dLy_scheme == 1:
dLy_all = np.ones(Nt)*dLy_max
dLy_all[0:nt_transition] = dLy_inc
elif dLy_scheme == 2:
dLy_all = np.zeros(Nt)
nt_Ly = np.linspace(0, Nt, num_gap+1)
nt_Ly = nt_Ly.astype(int)
for ii in np.arange(1, num_gap):
nt1 = nt_Ly[ii]-int(nt_transition/2)
nt2 = nt_Ly[ii]+int(nt_transition/2)
if ii%2 == 1:
dLy_all[nt_Ly[ii]:nt_Ly[ii+1]] = dLy_max
dLy_all[nt1:nt2] = dLy_inc
else:
dLy_all[nt1:nt2] = dLy_dec
nt_rec = np.linspace(0, Nt, int(Nt/5e4*num_gap/5)+1)
Ek_now = np.array(0)
Ep_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
x_l = np.zeros(Nt)
F_r = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_l = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vx_l = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)
wall_l = np.where(ind_wall==1)
wall_r = np.where(ind_wall==2)
wall = np.where(ind_wall>0)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
for nt in np.arange(Nt):
Ly = Ly0+dLy_all[nt]
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
x[wall_l] = x_l[nt]
vx[wall_l] = vx_l[nt]
Fx, Fy, Fl_now, Fr_now, Ep_now, cont_now, p_now = force_XFixed_collision_VibrLx(beta, Fx, Fy, N, x, y, vx, vy, D0, x_l[nt], Lx0, Ly, vx_l[nt], ind_wall)
F_r[nt] = Fr_now+sum(Fx[wall_r])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx
Fy_all = Fy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax[wall] = 0
ay[wall] = 0
vx[wall] = 0
vy[wall] = 0
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
nt_dLy = np.arange(0, Nt, 100)
return nt_dLy, dLy_all[nt_dLy], F_r, nt_rec, Ek_now, Ep_now
def MD_VibrWall_LySignal(Nt, N, x_ini, y_ini,D0, m0, Lx0, Ly0, Freq_Vibr, Amp_Vibr, ind_wall, B, dLy_scheme, num_gap):
dt = D0[0]/40
# B damping coefficient
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
dLy_max = 0.1
nt_transition = int(Nt/num_gap/20)
dLy_inc = np.linspace(0, dLy_max, nt_transition)
dLy_dec = np.linspace(dLy_max, 0, nt_transition)
if dLy_scheme == 0:
dLy_all = np.zeros(Nt)
elif dLy_scheme == 1:
dLy_all = np.ones(Nt)*dLy_max
dLy_all[0:nt_transition] = dLy_inc
elif dLy_scheme == 2:
dLy_all = np.zeros(Nt)
nt_Ly = np.linspace(0, Nt, num_gap+1)
nt_Ly = nt_Ly.astype(int)
for ii in np.arange(1, num_gap):
nt1 = nt_Ly[ii]-int(nt_transition/2)
nt2 = nt_Ly[ii]+int(nt_transition/2)
if ii%2 == 1:
dLy_all[nt_Ly[ii]:nt_Ly[ii+1]] = dLy_max
dLy_all[nt1:nt2] = dLy_inc
else:
dLy_all[nt1:nt2] = dLy_dec
nt_rec = np.linspace(0, Nt, int(Nt/5e4*num_gap/5)+1)
Ek_now = np.array(0)
Ep_now = np.array(0)
#nt_rec = np.linspace(0.5*Nt, Nt, 50)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
x_l = np.zeros(Nt)
F_r = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_l = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vx_l = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)
wall_l = np.where(ind_wall==1)
wall_r = np.where(ind_wall==2)
wall = np.where(ind_wall>0)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
for nt in np.arange(Nt):
Ly = Ly0+dLy_all[nt]
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
x[wall_l] = x_l[nt]
vx[wall_l] = vx_l[nt]
Fx, Fy, Fl_now, Fr_now, Ep_now, cont_now, p_now = force_Xfixed(Fx, Fy, N, x, y, D0, x_l[nt], Lx0, Ly, ind_wall)
F_r[nt] = Fr_now+sum(Fx[wall_r])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx-B*vx
Fy_all = Fy-B*vy
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax[wall] = 0
ay[wall] = 0
vx[wall] = 0
vy[wall] = 0
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
nt_dLy = np.arange(0, Nt, 100)
return nt_dLy, dLy_all[nt_dLy], F_r, nt_rec, Ek_now, Ep_now
def MD_VibrBot_FSignal_Collision(beta, Nt, N, x_ini, y_ini, D0, m0, Lx, Freq_Vibr, Amp_Vibr, F_scheme, num_gap):
dt = D0[0]/40
Nt = int(Nt)
#Nt = int(5e7)
#Nt = int(1e4)
F_max = 0.01
F_min = 1e-8
nt_transition = int(Nt/num_gap/20)
F_inc = np.linspace(F_min, F_max, nt_transition)
F_dec = np.linspace(F_max, F_min, nt_transition)
if F_scheme == 1:
F_all = np.ones(Nt)*F_max
elif F_scheme == 0:
F_all = np.ones(Nt)*F_min
F_all[0:nt_transition] = F_dec
elif F_scheme == 2:
F_all = np.ones(Nt)*F_max
nt_F = np.linspace(0, Nt, num_gap+1)
nt_F = nt_F.astype(int)
for ii in np.arange(1, num_gap):
nt1 = nt_F[ii]-int(nt_transition/2)
nt2 = nt_F[ii]+int(nt_transition/2)
if ii%2 == 1:
F_all[nt_F[ii]:nt_F[ii+1]] = F_min
F_all[nt1:nt2] = F_dec
else:
F_all[nt1:nt2] = F_inc
nt_rec = np.linspace(0, Nt, int(Nt/5e4*num_gap/5)+1)
Ek_now = np.array(0)
Ep_now = np.array(0)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
y_up = np.zeros(Nt)
F_up = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
y_bot = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)+Amp_Vibr
vy_bot = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt)+1.5*np.pi)
vx = np.zeros(N+1)
vy = np.zeros(N+1)
ax_old = np.zeros(N+1)
ay_old = np.zeros(N+1)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
y_up[nt] = y[N]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up_now = force_YFixed_collision_ConstP(beta, Fx, Fy, N, x, y, vx, vy, D0[0:N], Lx, y_bot[nt], vy_bot[nt], y[N])
F_up[nt] = Fup_now-F_all[nt]
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = np.append(Fx,0)
Fy_all = np.append(Fy, F_up[nt])
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek_up = 0.5*m0[N]*(vx[N]**2+vy[N]**2)
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))-Ek_up
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
print ("freq=%f, cont_min=%d, cont_max=%d, cont_ave=%f\n" %(Freq_Vibr, min(cont), max(cont), np.mean(cont)))
nt_F = np.arange(0, Nt, 100)
return nt_F, F_all[nt_F], y_up, nt_rec, Ek_now, Ep_now
def MD_SPSignal(mark_collision, beta, Nt, N, x_ini, y_ini,D0, m0, Lx, Ly, Freq_Vibr, Amp_Vibr, ind_in, ind_out, ind_fix, dr_scheme, num_gap, mark_vibrY, dr_one, dr_two):
dt = D0[0]/40
Nt = int(Nt)
d_ini = D0[0]
d0 = 0.1
dr_all = np.zeros(Nt)+dr_one
if abs(dr_scheme) <= 2:
nt_dr = np.linspace(0, Nt, 3)
nt_dr = nt_dr.astype(int)
dr_all[nt_dr[1]:nt_dr[2]] = dr_two
num_gap = 5
elif dr_scheme == 3 or dr_scheme == 4:
nt_dr = np.linspace(0, Nt, num_gap+1)
nt_dr = nt_dr.astype(int)
for ii in np.arange(1, num_gap, 2):
dr_all[nt_dr[ii]:nt_dr[ii+1]] = dr_two
D_fix = d_ini+dr_all*d_ini
nt_rec = np.linspace(0, Nt, int(Nt/5e4*num_gap/5)+1)
Ek_rec = np.array(0)
Ep_rec = np.array(0)
cont_rec = np.array(0)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 1:
y_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in]
vy_in = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt))
else:
x_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in]
vx_in = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt))
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
D0[ind_fix] = D_fix[nt]
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 1:
y[ind_in] = y_in[nt]
x[ind_in] = x_ini[ind_in]
vy[ind_in] = vy_in[nt]
vx[ind_in] = 0
else:
x[ind_in] = x_in[nt]
y[ind_in] = y_ini[ind_in]
vx[ind_in] = vx_in[nt]
vy[ind_in] = 0
Fx = np.zeros(N)
Fy = np.zeros(N)
if mark_collision == 1:
Fx, Fy, Ep_now, cont_now, p_now = force_YFixed_collision_ConstV(beta, Fx, Fy, N, x, y, vx, vy, D0, Lx, 0, Ly)
Fx_all = Fx
Fy_all = Fy
else:
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Fx_all = Fx-beta*vx
Fy_all = Fy-beta*vy
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if nt % 2000 == 0:
print ("nt = %d, Ek = %.2e, cont = %.2e" %(nt, Ek[nt], cont[nt]))
for ii in np.arange(len(nt_rec)-1):
Ek_rec = np.append(Ek_rec, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec = np.append(Ep_rec, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec = np.append(cont_rec, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
print ("freq=%f, cont_min=%d, cont_max=%d, cont_ave=%f\n" %(Freq_Vibr, min(cont), max(cont), np.mean(cont)))
nt_dr = np.arange(0, Nt, 100)
if mark_vibrY == 1:
xy_out = y_out
else:
xy_out = x_out
return nt_dr, dr_all[nt_dr], xy_out, nt_rec, Ek_rec, Ep_rec, cont_rec
def MD_YFixed_equi_SP_modecheck(Nt, N, x0, y0, D0, m0, Lx, Ly, T_set, V_em, n_em, ind_out):
dt = min(D0)/40
Nt = int(Nt)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = []
Ep_rec = []
cont_rec = []
vx = np.zeros(N)
vy = np.zeros(N)
for ii in np.arange(n_em):
ind1 = 2*np.arange(N)
ind2 = ind1+1
vx += V_em[ind1, ii]
vy += V_em[ind2, ii]
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_rec.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[1:] + nt_rec[:-1]) / 2
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f\n" %(CB_ratio))
Freq_Vibr = 0
freq_x, fft_x = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_y, fft_y = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
ind1 = freq_x<30
ind2 = freq_y<30
return freq_x[ind1], freq_y[ind2], fft_x[ind1], fft_y[ind2], np.mean(cont), nt_rec, Ek_rec, Ep_rec, cont_rec
def MD_YFixed_SPVibr_SP_modecheck(Nt, N, x0, y0, D0, m0, Lx, Ly, T_set, ind_in, ind_out, mark_vibrY):
dt = min(D0)/40
Nt = int(Nt)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = np.array(0)
Ep_rec = np.array(0)
cont_rec = np.array(0)
vx = np.zeros(N)
vy = np.zeros(N)
if mark_vibrY == 1:
vy[ind_in] = 1
vy_mc = sum(np.multiply(vy,m0))/sum(m0)
vy = vy-vy_mc
else:
vx[ind_in] = 1
vx_mc = sum(np.multiply(vx,m0))/sum(m0)
vx = vx-vx_mc
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if mark_vibrY == 1:
vy = vy*np.sqrt(N*T_set/T_rd)
print("|vy|_Max=%.3e, |vy|_Min=%.3e" %(max(abs(vy)), min(abs(vy))))
else:
vx = vx*np.sqrt(N*T_set/T_rd)
print("|vx|_Max=%.3e, |vx|_Min=%.3e" %(max(abs(vx)), min(abs(vx))))
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
mark_CB = 0
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Ep[nt] = Ep_now
cont[nt] = cont_now
if mark_CB == 0 and cont_now<cont[0]:
print("nt_CB=%d" % nt)
mark_CB = 1
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_rec = np.append(Ek_rec, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec = np.append(Ep_rec, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec = np.append(cont_rec, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f\n" %(CB_ratio))
Freq_Vibr = 0
freq_x, fft_x = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_y, fft_y = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
ind1 = freq_x<30
ind2 = freq_y<30
return freq_x[ind1], freq_y[ind2], fft_x[ind1], fft_y[ind2], cont_rec, nt_rec, Ek_rec, Ep_rec
#181105
def MD_YFixed_SPVibr_vCorr_modecheck(Nt_MD, Nt_FFT, N, x0, y0, D0, m0, Lx, Ly, T_set, ind_in, ind_out, mark_vibrY):
N = int(N)
Nt_FFT = int(Nt_FFT)
Nt_MD = int(Nt_MD)
dt = min(D0)/40
Nt = Nt_MD+Nt_FFT
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
mark_FFT = np.zeros(Nt)
mark_FFT[Nt_MD:Nt] = 1
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = []
Ep_rec = []
cont_rec = []
vx = np.zeros(N)
vy = np.zeros(N)
if mark_vibrY == 1:
vy[ind_in] = 1
vy_mc = sum(np.multiply(vy,m0))/sum(m0)
vy = vy-vy_mc
else:
vx[ind_in] = 1
vx_mc = sum(np.multiply(vx,m0))/sum(m0)
vx = vx-vx_mc
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if mark_vibrY == 1:
vy = vy*np.sqrt(N*T_set/T_rd)
print("|vy|_Max=%.3e, |vy|_Min=%.3e" %(max(abs(vy)), min(abs(vy))))
else:
vx = vx*np.sqrt(N*T_set/T_rd)
print("|vx|_Max=%.3e, |vx|_Min=%.3e" %(max(abs(vx)), min(abs(vx))))
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if mark_FFT[nt] == 1:
if mark_FFT[nt-1] == 0:
nt_ref = nt
vx_rec = np.zeros([Nt_FFT, N])
vy_rec = np.zeros([Nt_FFT, N])
nt_delta = nt-nt_ref
vx_rec[nt_delta] = vx
vy_rec[nt_delta] = vy
if nt_delta == Nt_FFT-1:
freq_now, fft_now = FFT_vCorr(Nt_FFT, N, vx_rec, vy_rec, dt)
print ("Nt_End="+str(nt))
for ii in np.arange(len(nt_rec)-1):
Ek_rec.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f" %(CB_ratio))
return freq_now, fft_now, (nt_rec[:-1]+nt_rec[1:])/2, Ek_rec, Ep_rec, cont_rec
def MD_YFixed_ConstV(B, Nt, N, x0, y0, D0, m0, Lx, Ly):
dt = min(D0)/40
Nt = int(Nt)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/1e3)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = []
Ep_rec = []
cont_rec = []
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
mark_CB = 0
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Fx = Fx-B*vx
Fy = Fy-B*vy
Ep[nt] = Ep_now
cont[nt] = cont_now
if mark_CB == 0 and cont_now<cont[0]:
print("nt_CB=%d" % nt)
mark_CB = 1
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_rec.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[0:-1]+nt_rec[1:])/2
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f\n" %(CB_ratio))
print ("Ek_last=%.3e" % Ek[-1])
return x, y, nt_rec, Ek_rec, Ep_rec, cont_rec
def MD_Vibr3Part_ConstV(B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, ind_in_all, ind_out, mark_vibrY, eigen_mode_now):
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
num_in = ind_in_all.size
Phase_Vibr = np.sin(Freq_Vibr*dt*np.arange(Nt))
Amp_Vibr_all = np.zeros(num_in)
for i_in in np.arange(num_in):
ind_in = ind_in_all[i_in]
if mark_vibrY == 0:
Amp_Vibr_all[i_in] = eigen_mode_now[2*ind_in]
elif mark_vibrY == 1:
Amp_Vibr_all[i_in] = eigen_mode_now[2*ind_in+1]
print(ind_in_all)
print(Amp_Vibr_all)
Amp_Vibr_all = Amp_Vibr_all*Amp_Vibr/max(np.abs(Amp_Vibr_all))
print(Amp_Vibr_all)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
for i_in in np.arange(num_in):
ind_in = ind_in_all[i_in]
if mark_vibrY == 0:
x[ind_in] = Phase_Vibr[nt]*Amp_Vibr_all[i_in]+x_ini[ind_in]
y[ind_in] = y_ini[ind_in]
elif mark_vibrY == 1:
x[ind_in] = x_ini[ind_in]
y[ind_in] = Phase_Vibr[nt]*Amp_Vibr_all[i_in]+y_ini[ind_in]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx-B*vx
Fy_all = Fy-B*vy
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = np.array(0)
Ep_now = np.array(0)
cont_now = np.array(0)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now = np.append(cont_now, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
cont_now[0] = cont_now[1]
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
if mark_vibrY == 0:
x_in = Phase_Vibr*Amp_Vibr
freq_fft, fft_in = FFT_Fup(int(Nt/2), x_in[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
y_in = Phase_Vibr*Amp_Vibr
freq_fft, fft_in = FFT_Fup(int(Nt/2), y_in[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
return freq_fft, fft_in, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_dPhiSignal(mark_collision, beta, Nt, N, x_ini, y_ini, d0, phi0, m0, Lx, Ly, Freq_Vibr, Amp_Vibr, ind_in, ind_out, dphi_scheme, dphi_on, dphi_off, num_gap, mark_vibrY):
dt = d0/40
Nt = int(Nt)
if dphi_scheme == 1:
nt_dphi = np.linspace(0, Nt, 3)
nt_dphi = nt_dphi.astype(int)
dphi_all = np.zeros(Nt)+dphi_on
dphi_all[nt_dphi[1]:nt_dphi[2]] = dphi_off
elif dphi_scheme == -1:
nt_dphi = np.linspace(0, Nt, 3)
nt_dphi = nt_dphi.astype(int)
dphi_all = np.zeros(Nt)+dphi_off
dphi_all[nt_dphi[1]:nt_dphi[2]] = dphi_on
else:
dphi_all = np.zeros(Nt)+dphi_on
nt_dphi = np.linspace(0, Nt, num_gap+1)
nt_dphi = nt_dphi.astype(int)
for ii in np.arange(1, num_gap, 2):
dphi_all[nt_dphi[ii]:nt_dphi[ii+1]] = dphi_off
D_ini = np.zeros(N)+d0
nt_rec = np.linspace(0, Nt, int(Nt/5e4*num_gap/5)+1)
Ek_rec = np.array(0)
Ep_rec = np.array(0)
cont_rec = np.array(0)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 1:
y_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in]
vy_in = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt))
else:
x_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in]
vx_in = Amp_Vibr*Freq_Vibr*np.cos(Freq_Vibr*dt*np.arange(Nt))
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
D0 = D_ini*np.sqrt(1+dphi_all[nt]/phi0)
#if np.mod(nt,100000) == 0:
#print(D0[3])
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 1:
y[ind_in] = y_in[nt]
x[ind_in] = x_ini[ind_in]
vy[ind_in] = vy_in[nt]
vx[ind_in] = 0
else:
x[ind_in] = x_in[nt]
y[ind_in] = y_ini[ind_in]
vx[ind_in] = vx_in[nt]
vy[ind_in] = 0
Fx = np.zeros(N)
Fy = np.zeros(N)
if mark_collision == 1:
Fx, Fy, Ep_now, cont_now, p_now = force_YFixed_collision_ConstV(beta, Fx, Fy, N, x, y, vx, vy, D0, Lx, 0, Ly)
Fx_all = Fx
Fy_all = Fy
else:
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, Lx, 0, Ly)
Fx_all = Fx-beta*vx
Fy_all = Fy-beta*vy
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
for ii in np.arange(len(nt_rec)-1):
Ek_rec = np.append(Ek_rec, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec = np.append(Ep_rec, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec = np.append(cont_rec, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
print ("freq=%f, cont_min=%d, cont_max=%d, cont_ave=%f\n" %(Freq_Vibr, min(cont), max(cont), np.mean(cont)))
nt_dphi = np.arange(0, Nt, 100)
if mark_vibrY == 1:
xy_out = y_out
else:
xy_out = x_out
return nt_dphi, dphi_all[nt_dphi], xy_out, nt_rec[1:], Ek_rec[1:], Ep_rec[1:], cont_rec[1:]
def Damping_calc(Damp_scheme, B, N, x, y, vx, vy, Lx, Ly):
Fx_damp = np.zeros(N)
Fy_damp = np.zeros(N)
if Damp_scheme == 1:
Fx_damp = -B*vx
Fy_damp = -B*vy
if Damp_scheme == 2:
Fx_damp = -B*vx*np.abs(vx)*5e5
Fy_damp = -B*vy*np.abs(vy)*5e5
if Damp_scheme == 3:
Fx_damp = -B*vx/np.sqrt(np.abs(vx))*np.sqrt(2e-6)
Fy_damp = -B*vy/np.sqrt(np.abs(vy))*np.sqrt(2e-6)
if Damp_scheme == 4:
Fx_damp = -B*vx*np.exp(-5e4*np.abs(vx)+1)*0.1
Fy_damp = -B*vy*np.exp(-5e4*np.abs(vy)+1)*0.1
if Damp_scheme == 5:
Fx_damp = -B*vx*np.exp(-5e5*np.abs(vx)+1)
Fy_damp = -B*vy*np.exp(-5e5*np.abs(vy)+1)
if Damp_scheme == 6:
Fx_damp = -B*vx*np.exp(-5e6*np.abs(vx)+1)*10
Fy_damp = -B*vy*np.exp(-5e6*np.abs(vy)+1)*10
if Damp_scheme == 7:
Fx_damp = -B*vx*np.exp(-5e7*np.abs(vx)+1)*100
Fy_damp = -B*vy*np.exp(-5e7*np.abs(vy)+1)*100
return Fx_damp, Fy_damp
def Force_FixedPos_calc(k, N, x, y, x0, y0, D0, vx, vy, Lx, Ly):
Fx_damp = np.zeros(N)
Fy_damp = np.zeros(N)
Ep = 0
for nn in np.arange(N):
dy = y[nn]-y0[nn]
dy = dy-round(dy/Ly)*Ly
Dmn = 0.5*D0[nn]
dx = x[nn]-x0[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if (dmn > 0):
F = -k*(dmn/Dmn/Dmn)/dmn
Fx_damp[nn] += F*dx
Fy_damp[nn] += F*dy
Ep += (1/2)*k*(dmn/Dmn)**2
return Fx_damp, Fy_damp, Ep
def MD_FilterCheck_Periodic_Equi_vCorr(Nt_damp, Nt_FFT, num_period, Damp_scheme, B, N, x0, y0, D0, m0, L, T_set, V_em, n_em):
if Damp_scheme < 0:
return
N = int(N)
Nt_FFT = int(Nt_FFT)
Nt_damp = int(Nt_damp)
dt = min(D0)/40
Nt_period = int(2*Nt_damp+Nt_FFT)
Nt = Nt_period*num_period
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
mark_damp = np.zeros(Nt)
mark_FFT = np.zeros(Nt)
for ii in np.arange(num_period):
if ii > 0:
t1 = ii*Nt_period
t2 = t1+Nt_damp
mark_damp[t1:t2] = 1
t3 = ii*Nt_period+2*Nt_damp
t4 = t3+Nt_FFT
mark_FFT[t3:t4] = 1
nt_rec = np.linspace(0, Nt, int(Nt/1e3)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = []
Ep_rec = []
cont_rec = []
num_FFT = 0
vx = np.zeros(N)
vy = np.zeros(N)
for ii in np.arange(n_em):
ind1 = 2*np.arange(N)
ind2 = ind1+1
vx += V_em[ind1, ii]
vy += V_em[ind2, ii]
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
if mark_damp[nt] == 1:
Fx_damp, Fy_damp = Damping_calc(Damp_scheme, B, N, x, y, vx, vy, L[0], L[1])
Fx = Fx + Fx_damp
Fy = Fy + Fy_damp
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if mark_FFT[nt] == 1:
if mark_FFT[nt-1] == 0:
nt_ref = nt
vx_rec = np.zeros([Nt_FFT, N])
vy_rec = np.zeros([Nt_FFT, N])
nt_delta = nt-nt_ref
vx_rec[nt_delta] = vx
vy_rec[nt_delta] = vy
if nt_delta == Nt_FFT-1:
num_FFT += 1
freq_now, fft_now = FFT_vCorr(Nt_FFT, N, vx_rec, vy_rec, dt)
if num_FFT == 1:
fft_all = np.array([fft_now])
freq_all = np.array([freq_now])
len_fft_ref = len(fft_now)
len_freq_ref = len(freq_now)
else:
fft_add = np.zeros(len_fft_ref)
freq_add = np.zeros(len_freq_ref)
len_fft_now = len(fft_now)
len_freq_now = len(freq_now)
if len_fft_now >= len_fft_ref:
fft_add[0:len_fft_ref] = fft_now[0:len_fft_ref]
else:
fft_add[0:len_fft_now] = fft_now[0:len_fft_now]
fft_add[len_fft_now:] = fft_now[len_fft_now]
if len_freq_now >= len_freq_ref:
freq_add[0:len_freq_ref] = freq_now[0:len_freq_ref]
else:
freq_add[0:len_freq_now] = freq_now[0:len_freq_now]
freq_add[len_freq_now:] = freq_now[len_freq_now]
fft_all = np.append(fft_all, [fft_add], axis=0)
freq_all = np.append(freq_all, [freq_add], axis=0)
print("FFT_iteration: %d" % num_FFT)
print("Ek_ave: %e" %(np.mean(Ek[nt_ref:nt])))
ind1 = m0>5
ind2 = m0<5
print("|vx|_ave(heavy):%e" % np.mean(np.abs(vx[ind1])))
print("|vx|_ave(light):%e" % np.mean(np.abs(vx[ind2])))
for ii in np.arange(len(nt_rec)-1):
Ek_rec.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f" %(CB_ratio))
return freq_all, fft_all, (nt_rec[:-1]+nt_rec[1:])/2, Ek_rec, Ep_rec, cont_rec
def MD_FilterCheck_Periodic_Equi_vCorr_Seperate(Nt_damp, Nt_FFT, num_period, Damp_scheme, k, B, N, x0, y0, D0, m0, L, T_set, V_em, n_em):
# for damping scheme = -1 (fixed spring at initial position)
if Damp_scheme != -1:
return
N = int(N)
Nt_FFT = int(Nt_FFT)
Nt_damp = int(Nt_damp)
dt = min(D0)/40
Nt = Nt_damp*num_period+Nt_FFT
if num_period == 0:
Nt = Nt_damp+Nt_FFT
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
mark_FFT = np.zeros(Nt)
t1 = Nt_damp * num_period
if num_period == 0:
t1 = Nt_damp
t2 = t1 + Nt_FFT
mark_FFT[t1:t2] = 1
nt_rec = np.linspace(0, Nt, int(Nt/1e3)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = []
Ep_rec = []
cont_rec = []
vx = np.zeros(N)
vy = np.zeros(N)
for ii in np.arange(n_em):
ind1 = 2*np.arange(N)
ind2 = ind1+1
vx += V_em[ind1, ii]
vy += V_em[ind2, ii]
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
# always have damping exceot num_period = 0
if num_period > 0:
Fx_damp, Fy_damp, Ep_fix = Force_FixedPos_calc(k, N, x, y, x0, y0, D0, vx, vy, L[0], L[1])
if (B > 0):
Fx_damp += -B*vx
Fy_damp += -B*vy
elif num_period == 0:
Fx_damp = 0
Fy_damp = 0
Ep_fix = 0
Ep_now += Ep_fix
Fx = Fx + Fx_damp
Fy = Fy + Fy_damp
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if mark_FFT[nt] == 1:
if mark_FFT[nt-1] == 0:
nt_ref = nt
vx_rec = np.zeros([Nt_FFT, N])
vy_rec = np.zeros([Nt_FFT, N])
nt_delta = nt-nt_ref
vx_rec[nt_delta] = vx
vy_rec[nt_delta] = vy
if nt_delta == Nt_FFT-1:
freq_now, fft_now = FFT_vCorr(Nt_FFT, N, vx_rec, vy_rec, dt)
print ("Nt_End="+str(nt))
for ii in np.arange(len(nt_rec)-1):
Ek_rec.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f" %(CB_ratio))
return freq_now, fft_now, (nt_rec[:-1]+nt_rec[1:])/2, Ek_rec, Ep_rec, cont_rec
def MD_Periodic_Equi_vDistr(Nt_MD, Nt_rec, N, x0, y0, D0, m0, L, T_set, V_em, n_em):
N = int(N)
Nt_MD = int(Nt_MD)
Nt_rec = int(Nt_rec)
dt = min(D0)/40
Nt = Nt_MD+Nt_rec
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/1e3)+1)
nt_rec = nt_rec.astype(int)
Ek_rec = []
Ep_rec = []
cont_rec = []
ind1 = m0>5
ind2 = m0<5
vx_light = []
vx_heavy = []
vy_light = []
vy_heavy = []
vx = np.zeros(N)
vy = np.zeros(N)
for ii in np.arange(n_em):
ind1 = 2*np.arange(N)
ind2 = ind1+1
vx += V_em[ind1, ii]
vy += V_em[ind2, ii]
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if nt >= Nt_MD:
vx_light.extend(vx[ind2])
vy_light.extend(vy[ind2])
vx_heavy.extend(vx[ind1])
vy_heavy.extend(vy[ind1])
for ii in np.arange(len(nt_rec)-1):
Ek_rec.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_rec.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_rec.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f" %(CB_ratio))
return nt_rec, Ek_rec, Ep_rec, cont_rec, vx_light, vx_heavy, vy_light, vy_heavy
def Output_resonator_1D(Nt, x_drive, x0, m0, w0, dt):
dx = x_drive - x0
k = w0**2*m0
x = 0
vx = 0
ax_old = 0
Nt = int(Nt)
x_rec = np.zeros(Nt)
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
x_rec[nt] = x
Fx = k*(dx[nt]-x)
ax = Fx/m0;
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
ax_old = ax;
freq_fft, fft_x_rec = FFT_Fup(int(Nt/2), x_rec[int(Nt/2):Nt], dt, w0)
return freq_fft, fft_x_rec
def MD_Periodic_vCorr(Nt, N, x0, y0, D0, m0, vx0, vy0, L, T_set):
dt = min(D0)/40
Nt = int(Nt)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
vx_rec = np.zeros([int(Nt/2), N])
vy_rec = np.zeros([int(Nt/2), N])
vx = vx0
vy = vy0
T_rd = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
vx = vx*np.sqrt(N*T_set/T_rd)
vy = vy*np.sqrt(N*T_set/T_rd)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, L[0], L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
ax = np.divide(Fx, m0);
ay = np.divide(Fy, m0);
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
if (nt >= Nt/2):
vx_rec[int(nt-Nt/2)] = vx
vy_rec[int(nt-Nt/2)] = vy
CB_ratio = min(cont)/max(cont)
print ("cont_min/cont_max=%f\n" %(CB_ratio))
freq_now, fft_now = FFT_vCorr(int(Nt/2), N, vx_rec, vy_rec, dt)
return freq_now, fft_now, np.mean(cont)
def MD_Period_ConstV_SD(Nt, N, x0, y0, D0, m0, Lx, Ly):
dt = D0[0]/40
Nt = int(Nt)
Ep = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
#t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Ep_now, cont_now, p_now = force_Regular(Fx, Fy, N, x, y, D0, Lx, Ly)
Ep[nt] = Ep_now
vx = 0.1*np.divide(Fx, m0)
vy = 0.1*np.divide(Fy, m0)
x += vx*dt
y += vy*dt
F_tot[nt] = sum(np.absolute(Fx)+np.absolute(Fy))
#t_end = time.time()
print ("F_tot=%.3e" %(F_tot[nt]))
#print ("time=%.3e" %(t_end-t_start))
return x, y, p_now
def Force_FixedPos_YFixed_calc(k, N, x, y, x0, y0, D0, vx, vy, Lx, Ly):
Fx_damp = np.zeros(N)
Fy_damp = np.zeros(N)
Ep = 0
for nn in np.arange(N):
dy = y[nn]-y0[nn]
Dmn = 0.5*D0[nn]
dx = x[nn]-x0[nn]
dx = dx-round(dx/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if (dmn > 0):
F = -k*(dmn/Dmn/Dmn)/dmn
Fx_damp[nn] += F*dx
Fy_damp[nn] += F*dy
Ep += (1/2)*k*(dmn/Dmn)**2
return Fx_damp, Fy_damp, Ep
def MD_VibrSP_ConstV_Yfixed_FixSpr(k, B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, ind_in, ind_out):
mark_vibrY = 0
mark_resonator = 1
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in]
elif mark_vibrY == 1:
y_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in]
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 0:
x[ind_in] = x_in[nt]
y[ind_in] = y_ini[ind_in]
elif mark_vibrY == 1:
x[ind_in] = x_ini[ind_in]
y[ind_in] = y_in[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Fx_damp, Fy_damp, Ep_fix = Force_FixedPos_YFixed_calc(k, N, x, y, x_ini, y_ini, D0, vx, vy, L[0], L[1])
#Fx_damp = 0; Fy_damp = 0; Ep_fix = 0
Fx_damp += -B*vx
Fy_damp += -B*vy
Ep[nt] = Ep_now + Ep_fix
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx+Fx_damp
Fy_all = Fy+Fy_damp
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = []
Ep_now = []
cont_now = []
for ii in np.arange(len(nt_rec)-1):
Ek_now.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[1:] + nt_rec[:-1]) / 2
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f, Ek_mean=%.3e, Ep_mean=%.3e\n" %(Freq_Vibr, CB_ratio, np.mean(Ek), np.mean(Ep)))
if mark_vibrY == 0:
freq_fft, fft_in = FFT_Fup(int(Nt/2), x_in[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in = FFT_Fup(int(Nt/2), y_in[int(Nt/2):Nt], dt, Freq_Vibr)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
return freq_fft, fft_in, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_VibrSP_ConstV_Yfixed_FixSpr2(k, B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out):
mark_vibrY = 0
mark_resonator = 0
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in1 = Amp_Vibr1*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in1]
x_in2 = Amp_Vibr2*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in2]
elif mark_vibrY == 1:
y_in1 = Amp_Vibr1*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in1]
y_in2 = Amp_Vibr2*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in2]
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 0:
x[ind_in1] = x_in1[nt]
y[ind_in1] = y_ini[ind_in1]
x[ind_in2] = x_in2[nt]
y[ind_in2] = y_ini[ind_in2]
elif mark_vibrY == 1:
x[ind_in1] = x_ini[ind_in1]
y[ind_in1] = y_in1[nt]
x[ind_in2] = x_ini[ind_in2]
y[ind_in2] = y_in2[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Fx_damp, Fy_damp, Ep_fix = Force_FixedPos_YFixed_calc(k, N, x, y, x_ini, y_ini, D0, vx, vy, L[0], L[1])
#Fx_damp = 0; Fy_damp = 0; Ep_fix = 0
Fx_damp += -B*vx
Fy_damp += -B*vy
Ep[nt] = Ep_now + Ep_fix
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx+Fx_damp
Fy_all = Fy+Fy_damp
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = []
Ep_now = []
cont_now = []
for ii in np.arange(len(nt_rec)-1):
Ek_now.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[1:] + nt_rec[:-1]) / 2
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
#print ("freq=%f, cont_min/cont_max=%f, Ek_mean=%.3e, Ep_mean=%.3e\n" %(Freq_Vibr, CB_ratio, np.mean(Ek), np.mean(Ep)))
if mark_vibrY == 0:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), x_in1[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), x_in2[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), y_in1[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), y_in2[int(Nt/2):Nt], dt, Freq_Vibr)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
return freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_VibrSP_ConstV_Yfixed_FixSpr3(k, B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr1, Amp_Vibr1, ind_in1, Freq_Vibr2, Amp_Vibr2, ind_in2, ind_out):
mark_vibrY = 0
mark_resonator = 0
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in1 = Amp_Vibr1*np.sin(Freq_Vibr1*dt*np.arange(Nt))+x_ini[ind_in1]
x_in2 = Amp_Vibr2*np.sin(Freq_Vibr2*dt*np.arange(Nt))+x_ini[ind_in2]
elif mark_vibrY == 1:
y_in1 = Amp_Vibr1*np.sin(Freq_Vibr1*dt*np.arange(Nt))+y_ini[ind_in1]
y_in2 = Amp_Vibr2*np.sin(Freq_Vibr2*dt*np.arange(Nt))+y_ini[ind_in2]
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 0:
x[ind_in1] = x_in1[nt]
y[ind_in1] = y_ini[ind_in1]
x[ind_in2] = x_in2[nt]
y[ind_in2] = y_ini[ind_in2]
elif mark_vibrY == 1:
x[ind_in1] = x_ini[ind_in1]
y[ind_in1] = y_in1[nt]
x[ind_in2] = x_ini[ind_in2]
y[ind_in2] = y_in2[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Fx_damp, Fy_damp, Ep_fix = Force_FixedPos_YFixed_calc(k, N, x, y, x_ini, y_ini, D0, vx, vy, L[0], L[1])
#Fx_damp = 0; Fy_damp = 0; Ep_fix = 0
Fx_damp += -B*vx
Fy_damp += -B*vy
Ep[nt] = Ep_now + Ep_fix
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx+Fx_damp
Fy_all = Fy+Fy_damp
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = []
Ep_now = []
cont_now = []
for ii in np.arange(len(nt_rec)-1):
Ek_now.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[1:] + nt_rec[:-1]) / 2
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f, Ek_mean=%.3e, Ep_mean=%.3e\n" %(Freq_Vibr1, CB_ratio, np.mean(Ek), np.mean(Ep)))
if mark_vibrY == 0:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), x_in1[int(Nt/2):Nt], dt, Freq_Vibr1)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), x_in2[int(Nt/2):Nt], dt, Freq_Vibr2)
elif mark_vibrY == 1:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), y_in1[int(Nt/2):Nt], dt, Freq_Vibr1)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), y_in2[int(Nt/2):Nt], dt, Freq_Vibr2)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr1)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr1)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr1, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr1, dt)
return freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_VibrSP_Force_ConstV(B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, ind_in, ind_out, mark_vibrY, mark_resonator):
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
x_in = np.zeros(Nt)
y_in = np.zeros(Nt)
if mark_vibrY == 0:
Fx_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))
elif mark_vibrY == 1:
Fy_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
x_in[nt] = x[ind_in]
y_in[nt] = y[ind_in]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx-B*vx
Fy_all = Fy-B*vy
if mark_vibrY == 0:
Fx_all[ind_in] += Fx_in[nt]
elif mark_vibrY == 1:
Fy_all[ind_in] += Fy_in[nt]
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = np.array(0)
Ep_now = np.array(0)
cont_now = np.array(0)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now = np.append(cont_now, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
cont_now[0] = cont_now[1]
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
if mark_vibrY == 0:
freq_fft, fft_in = FFT_Fup(int(Nt/2), x_in[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in = FFT_Fup(int(Nt/2), y_in[int(Nt/2):Nt], dt, Freq_Vibr)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
if Nt == 5e5:
print(x[ind_out], y[ind_out])
print(fft_x_out[100], fft_y_out[100])
print(fft_in[100])
return freq_fft, fft_in, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_VibrSP_ConstV_ConfigCB(B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr, ind_in, ind_out, Nt_rec):
mark_vibrY = 0
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in]
elif mark_vibrY == 1:
y_in = Amp_Vibr*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in]
#y_bot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
#t_start = time.time()
for nt in np.arange(Nt):
if nt == Nt_rec:
x_rec = x[:]
y_rec = y[:]
x = x+vx*dt+ax_old*dt**2/2; # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2;
if mark_vibrY == 0:
x[ind_in] = x_in[nt]
y[ind_in] = y_ini[ind_in]
elif mark_vibrY == 1:
x[ind_in] = x_ini[ind_in]
y[ind_in] = y_in[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed(Fx, Fy, N, x, y, D0, L[0], 0, L[1])
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx-B*vx
Fy_all = Fy-B*vy
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2; # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2;
ax_old = ax;
ay_old = ay;
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = np.array(0)
Ep_now = np.array(0)
cont_now = np.array(0)
for ii in np.arange(len(nt_rec)-1):
Ek_now = np.append(Ek_now, np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now = np.append(Ep_now, np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now = np.append(cont_now, np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
cont_now[0] = cont_now[1]
CB_ratio = min(cont)/max(cont)
print ("freq=%f, cont_min/cont_max=%f\n" %(Freq_Vibr, CB_ratio))
return x_rec, y_rec
def VL_YFixed_ConstV(N, x, y, D, Lx, VL_list, VL_counter_old, x_save, y_save, first_call):
r_factor = 1.2
r_cut = np.amax(D)
r_list = r_factor * r_cut
r_list_sq = r_list**2
r_skin_sq = ((r_factor - 1.0) * r_cut)**2
if first_call == 0:
dr_sq_max = 0.0
for nn in np.arange(N):
dy = y[nn] - y_save[nn]
dx = x[nn] - x_save[nn]
dx = dx - round(dx / Lx) * Lx
dr_sq = dx**2 + dy**2
if dr_sq > dr_sq_max:
dr_sq_max = dr_sq
if dr_sq_max < r_skin_sq:
return VL_list, VL_counter_old, x_save, y_save
VL_counter = 0
for nn in np.arange(N):
r_now = 0.5*D[nn]
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < r_list:
dx = x[mm]-x[nn]
dx = dx - round(dx / Lx) * Lx
if abs(dx) < r_list:
dmn_sq = dx**2 + dy**2
if dmn_sq < r_list_sq:
VL_list[VL_counter][0] = nn
VL_list[VL_counter][1] = mm
VL_counter += 1
return VL_list, VL_counter, x, y
def MD_YFixed_ConstV_SP_SD_DiffK(Nt, N, x0, y0, D0, m0, Lx, Ly, k_list, k_type):
dt = D0[0] * np.sqrt(k_list[2]) / 20.0
Nt = int(Nt)
Ep = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
x_save = np.array(x0)
y_save = np.array(y0)
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list = np.zeros((N * 10, 2), dtype=int)
VL_counter = 0
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 1)
t_start = time.time()
for nt in np.arange(Nt):
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 0)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
Ep[nt] = Ep_now
vx = 0.1 * Fx
vy = 0.1 * Fy
x += vx * dt
y += vy * dt
F_tot[nt] = sum(np.absolute(Fx) + np.absolute(Fy))
# putting a threshold on total force
if (F_tot[nt] < 1e-11):
break
print(nt)
print(F_tot[nt])
t_end = time.time()
#print ("F_tot=%.3e" %(F_tot[nt]))
#print ("time=%.3e" %(t_end-t_start))
return x, y, p_now
def FIRE_YFixed_ConstV_DiffK(Nt, N, x0, y0, D0, m0, Lx, Ly, k_list, k_type):
dt_md = 0.01 * D0[0] * np.sqrt(k_list[2])
N_delay = 20
N_pn_max = 2000
f_inc = 1.1
f_dec = 0.5
a_start = 0.15
f_a = 0.99
dt_max = 10.0 * dt_md
dt_min = 0.05 * dt_md
initialdelay = 1
Nt = int(Nt)
Ep = np.zeros(Nt)
F_tot = np.zeros(Nt)
vx = np.zeros(N)
vy = np.zeros(N)
x = np.array(x0)
y = np.array(y0)
x_save = np.array(x0)
y_save = np.array(y0)
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list = np.zeros((N * 10, 2), dtype=int)
VL_counter = 0
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 1)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
a_fire = a_start
delta_a_fire = 1.0 - a_fire
dt = dt_md
dt_half = dt / 2.0
N_pp = 0 # number of P being positive
N_pn = 0 # number of P being negative
## FIRE
for nt in np.arange(Nt):
# FIRE update
P = np.dot(vx, Fx) + np.dot(vy, Fy)
if P > 0.0:
N_pp += 1
N_pn = 0
if N_pp > N_delay:
dt = min(f_inc * dt, dt_max)
dt_half = dt / 2.0
a_fire = f_a * a_fire
delta_a_fire = 1.0 - a_fire
else:
N_pp = 0
N_pn += 1
if N_pn > N_pn_max:
break
if (initialdelay < 0.5) or (nt >= N_delay):
if f_dec * dt > dt_min:
dt = f_dec * dt
dt_half = dt / 2.0
a_fire = a_start
delta_a_fire = 1.0 - a_fire
x -= vx * dt_half
y -= vy * dt_half
vx = np.zeros(N)
vy = np.zeros(N)
# MD using Verlet method
vx += Fx * dt_half
vy += Fy * dt_half
rsc_fire = np.sqrt(np.sum(vx**2 + vy**2)) / np.sqrt(np.sum(Fx**2 + Fy**2))
vx = delta_a_fire * vx + a_fire * rsc_fire * Fx
vy = delta_a_fire * vy + a_fire * rsc_fire * Fy
x += vx * dt
y += vy * dt
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 0)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
Ep[nt] = Ep_now
F_tot[nt] = sum(np.absolute(Fx) + np.absolute(Fy))
# putting a threshold on total force
if (F_tot[nt] < 1e-11):
break
vx += Fx * dt_half
vy += Fy * dt_half
#print(nt)
#print(F_tot[nt])
t_end = time.time()
#print ("F_tot=%.3e" %(F_tot[nt]))
#print ("time=%.3e" %(t_end-t_start))
return x, y, p_now
def MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out):
Lx = L[0]
Ly = L[1]
mark_vibrY = 0
mark_resonator = 0
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
F_tot = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in1 = Amp_Vibr1*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in1]
x_in2 = Amp_Vibr2*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in2]
elif mark_vibrY == 1:
y_in1 = Amp_Vibr1*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in1]
y_in2 = Amp_Vibr2*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in2]
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
x_save = np.array(x_ini)
y_save = np.array(y_ini)
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list = np.zeros((N * 10, 2), dtype=int)
VL_counter = 0
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 1)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2 # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2
if mark_vibrY == 0:
x[ind_in1] = x_in1[nt]
y[ind_in1] = y_ini[ind_in1]
x[ind_in2] = x_in2[nt]
y[ind_in2] = y_ini[ind_in2]
elif mark_vibrY == 1:
x[ind_in1] = x_ini[ind_in1]
y[ind_in1] = y_in1[nt]
x[ind_in2] = x_ini[ind_in2]
y[ind_in2] = y_in2[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 0)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx - B*vx
Fy_all = Fy - B*vy
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2 # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2
ax_old = ax
ay_old = ay
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = []
Ep_now = []
cont_now = []
for ii in np.arange(len(nt_rec)-1):
Ek_now.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[1:] + nt_rec[:-1]) / 2
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
#print ("freq=%f, cont_min/cont_max=%f, Ek_mean=%.3e, Ep_mean=%.3e\n" %(Freq_Vibr, CB_ratio, np.mean(Ek), np.mean(Ep)))
if mark_vibrY == 0:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), x_in1[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), x_in2[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), y_in1[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), y_in2[int(Nt/2):Nt], dt, Freq_Vibr)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
return freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, np.mean(cont), nt_rec, Ek_now, Ep_now, cont_now
def MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D0, m0, L, Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out):
Lx = L[0]
Ly = L[1]
mark_vibrY = 0
mark_resonator = 0
dt = D0[0]/40
Nt = int(Nt)
nt_rec = np.linspace(0, Nt, int(Nt/5e4)+1)
nt_rec = nt_rec.astype(int)
Ep = np.zeros(Nt)
Ek = np.zeros(Nt)
cont = np.zeros(Nt)
p = np.zeros(Nt)
F_tot = np.zeros(Nt)
x_out = np.zeros(Nt)
y_out = np.zeros(Nt)
if mark_vibrY == 0:
x_in1 = Amp_Vibr1*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in1]
x_in2 = Amp_Vibr2*np.sin(Freq_Vibr*dt*np.arange(Nt))+x_ini[ind_in2]
elif mark_vibrY == 1:
y_in1 = Amp_Vibr1*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in1]
y_in2 = Amp_Vibr2*np.sin(Freq_Vibr*dt*np.arange(Nt))+y_ini[ind_in2]
vx = np.zeros(N)
vy = np.zeros(N)
ax_old = np.zeros(N)
ay_old = np.zeros(N)
x = np.array(x_ini)
y = np.array(y_ini)
x_save = np.array(x_ini)
y_save = np.array(y_ini)
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list = np.zeros((N * 10, 2), dtype=int)
VL_counter = 0
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 1)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
for nt in np.arange(Nt):
x = x+vx*dt+ax_old*dt**2/2 # first step in Verlet integration
y = y+vy*dt+ay_old*dt**2/2
if mark_vibrY == 0:
x[ind_in1] = x_in1[nt]
y[ind_in1] = y_ini[ind_in1]
x[ind_in2] = x_in2[nt]
y[ind_in2] = y_ini[ind_in2]
elif mark_vibrY == 1:
x[ind_in1] = x_ini[ind_in1]
y[ind_in1] = y_in1[nt]
x[ind_in2] = x_ini[ind_in2]
y[ind_in2] = y_in2[nt]
Fx = np.zeros(N)
Fy = np.zeros(N)
VL_list, VL_counter, x_save, y_save = VL_YFixed_ConstV(N, x, y, D0, Lx, VL_list, VL_counter, x_save, y_save, 0)
Fx, Fy, Fup_now, Fbot_now, Ep_now, cont_now, p_now, cont_up = force_YFixed_DiffK_VL(Fx, Fy, N, x, y, D0, Lx, 0, Ly, k_list, k_type, VL_list, VL_counter)
Ep[nt] = Ep_now
cont[nt] = cont_now
p[nt] = p_now
Fx_all = Fx - B*vx
Fy_all = Fy - B*vy
x_out[nt] = x[ind_out]
y_out[nt] = y[ind_out]
ax = np.divide(Fx_all, m0)
ay = np.divide(Fy_all, m0)
vx = vx+(ax_old+ax)*dt/2 # second step in Verlet integration
vy = vy+(ay_old+ay)*dt/2
ax_old = ax
ay_old = ay
Ek[nt] = sum(0.5*np.multiply(m0,np.multiply(vx, vx)+np.multiply(vy, vy)))
Ek_now = []
Ep_now = []
cont_now = []
for ii in np.arange(len(nt_rec)-1):
Ek_now.append(np.mean(Ek[nt_rec[ii]:nt_rec[ii+1]]))
Ep_now.append(np.mean(Ep[nt_rec[ii]:nt_rec[ii+1]]))
cont_now.append(np.mean(cont[nt_rec[ii]:nt_rec[ii+1]]))
nt_rec = (nt_rec[1:] + nt_rec[:-1]) / 2
#t_end = time.time()
#print ("time=%.3e" %(t_end-t_start))
CB_ratio = min(cont)/max(cont)
#print ("freq=%f, cont_min/cont_max=%f, Ek_mean=%.3e, Ep_mean=%.3e\n" %(Freq_Vibr, CB_ratio, np.mean(Ek), np.mean(Ep)))
if mark_vibrY == 0:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), x_in1[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), x_in2[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_vibrY == 1:
freq_fft, fft_in1 = FFT_Fup(int(Nt/2), y_in1[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_in2 = FFT_Fup(int(Nt/2), y_in2[int(Nt/2):Nt], dt, Freq_Vibr)
if mark_resonator == 0:
freq_fft, fft_x_out = FFT_Fup(int(Nt/2), x_out[int(Nt/2):Nt], dt, Freq_Vibr)
freq_fft, fft_y_out = FFT_Fup(int(Nt/2), y_out[int(Nt/2):Nt], dt, Freq_Vibr)
elif mark_resonator == 1:
freq_fft, fft_x_out = Output_resonator_1D(Nt, x_out[0:Nt], x_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
freq_fft, fft_y_out = Output_resonator_1D(Nt, y_out[0:Nt], y_ini[ind_out], m0[ind_out], Freq_Vibr, dt)
return x_in1-x_ini[ind_in1], x_in2-x_ini[ind_in2], x_out-x_ini[ind_out]
| 133,858 | 30.675106 | 178 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/constants.py
|
# number of runs
RUNS = 3
worstFitness = +1000000
# population size
popSize = 50
# number of generations
numGenerations = 200
| 129 | 10.818182 | 23 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/afpo_seed_binary.py
|
import constants as c
import copy
import numpy as np
import operator
import statistics
import pickle
from joblib import Parallel, delayed
import multiprocessing
from genome_seed_binary import GENOME
class AFPO:
def __init__(self,randomSeed):
self.randomSeed = randomSeed
self.currentGeneration = 0
self.nextAvailableID = 0
self.genomes = {}
for populationPosition in range(c.popSize):
self.genomes[populationPosition] = GENOME(self.nextAvailableID)
self.nextAvailableID = self.nextAvailableID + 1
def Evolve(self):
self.Perform_First_Generation()
for self.currentGeneration in range(1,c.numGenerations):
self.Perform_One_Generation()
self.SaveLastGen()
# -------------------------- Private methods ----------------------
def Age(self):
for genome in self.genomes:
self.genomes[genome].Age()
def Aggressor_Dominates_Defender(self,aggressor,defender):
return self.genomes[aggressor].Dominates(self.genomes[defender])
def Choose_Aggressor(self):
return np.random.randint(c.popSize)
def Choose_Defender(self,aggressor):
defender = np.random.randint(c.popSize)
while defender == aggressor:
defender = np.random.randint(c.popSize)
return defender
def Contract(self):
while len(self.genomes) > c.popSize:
aggressorDominatesDefender = False
while not aggressorDominatesDefender:
aggressor = self.Choose_Aggressor()
defender = self.Choose_Defender(aggressor)
aggressorDominatesDefender = self.Aggressor_Dominates_Defender(aggressor,defender)
for genomeToMove in range(defender,len(self.genomes)-1):
self.genomes[genomeToMove] = self.genomes.pop(genomeToMove+1)
def process(self, i):
return i*i
def Evaluate_Genomes(self):
num_cores = multiprocessing.cpu_count()
print("we have")
print(num_cores)
print("cores")
outs = Parallel(n_jobs=num_cores)(delayed(self.genomes[genome].Evaluate)() for genome in self.genomes)
#print("done")
#print(type(outs))
#self.genomes = copy.deepcopy(np.array(outs))
#self.genomes = dict(zip(list(range(0, c.popSize)), outs))
#print(type(self.genomes))
for genome in self.genomes:
# print(genome)
#print(self.genomes[genome].indv.fitness)
# print(outs[genome])
self.genomes[genome].fitness = outs[genome]
self.genomes[genome].indv.fitness = -outs[genome]
def Expand(self):
popSize = len(self.genomes)
for newGenome in range( popSize , 2 * popSize - 1 ):
spawner = self.Choose_Aggressor()
self.genomes[newGenome] = copy.deepcopy(self.genomes[spawner])
self.genomes[newGenome].Set_ID(self.nextAvailableID)
self.nextAvailableID = self.nextAvailableID + 1
self.genomes[newGenome].Mutate()
def Find_Best_Genome(self):
genomesSortedByFitness = sorted(self.genomes.values(), key=operator.attrgetter('fitness'),reverse=False)
return genomesSortedByFitness[0]
def Find_Avg_Fitness(self):
add = 0
for g in self.genomes:
add += self.genomes[g].fitness
return add/c.popSize
def Inject(self):
popSize = len(self.genomes)
self.genomes[popSize-1] = GENOME(self.nextAvailableID)
self.nextAvailableID = self.nextAvailableID + 1
def Perform_First_Generation(self):
self.Evaluate_Genomes()
self.Print()
self.Save_Best()
self.Save_Avg()
def Perform_One_Generation(self):
self.Expand()
self.Age()
self.Inject()
self.Evaluate_Genomes()
self.Contract()
self.Print()
self.Save_Best()
self.Save_Avg()
def Print(self):
print('Generation ', end='', flush=True)
print(self.currentGeneration, end='', flush=True)
print(' of ', end='', flush=True)
print(str(c.numGenerations), end='', flush=True)
print(': ', end='', flush=True)
bestGenome = self.Find_Best_Genome()
bestGenome.Print()
def Save_Best(self):
bestGenome = self.Find_Best_Genome()
bestGenome.Save(self.randomSeed)
def SaveLastGen(self):
genomesSortedByFitness = sorted(self.genomes.values(), key=operator.attrgetter('fitness'),reverse=False)
f = open('savedRobotsLastGenAfpoSeed.dat', 'ab')
pickle.dump(genomesSortedByFitness, f)
f.close()
def Save_Avg(self):
f = open('avgFitnessAfpoSeed.dat', 'ab')
avg = self.Find_Avg_Fitness()
print('Average ' + str(avg))
print()
#f.write("%.3f\n" % avg)
pickle.dump(avg, f)
f.close()
def Show_Best_Genome(self):
bestGenome = self.Find_Best_Genome()
bestGenome.Show()
| 5,048 | 30.955696 | 112 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/DynamicalMatrix.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 22:09:09 2017
@author: Hightoutou
"""
def DM_mass(N, x0, y0, D0, m0, L):
import numpy as np
Lx = L[0]
Ly = L[1]
M = np.zeros((2*N, 2*N))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
rijsq = dx**2+dy**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0],[0,1]])/rij/dij
Mij = Mij1+Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
m_sqrt = np.zeros((2*N, 2*N))
m_inv = np.zeros((2*N, 2*N))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_3D(N, x0, y0, z0, D0, m0, L):
import numpy as np
Lx = L[0]
Ly = L[1]
Lz = L[2]
M = np.zeros((3*N, 3*N))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
dz = z0[i]-z0[j]
dz = dz-round(dz/Lz)*Lz
rijsq = dx**2+dy**2+dz**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy, dx*dz], [dy*dx, dy*dy, dy*dz], [dz*dx, dz*dy, dz*dz]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0,0],[0,1,0],[0,0,1]])/rij/dij
Mij = Mij1+Mij2
M[3*i:3*i+3,3*j:3*j+3] = Mij
M[3*j:3*j+3,3*i:3*i+3] = Mij
M[3*i:3*i+3,3*i:3*i+3] = M[3*i:3*i+3,3*i:3*i+3] - Mij
M[3*j:3*j+3,3*j:3*j+3] = M[3*j:3*j+3,3*j:3*j+3] - Mij
m_sqrt = np.zeros((3*N, 3*N))
m_inv = np.zeros((3*N, 3*N))
for i in range(N):
m_sqrt[3*i, 3*i] = 1/np.sqrt(m0[i])
m_sqrt[3*i+1, 3*i+1] = 1/np.sqrt(m0[i])
m_sqrt[3*i+2, 3*i+2] = 1/np.sqrt(m0[i])
m_inv[3*i, 3*i] = 1/m0[i]
m_inv[3*i+1, 3*i+1] = 1/m0[i]
m_inv[3*i+2, 3*i+2] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_Yfixed(N, x0, y0, D0, m0, Lx, y_bot, y_top, k):
import numpy as np
M = np.zeros((2*N, 2*N))
contactNum = 0
for i in range(N):
r_now = 0.5*D0[i]
if y0[i]-y_bot<r_now or y_top-y0[i]<r_now:
M[2*i+1, 2*i+1] = M[2*i+1, 2*i+1]+1/r_now/r_now
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
rijsq = dx**2+dy**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0],[0,1]])/rij/dij
Mij = Mij1+Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
M = k*M
m_sqrt = np.zeros((2*N, 2*N))
m_inv = np.zeros((2*N, 2*N))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_Xfixed(N, x0, y0, D0, m0, Ly):
import numpy as np
M = np.zeros((2*N, 2*N))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
rijsq = dx**2+dy**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0],[0,1]])/rij/dij
Mij = Mij1+Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
m_sqrt = np.zeros((2*N, 2*N))
m_inv = np.zeros((2*N, 2*N))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_DiffK_Yfixed(N, x0, y0, D0, m0, Lx, y_bot, y_top, k_list, k_type):
import numpy as np
M = np.zeros((2*N, 2*N))
contactNum = 0
for i in range(N):
r_now = 0.5*D0[i]
if y0[i]-y_bot<r_now or y_top-y0[i]<r_now:
M[2*i+1, 2*i+1] = M[2*i+1, 2*i+1] + k_list[k_type[i]] / r_now / r_now
for j in range(i):
dij = 0.5 * (D0[i] + D0[j])
dijsq = dij**2
dx = x0[i] - x0[j]
dx = dx - round(dx / Lx) * Lx
dy = y0[i] - y0[j]
rijsq = dx**2 + dy**2
if rijsq < dijsq:
contactNum += 1
k = k_list[(k_type[i] ^ k_type[j]) + np.maximum(k_type[i], k_type[j])]
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -k * rijmat / rijsq / dijsq
Mij2 = -k * (1.0 - rij / dij) * (rijmat / rijsq - [[1,0],[0,1]]) / rij / dij
Mij = Mij1 + Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
m_sqrt = np.zeros((2*N, 2*N))
m_inv = np.zeros((2*N, 2*N))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_Zfixed_3D(N, x0, y0, z0, D0, m0, L):
import numpy as np
Lx = L[0]
Ly = L[1]
Lz = L[2]
M = np.zeros((3*N, 3*N))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
dz = z0[i]-z0[j]
rijsq = dx**2+dy**2+dz**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy, dx*dz], [dy*dx, dy*dy, dy*dz], [dz*dz, dz*dy, dz*dz]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0,0],[0,1,0],[0,0,1]])/rij/dij
Mij = Mij1+Mij2
M[3*i:3*i+3,3*j:3*j+3] = Mij
M[3*j:3*j+3,3*i:3*i+3] = Mij
M[3*i:3*i+3,3*i:3*i+3] = M[3*i:3*i+3,3*i:3*i+3] - Mij
M[3*j:3*j+3,3*j:3*j+3] = M[3*j:3*j+3,3*j:3*j+3] - Mij
m_sqrt = np.zeros((3*N, 3*N))
m_inv = np.zeros((3*N, 3*N))
for i in range(N):
m_sqrt[3*i, 3*i] = 1/np.sqrt(m0[i])
m_sqrt[3*i+1, 3*i+1] = 1/np.sqrt(m0[i])
m_sqrt[3*i+2, 3*i+2] = 1/np.sqrt(m0[i])
m_inv[3*i, 3*i] = 1/m0[i]
m_inv[3*i+1, 3*i+1] = 1/m0[i]
m_inv[3*i+2, 3*i+2] = 1/m0[i]
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_UpPlate(N, x0, y0, D0, m0, Lx, y_up, m_up):
import numpy as np
M = np.zeros((2*N+1, 2*N+1))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
rijsq = dx**2+dy**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy], [dx*dy, dy*dy]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0],[0,1]])/rij/dij
Mij = Mij1+Mij2
M[2*i:2*i+2,2*j:2*j+2] = Mij
M[2*j:2*j+2,2*i:2*i+2] = Mij
M[2*i:2*i+2,2*i:2*i+2] = M[2*i:2*i+2,2*i:2*i+2] - Mij
M[2*j:2*j+2,2*j:2*j+2] = M[2*j:2*j+2,2*j:2*j+2] - Mij
for i in range(N):
r_now = 0.5*D0[i]
if y0[i]<r_now:
M[2*i+1, 2*i+1] = M[2*i+1, 2*i+1]+1/r_now**2
if y_up-y0[i]<r_now:
M[2*i+1, 2*i+1] = M[2*i+1, 2*i+1]+1/r_now**2
M[2*N, 2*N] = M[2*N, 2*N]+1/r_now**2
M[2*i+1, 2*N] = M[2*i+1, 2*N]-1/r_now**2
M[2*N, 2*i+1] = M[2*N, 2*i+1]-1/r_now**2
m_sqrt = np.zeros((2*N+1, 2*N+1))
m_inv = np.zeros((2*N+1, 2*N+1))
for i in range(N):
m_sqrt[2*i, 2*i] = 1/np.sqrt(m0[i])
m_sqrt[2*i+1, 2*i+1] = 1/np.sqrt(m0[i])
m_inv[2*i, 2*i] = 1/m0[i]
m_inv[2*i+1, 2*i+1] = 1/m0[i]
m_sqrt[2*N, 2*N] = 1/np.sqrt(m_up)
m_inv[2*N, 2*N] = 1/m_up
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
def DM_mass_UpPlate_3D(N, x0, y0, z0, D0, m0, Lx, Ly, z_up, m_up):
import numpy as np
M = np.zeros((3*N+1, 3*N+1))
contactNum = 0
for i in range(N):
for j in range(i):
dij = 0.5*(D0[i]+D0[j])
dijsq = dij**2
dx = x0[i]-x0[j]
dx = dx-round(dx/Lx)*Lx
dy = y0[i]-y0[j]
dy = dy-round(dy/Ly)*Ly
dz = z0[i]-z0[j]
rijsq = dx**2+dy**2+dz**2
if rijsq<dijsq:
contactNum += 1
rijmat = np.array([[dx*dx, dx*dy, dx*dz], [dy*dx, dy*dy, dy*dz], [dz*dz, dz*dy, dz*dz]])
rij = np.sqrt(rijsq)
Mij1 = -rijmat/rijsq/dijsq
Mij2 = -(1-rij/dij)*(rijmat/rijsq-[[1,0,0],[0,1,0],[0,0,1]])/rij/dij
Mij = Mij1+Mij2
M[3*i:3*i+3,3*j:3*j+3] = Mij
M[3*j:3*j+3,3*i:3*i+3] = Mij
M[3*i:3*i+3,3*i:3*i+3] = M[3*i:3*i+3,3*i:3*i+3] - Mij
M[3*j:3*j+3,3*j:3*j+3] = M[3*j:3*j+3,3*j:3*j+3] - Mij
for i in range(N):
r_now = 0.5*D0[i]
if z0[i]<r_now:
M[3*i+2, 3*i+2] = M[3*i+2, 3*i+2]+1/r_now**2
if z_up-z0[i]<r_now:
M[3*i+2, 3*i+2] = M[3*i+2, 3*i+2]+1/r_now**2
M[3*N, 3*N] = M[3*N, 3*N]+1/r_now**2
M[3*i+2, 3*N] = M[3*i+2, 3*N]-1/r_now**2
M[3*N, 3*i+2] = M[3*N, 3*i+2]-1/r_now**2
m_sqrt = np.zeros((3*N+1, 3*N+1))
m_inv = np.zeros((3*N+1, 3*N+1))
for i in range(N):
m_sqrt[3*i, 3*i] = 1/np.sqrt(m0[i])
m_sqrt[3*i+1, 3*i+1] = 1/np.sqrt(m0[i])
m_sqrt[3*i+2, 3*i+2] = 1/np.sqrt(m0[i])
m_inv[3*i, 3*i] = 1/m0[i]
m_inv[3*i+1, 3*i+1] = 1/m0[i]
m_inv[3*i+2, 3*i+2] = 1/m0[i]
m_sqrt[3*N, 3*N] = 1/np.sqrt(m_up)
m_inv[3*N, 3*N] = 1/m_up
#M = m_sqrt.dot(M).dot(m_sqrt)
M = m_inv.dot(M)
w,v = np.linalg.eig(M)
return w,v
| 12,537 | 30.423559 | 104 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/ConfigPlot.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 21:01:26 2017
@author: Hightoutou
"""
import numpy as np
def ConfigPlot_DiffSize(N, x, y, D, L, mark_print):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
Dmin = min(D)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
D_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
D_all.append(D[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_alpha(0.3)
if D_all[i] > Dmin:
e.set_facecolor('C1')
else:
e.set_facecolor('C0')
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
def ConfigPlot_DiffMass(N, x, y, D, L, m, mark_print, hn):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffMass2(N, x, y, D, L, m, mark_print, hn, in1, in2, out):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
if i==in1:
e.set_edgecolor((0, 1, 0))
e.set_linewidth(4)
elif i==in2:
e.set_edgecolor((0, 0, 1))
e.set_linewidth(4)
elif i==out:
e.set_edgecolor((1, 0, 0))
e.set_linewidth(4)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffStiffness(N, x, y, D, L, m, mark_print, hn):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C2')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffStiffness2(N, x, y, D, L, m, mark_print, hn, in1, in2, out):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
if i==in1:
e.set_edgecolor((0, 1, 0))
e.set_linewidth(4)
elif i==in2:
e.set_edgecolor((0, 0, 1))
e.set_linewidth(4)
elif i==out:
e.set_edgecolor((1, 0, 0))
e.set_linewidth(4)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C2')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffStiffness3(N, x, y, D, L, m, mark_print, hn, in1, in2, out):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
if i==in1:
e.set_edgecolor((0, 1, 0))
e.set_linewidth(4)
plt.scatter(x_now, y_now, marker='^', s=80, color=(0, 1, 0, 1))
elif i==in2:
e.set_edgecolor((0, 0, 1))
e.set_linewidth(4)
plt.scatter(x_now, y_now, marker='s', s=80, color=(0, 0, 1, 1))
elif i==out:
e.set_edgecolor((1, 0, 0))
e.set_linewidth(4)
plt.scatter(x_now, y_now, marker='*', s=100, color=(1, 0, 0, 1))
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('k')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
import matplotlib.lines as mlines
red_star = mlines.Line2D([], [], color=(1, 0, 0), marker='*', linestyle='None',
markersize=10, label='Output')
blue_square = mlines.Line2D([], [], color=(0, 0, 1), marker='s', linestyle='None',
markersize=10, label='Input 2')
green_triangle = mlines.Line2D([], [], color=(0, 1, 0), marker='^', linestyle='None',
markersize=10, label='Input 1')
plt.legend(handles=[red_star, green_triangle, blue_square], bbox_to_anchor=(1.215, 1))
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_DiffMass_3D(N, x, y, z, D, L, m, mark_print):
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
m_min = min(m)
m_max = max(m)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_aspect('equal')
sphes = []
m_all = []
for i in range(int(N/2)):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
z_now = z[i]%L[2]
r_now = 0.5*D[i]
#alpha_now = 0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3
alpha_now = 0.3
pos1 = 0
pos2 = 1
for j in range(pos1, pos2):
for k in range(pos1, pos2):
for l in range(pos1, pos2):
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x_plot = x_now+j*L[0]+r_now * np.outer(np.cos(u), np.sin(v))
y_plot = y_now+k*L[1]+r_now * np.outer(np.sin(u), np.sin(v))
z_plot = z_now+l*L[2]+r_now * np.outer(np.ones(np.size(u)), np.cos(v))
ymin = y_plot[y_plot>0].min()
ymax = y_plot[y_plot>0].max()
print (i, ymin, ymax)
ax.plot_surface(x_plot,y_plot,z_plot,rstride=4,cstride=4, color='C0',linewidth=0,alpha=alpha_now)
#sphes.append(e)
#m_all.append(m[i])
# i = 0
# for e in sphes:
# ax.add_artist(e)
# e.set_clip_box(ax.bbox)
# e.set_facecolor('C0')
# e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
#e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
# i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
ax.set_zlim(0, L[2])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
def ConfigPlot_YFixed_rec(N, x, y, D, Lx, y_top, y_bot, m, mark_order):
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse, Rectangle
mark_print = 0
m_min = min(m)
m_max = max(m)
if m_min == m_max:
m_max *= 1.001
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%Lx
y_now = y[i]
if mark_order==1:
plt.text(x_now, y_now, str(i))
for k in range(-1, 2):
e = Ellipse((x_now+k*Lx, y_now), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.3+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
#rect = Rectangle([0, y_top], Lx, 0.2*D[0], color='C0')
#ax.add_patch(rect)
for nn in np.arange(N):
x1 = x[nn]%Lx
d_up = y_top-y[nn]
d_bot = y[nn]-y_bot
r_now = 0.5*D[nn]
if d_up<r_now:
ax.plot([x1, x1], [y[nn], y[nn]+r_now], '-', color='w')
if d_bot<r_now:
ax.plot([x1, x1], [y[nn], y[nn]-r_now], '-', color='w')
for mm in np.arange(nn+1, N):
dy = y[mm]-y[nn]
Dmn = 0.5*(D[mm]+D[nn])
if abs(dy) < Dmn:
x2 = x[mm]%Lx
if x2>x1:
xl = x1
xr = x2
yl = y[nn]
yr = y[mm]
else:
xl = x2
xr = x1
yl = y[mm]
yr = y[nn]
dx0 = xr-xl
dx = dx0-round(dx0/Lx)*Lx
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
if dx0<Dmn:
ax.plot([xl, xr], [yl, yr], '-', color='w')
else:
ax.plot([xl, xr-Lx], [yl, yr], '-', color='w')
ax.plot([xl+Lx, xr], [yl, yr], '-', color='w')
ax.set_xlim(0, Lx)
ax.set_ylim(y_bot, y_top)
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/plot_test/fig'+str(int(ind_nt+1e4))+'.png', dpi = 150)
def ConfigPlot_DiffMass_SP(N, x, y, D, L, m, mark_print, ind_in, ind_out, ind_fix):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
width = 2
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m[i]-m_min)/(m_max-m_min)*0.3)
if i == ind_in:
e.set_edgecolor('r')
e.set_linewidth(width)
if i == ind_out:
e.set_edgecolor('b')
e.set_linewidth(width)
if i == ind_fix:
e.set_edgecolor('k')
e.set_linewidth(width)
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
def ConfigPlot_DiffMass_FixLx(N, x, y, D, L, m, mark_print, ind_wall):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
width = 2
for i in range(N):
x_now = x[i]
y_now = y[i]%L[1]
for l in range(-1, 2):
e = Ellipse((x_now, y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
if ind_wall[i] > 0:
e.set_edgecolor('k')
e.set_linewidth(width)
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
def ConfigPlot_DiffMass_SP_rec(N, x, y, D, L, m, mark_print, ind_in, ind_out, ind_fix):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
width = 2
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m[i]-m_min)/(m_max-m_min)*0.3)
if i == ind_in:
e.set_edgecolor('r')
e.set_linewidth(width)
if i == ind_out:
e.set_edgecolor('b')
e.set_linewidth(width)
if i == ind_fix:
e.set_edgecolor('k')
e.set_linewidth(width)
Lx = L[0]
Ly = L[1]
for nn in np.arange(N):
x1 = x[nn]%Lx
y1 = y[nn]%Ly
for mm in np.arange(nn+1, N):
x2 = x[mm]%Lx
y2 = y[mm]%Ly
if x2>x1:
xl = x1
xr = x2
yl = y1
yr = y2
else:
xl = x2
xr = x1
yl = y2
yr = y1
dx0 = xr-xl
dx = dx0-round(dx0/Lx)*Lx
if y2>y1:
xd = x1
xu = x2
yd = y1
yu = y2
else:
xd = x2
xu = x1
yd = y2
yu = y1
dy0 = yu-yd
dy = dy0-round(dy0/Ly)*Ly
Dmn = 0.5*(D[mm]+D[nn])
dmn = np.sqrt(dx**2+dy**2)
if dmn < Dmn:
if dx0<Dmn and dy0<Dmn:
ax.plot([xl, xr], [yl, yr], '-', color='w')
else:
if dx0>Dmn and dy0>Dmn:
if yr>yl:
ax.plot([xl, xr-Lx], [yl, yr-Ly], '-', color='w')
ax.plot([xl+Lx, xr], [yl+Ly, yr], '-', color='w')
else:
ax.plot([xl, xr-Lx], [yl, yr+Ly], '-', color='w')
ax.plot([xl+Lx, xr], [yl-Ly, yr], '-', color='w')
else:
if dx0>Dmn:
ax.plot([xl, xr-Lx], [yl, yr], '-', color='w')
ax.plot([xl+Lx, xr], [yl, yr], '-', color='w')
if dy0>Dmn:
ax.plot([xd, xu], [yd, yu-Ly], '-', color='w')
ax.plot([xd, xu], [yd+Ly, yu], '-', color='w')
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig('/Users/Hightoutou/Desktop/fig.png', dpi = 300)
return fig
def ConfigPlot_EigenMode_DiffMass(N, x, y, D, L, m, em, mark_print, hn):
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
m_min = min(m)
m_max = max(m)
if m_min == m_max:
m_max *= 1.001
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
m_all = []
for i in range(N):
x_now = x[i]%L[0]
y_now = y[i]%L[1]
for k in range(-1, 2):
for l in range(-1, 2):
e = Ellipse((x_now+k*L[0], y_now+l*L[1]), D[i],D[i],0)
ells.append(e)
m_all.append(m[i])
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.3)
i += 1
r_now = D[0]*0.5
dr = np.zeros(N)
for i in range(N):
dr[i] = np.sqrt(em[2*i]**2+em[2*i+1]**2)
dr_max = max(dr)
for i in range(N):
ratio = dr[i]/dr_max*r_now/dr_max
plt.arrow(x[i], y[i],em[2*i]*ratio, em[2*i+1]*ratio, head_width=0.005)
ax.set_xlim(0, L[0])
ax.set_ylim(0, L[1])
plt.show()
if mark_print == 1:
fig.savefig(hn, dpi = 300)
return fig
def ConfigPlot_YFixed_SelfAssembly(N, Nl, x, y, theta, n, d1, d2, Lx, y_top, y_bot):
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse, Rectangle
mark_order = 0
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
alpha_all = []
alpha1 = 0.6
alpha2 = 0.3
for i in range(N):
x_now = x[i]%Lx
y_now = y[i]
if mark_order==1:
plt.text(x_now, y_now, str(i))
alpha = alpha1 if i < Nl else alpha2
for k in range(-1, 2):
e = Ellipse((x_now+k*Lx, y_now), d1,d1,0)
ells.append(e)
alpha_all.append(alpha)
if i >= Nl:
for ind in range(n):
x_i = x_now+k*Lx+0.5*(d1+d2)*np.cos(theta[i]+ind*2*np.pi/n)
y_i = y_now+0.5*(d1+d2)*np.sin(theta[i]+ind*2*np.pi/n)
e = Ellipse((x_i, y_i), d2,d2,0)
ells.append(e)
alpha_all.append(alpha)
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(alpha_all[i])
i += 1
ax.set_xlim(0, Lx)
ax.set_ylim(y_bot, y_top)
plt.show()
def ConfigPlot_YFixed_SelfAssembly_BumpyBd(N, n_col, Nl, x, y, theta, n, d0, d1, d2, Lx, y_top, y_bot):
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse, Rectangle
mark_order = 0
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ells = []
alpha_all = []
alpha1 = 0.6
alpha2 = 0.3
for i in range(n_col+1):
x_now = i*d0
e1 = Ellipse((x_now, y_bot), d0,d0,0)
e2 = Ellipse((x_now, y_top), d0,d0,0)
ells.append(e1)
alpha_all.append(alpha1)
ells.append(e2)
alpha_all.append(alpha1)
for i in range(N):
x_now = x[i]%Lx
y_now = y[i]
if mark_order==1:
plt.text(x_now, y_now, str(i))
alpha = alpha1 if i < Nl else alpha2
for k in range(-1, 2):
e = Ellipse((x_now+k*Lx, y_now), d1,d1,0)
ells.append(e)
alpha_all.append(alpha)
if i >= Nl:
for ind in range(n):
x_i = x_now+k*Lx+0.5*(d1+d2)*np.cos(theta[i]+ind*2*np.pi/n)
y_i = y_now+0.5*(d1+d2)*np.sin(theta[i]+ind*2*np.pi/n)
e = Ellipse((x_i, y_i), d2,d2,0)
ells.append(e)
alpha_all.append(alpha)
i = 0
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_facecolor('C0')
#e.set_alpha(0.2+(m_all[i]-m_min)/(m_max-m_min)*0.8)
e.set_alpha(alpha_all[i])
i += 1
ax.set_xlim(0, Lx)
ax.set_ylim(y_bot, y_top)
plt.show()
| 22,835 | 29.488652 | 117 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/genome_seed_binary.py
|
import constants as c
from individual_seed_binary import INDIVIDUAL
import pickle
class GENOME:
def __init__(self,ID,fitness=c.worstFitness):
self.Set_ID(ID)
self.indv = INDIVIDUAL(ID)
self.age = 0
self.fitness = fitness
def Age(self):
self.age = self.age + 1
def Dominates(self,other):
if self.Get_Fitness() <= other.Get_Fitness():
if self.Get_Age() <= other.Get_Age():
equalFitnesses = self.Get_Fitness() == other.Get_Fitness()
equalAges = self.Get_Age() == other.Get_Age()
if not equalFitnesses and equalAges:
return True
else:
return self.Is_Newer_Than(other)
else:
return False
else:
return False
def Evaluate(self):
#self.indv.Start_Evaluation(True)
f = self.indv.Compute_Fitness()
# if f < 0:
# self.fitness = c.worstFitness
# else:
# self.fitness = 1/(1+f)
self.fitness = -f
#print(f)
#print(self.indv.genome)
return self.fitness
def Get_Age(self):
return self.age
def Get_Fitness(self):
return self.fitness
def Mutate(self):
self.indv.Mutate()
def Print(self):
print(' fitness: ' , end = '' )
print(self.fitness , end = '' )
print(' age: ' , end = '' )
print(self.age , end = '' )
print()
def Save(self,randomSeed):
f = open('savedRobotsAfpoSeed.dat', 'ab')
pickle.dump(self.indv , f)
f.close()
pass
def Set_ID(self,ID):
self.ID = ID
def Show(self):
#self.indv.Start_Evaluation(False, 40)
self.indv.Compute_Fitness(True)
# def __add__(self, other):
# total_fitness = self.fitness + other.fitness
# print("I've been called")
# return GENOME(1, total_fitness)
# def __radd__(self, other):
# if other == 0:
# return self
# else:
# return self.__add__(other)
# -------------------- Private methods ----------------------
def Get_ID(self):
return self.ID
def Is_Newer_Than(self,other):
return self.Get_ID() > other.Get_ID()
| 2,336 | 24.681319 | 74 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/afpoPlots_seed_binary.py
|
import pickle
import matplotlib.pyplot as plt
from switch_binary import switch
import constants as c
import numpy
runs = c.RUNS
gens = c.numGenerations
fitnesses = numpy.zeros([runs, gens])
temp = []
individuals = []
with open('savedRobotsAfpoSeed.dat', "rb") as f:
for r in range(1, runs+1):
for g in range(1, gens+1):
try:
temp.append(pickle.load(f).fitness)
except EOFError:
break
fitnesses[r-1] = temp
temp = []
f.close()
mean_f = numpy.mean(fitnesses, axis=0)
std_f = numpy.std(fitnesses, axis=0)
plt.figure(figsize=(6.4,4.8))
plt.plot(list(range(1, gens+1)), mean_f, color='blue')
plt.fill_between(list(range(1, gens+1)), mean_f-std_f, mean_f+std_f, color='cornflowerblue', alpha=0.2)
plt.xlabel("Generations")
plt.ylabel("Best Fitness")
plt.title("Fitness of the Best Individual in the Population - AFPO", fontsize='small')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.tight_layout()
#plt.legend(['two robot', 'three robots'], loc='upper left')
#plt.savefig("compare.pdf")
plt.show()
# running the best individuals
m1 = 1
m2 = 10
N_light = 9
N = 30
bests = numpy.zeros([runs, gens])
temp = []
rubish = []
with open('savedRobotsLastGenAfpoSeed.dat', "rb") as f:
for r in range(1, runs+1):
# population of the last generation
temp = pickle.load(f)
# best individual of last generation
best = temp[0]
switch.showPacking(m1, m2, N_light, best.indv.genome)
print(switch.evaluate(m1, m2, N_light, best.indv.genome))
print(switch.evaluateAndPlot(m1, m2, N_light, best.indv.genome))
temp = []
f.close()
# running all of the individuals of the last generation of each of the runs
bests = numpy.zeros([runs, gens])
temp = []
rubish = []
with open('savedRobotsLastGenAfpoSeed.dat', "rb") as f:
for r in range(1, runs+1):
print("run:")
print(r)
# population of the last generation
temp = pickle.load(f)
for g in range(0, gens):
switch.showPacking(m1, m2, N_light, temp[g].indv.genome)
print(switch.evaluateAndPlot(m1, m2, N_light, temp[g].indv.genome))
temp = []
f.close()
| 2,217 | 28.972973 | 103 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/evolveAfpo_seed_binary.py
|
from afpo_seed_binary import AFPO
import os
import constants as c
import random
#cleaning up the data files
try:
os.remove("savedRobotsLastGenAfpoSeed.dat")
except OSError:
pass
try:
os.remove("avgFitnessAfpoSeed.dat")
except OSError:
pass
try:
os.remove("savedRobotsAfpoSeed.dat")
except OSError:
pass
runs = c.RUNS
for r in range(1, runs+1):
print("*********************************************************", flush=True)
print("run: "+str(r), flush=True)
randomSeed = r
random.seed(r)
afpo = AFPO(randomSeed)
afpo.Evolve()
#afpo.Show_Best_Genome()
| 616 | 18.28125 | 82 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/individual_seed_binary.py
|
from switch_binary import switch
import constants as c
import random
import math
import numpy as np
import sys
import pickle
class INDIVIDUAL:
def __init__(self, i):
# assuming curves have one control point, [Sx, Ex, Cx, Cy] for each fiber
# assuming we have two planes, each with c.FIBERS of fibers on them
self.m1 = 1
self.m2 = 10 #[2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000] #10 is what is in fig2 of the paper
self.N_light = 9 #[25, 50, 75] #[9, 15, 21]
self.N = 30
#self.low = 7
#self.high = 12
#indices = random.sample(range(0, N), N_light)
self.genome = np.random.randint(low=0, high=2, size=self.N)#random.sample(range(0, self.N), self.N_light) #np.random.randint(0, high=c.GRID_SIZE-1, size=(c.FIBERS*2, 4), dtype='int')
self.fitness = 0
self.ID = i
def Compute_Fitness(self, show=False):
# wait for the simulation to end and get the fitness
self.fitness = switch.evaluate(self.m1, self.m2, self.N_light, self.genome)#, self.low, self.high)
if show:
switch.showPacking(self.m1, self.m2, self.N_light, self.genome)#, self.low, self.high)
print("fitness is:")
print(self.fitness)
return self.fitness
def Mutate(self):
mutationRate = 0.05
probToMutate = np.random.choice([False, True], size=self.genome.shape, p=[1-mutationRate, mutationRate])
candidate = np.where(probToMutate, 1-self.genome, self.genome)
self.genome = candidate
def Print(self):
print('[', self.ID, self.fitness, ']', end=' ')
def Save(self):
f = open('savedFitnessSeed.dat', 'ab')
pickle.dump(self.fitness , f)
f.close()
def SaveBest(self):
f = open('savedBestsSeed.dat', 'ab')
pickle.dump(self.genome , f)
f.close()
| 1,936 | 35.54717 | 190 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/randomSearch2.py
|
from switch_binary import switch
import matplotlib.pyplot as plt
import random
import numpy as np
from joblib import Parallel, delayed
import multiprocessing
import pickle
from scipy.stats import norm
import operator
from ConfigPlot import ConfigPlot_DiffStiffness3
with open('outs.dat', "rb") as f:
outs = pickle.load(f)
f.close()
with open('samples.dat', "rb") as f:
samples = pickle.load(f)
f.close()
# compute the cumulative sum
#Nk_cum = np.cumsum(Nk)
# go to log scale
#log_Nk_cum = np.log10(Nk_cum)
#log_k = np.log10(k)
# plot the original data
#fig = plt.figure()
#ax = plt.gca()
#ax.scatter(log_k, log_Nk_cum, s=5, alpha=0.3)
#ax.set_title('CCDF in log-log scale')
#ax.set_xlabel('$Log_{10}(k)$')
#ax.set_ylabel('$Log_{10}(Nk_{>k})$')
def showPacking(indices):
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
m1=1
m2=10
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
# show packing
ConfigPlot_DiffStiffness3(N, x0, y0, D, [Lx,Ly], k_type, 0, '/Users/atoosa/Desktop/results/packing.pdf', ind_in1, ind_in2, ind_out)
print("done", flush=True)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
n, bins, patches = plt.hist(x=outs, bins='auto', color='#0504aa', alpha=0.7, cumulative=False)#, grid=True)
# fitting a normal distribution
mu, std = norm.fit(outs)
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 1000)
p = norm.pdf(x, mu, std)
#plt.plot(x, p, linewidth=2)
myText = "Mean={:.3f}, STD={:.3f}".format(mu, std)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize='medium', color='g')
plt.xlabel('XOR-Ness')
plt.ylabel('Counts')
plt.title('Random Search', fontsize='medium')
#plt.xlim([0, 8])
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
#plt.show()
plt.savefig("histogram2.jpg", dpi=300)
sortedList = list(zip(*sorted(zip(samples,outs), key=operator.itemgetter(1))))
showPacking(sortedList[0][0])
print(sortedList[1][0])
showPacking(sortedList[0][-1])
print(sortedList[1][-1])
showPacking(sortedList[0][-2])
print(sortedList[1][-2])
| 3,171 | 25 | 138 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/plot_functions.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 22 14:48:04 2017
@author: Hightoutou
"""
import matplotlib.pyplot as plt
#import matplotlib
#matplotlib.use('TkAgg')
def Line_single(xdata, ydata, line_spec, xlabel, ylabel, mark_print, fn = '', xscale='linear', yscale='linear'):
fig, ax1 = plt.subplots()
fig.set_size_inches(3.5,3.5*3/4)
pos1 = ax1.get_position()
pos2 = [pos1.x0 + 0.12, pos1.y0 + 0.05, pos1.width-0.1, pos1.height]
ax1.set_position(pos2)
#ax1.tick_params(labelsize=10)
for axis in ['top','bottom','left','right']:
ax1.spines[axis].set_linewidth(2)
plt.ylabel(ylabel, fontsize=12)
plt.xlabel(xlabel, fontsize=12)
plt.xscale(xscale), plt.yscale(yscale)
plt.style.use('default')
ax1.plot(xdata, ydata, line_spec)
if mark_print == 1:
fig.savefig(fn, dpi = 300)
fig.show()
def Line_multi(xdata, ydata, line_spec, xlabel, ylabel, xscale='linear', yscale='linear'):
fig, ax1 = plt.subplots()
fig.set_size_inches(3.5,3.5*3/4)
ax1.tick_params(labelsize=10)
for axis in ['top','bottom','left','right']:
ax1.spines[axis].set_linewidth(2)
ax1.set_ylabel(ylabel, fontsize=12)
plt.xlabel(xlabel, fontsize=12)
plt.xscale(xscale), plt.yscale(yscale)
plt.style.use('default')
for ii in range(len(xdata)):
ax1.plot(xdata[ii], ydata[ii], line_spec[ii])
plt.show()
def Line_yy(xdata, ydata, line_spec, xlabel, ylabel, xscale='linear', yscale='linear'):
fig, ax1 = plt.subplots()
fig.set_size_inches(3.5,3.5*3/4)
ax1.tick_params(labelsize=10)
for axis in ['top','bottom','left','right']:
ax1.spines[axis].set_linewidth(2)
ax1.set_ylabel(ylabel[0], fontsize=12)
plt.xlabel(xlabel, fontsize=12)
plt.xscale(xscale), plt.yscale(yscale)
plt.style.use('default')
ax1.plot(xdata[0], ydata[0], line_spec[0])
ax2 = ax1.twinx()
ax2.set_ylabel(ylabel[1], fontsize=12)
ax2.plot(xdata[1], ydata[1], line_spec[1])
plt.show()
| 2,062 | 33.966102 | 112 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/FFT_functions.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 17 15:10:21 2017
@author: Hightoutou
"""
import numpy as np
import matplotlib.pyplot as plt
from plot_functions import Line_multi, Line_single
#from numba import jit
def FFT_Fup(Nt, F, dt, Freq_Vibr):
sampling_rate = 1/dt
t = np.arange(Nt)*dt
fft_size = Nt
xs = F[:fft_size]
xf = np.absolute(np.fft.rfft(xs)/fft_size)
freqs = (2*np.pi)*np.linspace(0, sampling_rate/2, fft_size//2+1)
ind = freqs<30
freqs = freqs[ind]
xf = xf[ind]
if 1 == 0:
Line_multi([freqs[1:], [Freq_Vibr, Freq_Vibr]], [xf[1:], [min(xf[1:]), max(xf[1:])]], ['o', 'r--'], 'Frequency', 'FFT', 'linear', 'log')
return freqs[1:], xf[1:]
def FFT_Fup_RealImag(Nt, F, dt, Freq_Vibr):
sampling_rate = 1/dt
t = np.arange(Nt)*dt
fft_size = Nt
xs = F[:fft_size]
xf = np.fft.rfft(xs)/fft_size
freqs = (2*np.pi)*np.linspace(0, sampling_rate/2, fft_size/2+1)
ind = freqs<30
freqs = freqs[ind]
xf = xf[ind]
xf_real = xf.real
xf_imag = xf.imag
if 1 == 0:
Line_multi([freqs[1:], [Freq_Vibr, Freq_Vibr]], [xf[1:], [min(xf[1:]), max(xf[1:])]], ['o', 'r--'], 'Frequency', 'FFT')
return freqs[1:], xf_real[1:], xf_imag[1:]
#@jit
def vCorr_Cal(fft_size, Nt, y_raw):
y_fft = np.zeros(fft_size)
for jj in np.arange(fft_size):
sum_vcf = 0
sum_tt = 0
count = 0
for kk in np.arange(Nt-jj):
count = count+1
sum_vcf += y_raw[kk]*y_raw[kk+jj];
sum_tt = sum_tt+y_raw[kk]*y_raw[kk];
y_fft[jj] = sum_vcf/sum_tt;
return y_fft
def FFT_vCorr(Nt, N, vx_rec, vy_rec, dt):
sampling_rate = 1/dt
fft_size = Nt-1
freqs = (2*np.pi)*np.linspace(0, sampling_rate/2, fft_size/2+1)
for ii in np.arange(2*N):
#for ii in [0,4]:
if np.mod(ii, 10) == 0:
print('ii=%d\n' % (ii))
if ii >= N:
y_raw = vy_rec[:, ii-N]
else:
y_raw = vx_rec[:, ii]
y_fft = vCorr_Cal(fft_size, Nt, y_raw)
if ii == 0:
xf = np.absolute(np.fft.rfft(y_fft)/fft_size)
else:
xf += np.absolute(np.fft.rfft(y_fft)/fft_size)
ind = freqs<30
freqs = freqs[ind]
xf = xf[ind]
if 1 == 1:
Line_single(freqs[1:], xf[1:], 'o', 'Frequency', 'FFT')
return freqs[1:], xf[1:]
def FFT_vCorr_3D(Nt, N, vx_rec, vy_rec, vz_rec, dt):
sampling_rate = 1/dt
fft_size = Nt-1
freqs = (2*np.pi)*np.linspace(0, sampling_rate/2, fft_size/2+1)
for ii in np.arange(3*N):
#for ii in [0,4]:
if np.mod(ii, 10) == 0:
print('ii=%d\n' % (ii))
if ii >= 2*N:
y_raw = vz_rec[:, ii-2*N]
elif ii < N:
y_raw = vx_rec[:, ii]
else:
y_raw = vy_rec[:, ii-N]
y_fft = vCorr_Cal(fft_size, Nt, y_raw)
if ii == 0:
xf = np.absolute(np.fft.rfft(y_fft)/fft_size)
else:
xf += np.absolute(np.fft.rfft(y_fft)/fft_size)
ind = freqs<30
freqs = freqs[ind]
xf = xf[ind]
if 1 == 1:
Line_single(freqs[1:], xf[1:], 'o', 'Frequency', 'FFT')
return freqs[1:], xf[1:]
| 3,487 | 25.225564 | 152 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/randomSearch.py
|
from switch_binary import switch
import matplotlib.pyplot as plt
import random
import numpy as np
from joblib import Parallel, delayed
import multiprocessing
import pickle
m1 = 1
m2 = 10
N = 30
N_light = 9
samples = []
print("sampling", flush=True)
for i in range(0, 5001):
samples.append(np.random.randint(low=0, high=2, size=N))
print("sampling done", flush=True)
num_cores = multiprocessing.cpu_count()
outs = Parallel(n_jobs=num_cores)(delayed(switch.evaluate)(m1, m2, N_light, samples[i]) for i in range(0, 5001))
print("done", flush=True)
f = open('outs.dat', 'ab')
pickle.dump(outs , f)
f.close()
f = open('samples.dat', 'ab')
pickle.dump(samples , f)
f.close()
n, bins, patches = plt.hist(x=outs, bins='auto', color='#0504aa', alpha=0.7, rwidth=0.85)#, grid=True)
plt.xlabel('Andness')
plt.ylabel('Counts')
plt.title('Random Search')
#plt.xlim([0, 8])
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.show()
plt.savefig("histogram.jpg", dpi=300)
| 978 | 21.767442 | 112 |
py
|
gecco-2022
|
gecco-2022-main/RandomSearch/XOR-NESS/plotInOut.py
|
import constants as c
import numpy as np
from ConfigPlot import ConfigPlot_DiffStiffness2
from MD_functions import MD_VibrSP_ConstV_Yfixed_DiffK, FIRE_YFixed_ConstV_DiffK, MD_VibrSP_ConstV_Yfixed_DiffK2
from DynamicalMatrix import DM_mass_DiffK_Yfixed
import random
import matplotlib.pyplot as plt
import pickle
from os.path import exists
from switch_binary import switch
def showPacking(indices):
k1 = 1.
k2 = 10.
n_col = 6
n_row = 5
N = n_col*n_row
m1=1
m2=10
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
# show packing
ConfigPlot_DiffStiffness2(N, x0, y0, D, [Lx,Ly], k_type, 0, '/Users/atoosa/Desktop/results/packing.pdf', ind_in1, ind_in2, ind_out)
def plotInOut(indices):
#%% Initial Configuration
k1 = 1.
k2 = 10.
m1 = 1
m2 = 10
n_col = 6
n_row = 5
N = n_col*n_row
Nt_fire = 1e6
dt_ratio = 40
Nt_SD = 1e5
Nt_MD = 1e5
dphi_index = -1
dphi = 10**dphi_index
d0 = 0.1
d_ratio = 1.1
Lx = d0*n_col
Ly = (n_row-1)*np.sqrt(3)/2*d0+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
phi0 = N*np.pi*d0**2/4/(Lx*Ly)
d_ini = d0*np.sqrt(1+dphi/phi0)
D = np.zeros(N)+d_ini
#D = np.zeros(N)+d0
x0 = np.zeros(N)
y0 = np.zeros(N)
for i_row in range(1, n_row+1):
for i_col in range(1, n_col+1):
ind = (i_row-1)*n_col+i_col-1
if i_row%2 == 1:
x0[ind] = (i_col-1)*d0
else:
x0[ind] = (i_col-1)*d0+0.5*d0
y0[ind] = (i_row-1)*np.sqrt(3)/2*d0
y0 = y0+0.5*d0
mass = np.zeros(N) + 1
k_list = np.array([k1, k2, k1 * k2 / (k1 + k2)])
k_type = indices #np.zeros(N, dtype=np.int8)
#k_type[indices] = 1
# Steepest Descent to get energy minimum
#x_ini, y_ini, p_now = MD_YFixed_ConstV_SP_SD_DiffK(Nt_SD, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
x_ini, y_ini, p_now = FIRE_YFixed_ConstV_DiffK(Nt_fire, N, x0, y0, D, mass, Lx, Ly, k_list, k_type)
# skip the steepest descent for now to save time
#x_ini = x0
#y_ini = y0
# calculating the bandgap - no need to do this in this problem
w, v = DM_mass_DiffK_Yfixed(N, x_ini, y_ini, D, mass, Lx, 0.0, Ly, k_list, k_type)
w = np.real(w)
v = np.real(v)
freq = np.sqrt(np.absolute(w))
ind_sort = np.argsort(freq)
freq = freq[ind_sort]
v = v[:, ind_sort]
ind = freq > 1e-4
eigen_freq = freq[ind]
eigen_mode = v[:, ind]
w_delta = eigen_freq[1:] - eigen_freq[0:-1]
index = np.argmax(w_delta)
F_low_exp = eigen_freq[index]
F_high_exp = eigen_freq[index+1]
plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.scatter(np.arange(0, len(eigen_freq)), eigen_freq, marker='x', color='blue')
plt.xlabel("Number")
plt.ylabel("Frequency")
plt.title("Vibrational Response", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
props = dict(facecolor='green', alpha=0.1)
myText = 'f_low='+"{:.2f}".format(F_low_exp)+"\n"+'f_high='+"{:.2f}".format(F_high_exp)+"\n"+'band gap='+"{:.2f}".format(max(w_delta))
plt.text(0.85, 0.1, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize='large', bbox=props)
plt.tight_layout()
plt.show()
print("specs:")
print(F_low_exp)
print(F_high_exp)
print(max(w_delta))
# specify the input ports and the output port
SP_scheme = 0
digit_in = SP_scheme//2
digit_out = SP_scheme-2*digit_in
ind_in1 = int((n_col+1)/2)+digit_in - 1
ind_in2 = ind_in1 + 2
ind_out = int(N-int((n_col+1)/2)+digit_out)
ind_fix = int((n_row+1)/2)*n_col-int((n_col+1)/2)
B = 1
Nt = 1e4 # it was 1e5 before, i reduced it to run faster
# we are designing an and gait at this frequency
Freq_Vibr = 7
# case 1, input [1, 1]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out1 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain1 = out1/(inp1+inp2)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='Input1', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency")
plt.ylabel("Amplitude of FFT")
plt.title("Logic Gate Response - input = 11", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right')
plt.tight_layout()
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
myText = 'Gain='+"{:.3f}".format(gain1)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize='medium')
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='Input1', linestyle='solid')
plt.plot(x_in2, color='blue', label='Input2', linestyle='solid')
plt.plot(x_out, color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps")
plt.ylabel("Amplitude of Displacement")
plt.title("Logic Gate Response - input = 11", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right')
plt.tight_layout()
plt.show()
# case 2, input [1, 0]
Amp_Vibr1 = 1e-2
Amp_Vibr2 = 0
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out2 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain2 = out2/(inp1+inp2)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='Input1', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency")
plt.ylabel("Amplitude of FFT")
plt.title("Logic Gate Response - input = 10", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right')
plt.tight_layout()
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
myText = 'Gain='+"{:.3f}".format(gain2)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize='medium')
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='Input1', linestyle='solid')
plt.plot(x_in2, color='blue', label='Input2', linestyle='solid')
plt.plot(x_out, color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps")
plt.ylabel("Amplitude of Displacement")
plt.title("Logic Gate Response - input = 10", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right')
plt.tight_layout()
plt.show()
# case 3, input [0, 1]
Amp_Vibr1 = 0
Amp_Vibr2 = 1e-2
# changed the resonator to one in MD_functions file and vibrations in x direction
freq_fft, fft_in1, fft_in2, fft_x_out, fft_y_out, mean_cont, nt_rec, Ek_now, Ep_now, cont_now = MD_VibrSP_ConstV_Yfixed_DiffK(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
ind = np.where(freq_fft>Freq_Vibr)
index_=ind[0][0]
# fft of the output port at the driving frequency
out3 = fft_x_out[index_-1] + (fft_x_out[index_]-fft_x_out[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input1 at driving frequency
inp1 = fft_in1[index_-1] + (fft_in1[index_]-fft_in1[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
# fft of input2 at driving frequency
inp2 = fft_in2[index_-1] + (fft_in2[index_]-fft_in2[index_-1])*((Freq_Vibr-freq_fft[index_-1])/(freq_fft[index_]-freq_fft[index_-1]))
gain3 = out3/(inp1+inp2)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(freq_fft, fft_in1, color='green', label='Input1', linestyle='dotted')
plt.plot(freq_fft, fft_in2, color='blue', label='Input2', linestyle=(0, (3, 5, 1, 5)))
plt.plot(freq_fft, fft_x_out, color='red', label='Output', linestyle='dashed')
plt.xlabel("Frequency")
plt.ylabel("Amplitude of FFT")
plt.title("Logic Gate Response - input = 01", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right')
plt.tight_layout()
#plt.axvline(x=Freq_Vibr, color='purple', linestyle='solid', alpha=0.5)
myText = 'Gain='+"{:.3f}".format(gain3)
plt.text(0.5, 0.9, myText, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize='medium')
plt.show()
x_in1, x_in2, x_out = MD_VibrSP_ConstV_Yfixed_DiffK2(k_list, k_type, B, Nt, N, x_ini, y_ini, D, mass, [Lx, Ly], Freq_Vibr, Amp_Vibr1, ind_in1, Amp_Vibr2, ind_in2, ind_out)
fig = plt.figure(figsize=(6.4,4.8))
ax = plt.axes()
plt.plot(x_in1, color='green', label='Input1', linestyle='solid')
plt.plot(x_in2, color='blue', label='Input2', linestyle='solid')
plt.plot(x_out, color='red', label='Output', linestyle='solid')
plt.xlabel("Time Steps")
plt.ylabel("Amplitude of Displacement")
plt.title("Logic Gate Response - input = 01", fontsize='medium')
plt.grid(color='skyblue', linestyle=':', linewidth=0.5)
plt.legend(loc='upper right')
plt.tight_layout()
plt.show()
print("gain1:")
print(gain1)
print("gain2:")
print(gain2)
print("gain3:")
print(gain3)
andness = 2*gain1/(gain2+gain3)
return andness
runs = c.RUNS
gens = c.numGenerations
# running the best individuals
temp = []
rubish = []
with open('savedRobotsLastGenAfpoSeed.dat', "rb") as f:
for r in range(1, runs+1):
# population of the last generation
temp = pickle.load(f)
# best individual of last generation
best = temp[0]
showPacking(best.indv.genome)
print(plotInOut(best.indv.genome))
temp = []
f.close()
| 13,392 | 35.997238 | 248 |
py
|
python-urx
|
python-urx-master/setup.py
|
from setuptools import setup
setup(
name="urx",
version="0.11.0",
description="Python library to control an UR robot",
author="Olivier Roulet-Dubonnet",
author_email="[email protected]",
url='https://github.com/oroulet/python-urx',
packages=["urx"],
provides=["urx"],
install_requires=["numpy", "math3d"],
license="GNU Lesser General Public License v3",
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Topic :: System :: Hardware :: Hardware Drivers",
"Topic :: Software Development :: Libraries :: Python Modules",
])
| 778 | 32.869565 | 71 |
py
|
python-urx
|
python-urx-master/make_deb.py
|
#!/usr/bin/python3
"""
hackish file to crreate deb from setup.py
"""
import subprocess
from email.utils import formatdate
import urx
DEBVERSION = urx.__version__
branch = subprocess.check_output("git rev-parse --abbrev-ref HEAD", shell=True)
branch = branch.decode()
branch = branch.strip()
branch = str(branch).replace("'","")
rev = subprocess.check_output("git log -1 --format=\'%ad--%h\' --date=short", shell=True)
rev = rev.decode()
rev = rev.strip()
rev = rev.replace("'","")
#rev = rev.replace(" ", "T", 1)
#ev = rev.replace(" ", "Z", 1)
vcsstring = "git-" + branch + "-" + rev
def get_changelog(progname, version, changelog, date):
"""
return a dummy changelog acceptable by debian script engine
"""
return """%s (%s) unstable; urgency=low
%s
-- Olivier R-D <unknown@unknown> %s """ % (progname, version, changelog, date)
def check_deb(name):
print("checking if %s is installed" % name)
subprocess.check_call("dpkg -s %s > /dev/null" % name, shell=True)
if __name__ == "__main__":
check_deb("build-essential")
f = open("debian/changelog", "w")
f.write(get_changelog("python-urx", DEBVERSION + vcsstring, "Updated to last changes in repository", formatdate()))
f.close()
#now build package
#subprocess.check_call("dpkg-buildpackage -rfakeroot -uc -us -b", shell=True)
subprocess.check_call("fakeroot dh binary --with python3,python2", shell=True)
subprocess.check_call("dh clean", shell=True)
| 1,478 | 24.947368 | 119 |
py
|
python-urx
|
python-urx-master/release.py
|
import re
import os
def bump_version():
with open("setup.py") as f:
s = f.read()
m = re.search(r'version="(.*)\.(.*)\.(.*)",', s)
v1, v2, v3 = m.groups()
oldv = "{0}.{1}.{2}".format(v1, v2, v3)
newv = "{0}.{1}.{2}".format(v1, v2, str(int(v3) + 1))
print("Current version is: {0}, write new version, ctrl-c to exit".format(oldv))
ans = input(newv)
if ans:
newv = ans
s = s.replace(oldv, newv)
with open("setup.py", "w") as f:
f.write(s)
return newv
def release():
v = bump_version()
ans = input("version bumped, commiting?(Y/n)")
if ans in ("", "y", "yes"):
os.system("git add setup.py")
os.system("git commit -m 'new release'")
os.system("git tag {0}".format(v))
ans = input("change committed, push to server?(Y/n)")
if ans in ("", "y", "yes"):
os.system("git push")
os.system("git push --tags")
ans = input("upload to pip?(Y/n)")
if ans in ("", "y", "yes"):
os.system("rm -rf dist/*")
os.system("python setup.py sdist")
os.system("twine upload dist/*")
if __name__ == "__main__":
release()
| 1,197 | 27.52381 | 84 |
py
|
python-urx
|
python-urx-master/tools/find_packet.py
|
from urx import ursecmon
if __name__ == "__main__":
f = open("packets.bin", "rb")
s = open("packet.bin", "wb")
data = f.read(99999)
parser = ursecmon.ParserUtils()
p, rest = parser.find_first_packet(data)
print(len(p))
p, rest = parser.find_first_packet(rest)
print(len(p))
s.write(p)
p, rest = parser.find_first_packet(rest)
print(len(p))
| 385 | 24.733333 | 44 |
py
|
python-urx
|
python-urx-master/tools/grabber.py
|
import socket
import sys
if __name__ == "__main__":
host, port = "localhost", 30002
host, port = "192.168.1.8", 30002
if len(sys.argv) > 1:
host = sys.argv[1]
sock = socket.create_connection((host, port))
f = open("packets.bin", "wb")
try:
# Connect to server and send data
for i in range(0, 20):
data = sock.recv(1024)
f.write(data)
print("Got packet: ", i)
finally:
f.close()
sock.close()
| 500 | 19.875 | 49 |
py
|
python-urx
|
python-urx-master/tools/get_rob.py
|
#!/usr/bin/env python
import sys
import logging
from math import pi
from IPython import embed
from urx import Robot
import math3d
if __name__ == "__main__":
if len(sys.argv) > 1:
host = sys.argv[1]
else:
host = 'localhost'
try:
robot = Robot(host)
r = robot
embed()
finally:
if "robot" in dir():
robot.close()
| 389 | 15.956522 | 28 |
py
|
python-urx
|
python-urx-master/tools/fakerobot.py
|
import socket
import threading
import socketserver
import time
class RequestHandler(socketserver.BaseRequestHandler):
#def __init__(self, *args, **kwargs):
#print(self, *args, **kwargs)
#print("Got connection from {}".format( self.client_address[0]) )
#socketserver.BaseRequestHandler.__init__(self, *args, **kwargs)
def handle(self):
while True:
data = str(self.request.recv(1024), 'ascii')
cur_thread = threading.current_thread()
print("{} received {} from {}".format(cur_thread.name, data, self.client_address) )
if data == "":
return
#when this methods returns, the connection to the client closes
def setup(self):
print("Got new connection from {}".format( self.client_address) )
self.server.handlers.append(self)
def finish(self):
print("Connection from {} lost".format( self.client_address) )
self.server.handlers.remove(self)
class Server(socketserver.ThreadingMixIn, socketserver.TCPServer):
def init(self):
"""
__init__ should not be overriden
"""
self.handlers = []
def close(self):
for handler in self.handlers:
handler.request.shutdown(socket.SHUT_RDWR)
handler.request.close()
self.shutdown()
class FakeRobot(object):
def run(self):
host = "localhost"
port = 30002
server = Server((host, port), RequestHandler)
server.init()
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
print("Fake Universal robot running at ", host, port)
try:
f = open("packet.bin", "rb")
packet = f.read()
f.close()
while True:
time.sleep(0.09) #The real robot published data 10 times a second
for handler in server.handlers:
handler.request.sendall(packet)
finally:
print("Shutting down server")
server.close()
if __name__ == "__main__":
r = FakeRobot()
r.run()
| 2,177 | 28.432432 | 95 |
py
|
python-urx
|
python-urx-master/examples/test_movep.py
|
import time
import urx
import logging
if __name__ == "__main__":
rob = urx.Robot("192.168.1.6")
try:
l = 0.1
v = 0.07
a = 0.1
r = 0.05
pose = rob.getl()
pose[2] += l
rob.movep(pose, acc=a, vel=v, radius=r, wait=False)
while True:
p = rob.getl(wait=True)
if p[2] > pose[2] - 0.05:
break
pose[1] += l
rob.movep(pose, acc=a, vel=v, radius=r, wait=False)
while True:
p = rob.getl(wait=True)
if p[1] > pose[1] - 0.05:
break
pose[2] -= l
rob.movep(pose, acc=a, vel=v, radius=r, wait=False)
while True:
p = rob.getl(wait=True)
if p[2] < pose[2] + 0.05:
break
pose[1] -= l
rob.movep(pose, acc=a, vel=v, radius=0, wait=True)
finally:
rob.close()
| 914 | 21.317073 | 59 |
py
|
python-urx
|
python-urx-master/examples/get_robot.py
|
import urx
from IPython import embed
import logging
if __name__ == "__main__":
try:
logging.basicConfig(level=logging.INFO)
#robot = urx.Robot("192.168.1.6")
robot = urx.Robot("192.168.1.100")
#robot = urx.Robot("localhost")
r = robot
print("Robot object is available as robot or r")
embed()
finally:
robot.close()
| 388 | 23.3125 | 56 |
py
|
python-urx
|
python-urx-master/examples/simple.py
|
import urx
import logging
if __name__ == "__main__":
logging.basicConfig(level=logging.WARN)
rob = urx.Robot("192.168.1.100")
#rob = urx.Robot("localhost")
rob.set_tcp((0,0,0,0,0,0))
rob.set_payload(0.5, (0,0,0))
try:
l = 0.05
v = 0.05
a = 0.3
pose = rob.getl()
print("robot tcp is at: ", pose)
print("absolute move in base coordinate ")
pose[2] += l
rob.movel(pose, acc=a, vel=v)
print("relative move in base coordinate ")
rob.translate((0, 0, -l), acc=a, vel=v)
print("relative move back and forth in tool coordinate")
rob.translate_tool((0, 0, -l), acc=a, vel=v)
rob.translate_tool((0, 0, l), acc=a, vel=v)
finally:
rob.close()
| 775 | 25.758621 | 64 |
py
|
python-urx
|
python-urx-master/examples/get_realtime_data.py
|
import urx
import time
import logging
r = urx.Robot("192.168.111.134", use_rt=True, urFirm=5.1)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
while 1:
try:
j_temp = r.get_joint_temperature()
j_voltage = r.get_joint_voltage()
j_current = r.get_joint_current()
main_voltage = r.get_main_voltage()
robot_voltage = r.get_robot_voltage()
robot_current = r.get_robot_current()
print("JOINT TEMPERATURE")
print(j_temp)
print("JOINT VOLTAGE")
print(j_voltage)
print("JOINT CURRENT")
print(j_current)
print("MAIN VOLTAGE")
print(main_voltage)
print("ROBOT VOLTAGE")
print(robot_voltage)
print("ROBOT CURRENT")
print(robot_current)
print("##########\t##########\t##########\t##########")
time.sleep(1)
except:
pass
r.close()
| 1,035 | 23.093023 | 67 |
py
|
python-urx
|
python-urx-master/examples/matrices.py
|
from math import pi
import urx
import logging
if __name__ == "__main__":
rob = urx.Robot("192.168.1.100")
#rob = urx.Robot("localhost")
rob.set_tcp((0,0,0,0,0,0))
rob.set_payload(0.5, (0,0,0))
try:
l = 0.05
v = 0.05
a = 0.3
j = rob.getj()
print("Initial joint configuration is ", j)
t = rob.get_pose()
print("Transformation from base to tcp is: ", t)
print("Translating in x")
rob.translate((l, 0, 0), acc=a, vel=v)
pose = rob.getl()
print("robot tcp is at: ", pose)
print("moving in z")
pose[2] += l
rob.movel(pose, acc=a, vel=v)
print("Translate in -x and rotate")
t.orient.rotate_zb(pi/4)
t.pos[0] -= l
rob.set_pose(t, vel=v, acc=a)
print("Sending robot back to original position")
rob.movej(j, acc=0.8, vel=0.2)
finally:
rob.close()
| 937 | 23.051282 | 56 |
py
|
python-urx
|
python-urx-master/examples/spnav_control.py
|
from __future__ import division
import spnav
import time
import math3d as m3d
from math import pi
import urx
class Cmd(object):
def __init__(self):
self.reset()
def reset(self):
self.x = 0
self.y = 0
self.z = 0
self.rx = 0
self.ry = 0
self.rz = 0
self.btn0 = 0
self.btn1 = 0
def get_speeds(self):
return [self.x, self.y, self.z, self.rx, self.ry, self.rz]
class Service(object):
def __init__(self, robot):
self.robot = robot
self.lin_coef = 5000
self.rot_coef = 5000
def loop(self):
ts = 0
btn0_state = 0
btn_event = None
cmd = Cmd()
while True:
time.sleep(0.01)
cmd.reset()
#spnav.spnav_remove_events(spnav.SPNAV_EVENT_ANY) # seems broken
event = spnav.spnav_poll_event()
if event:
if type(event) is spnav.SpnavButtonEvent:
btn_event = event
if event.bnum == 0:
btn0_state = event.press
elif type(event) is spnav.SpnavMotionEvent:
if abs(event.translation[0]) > 30:
cmd.y = event.translation[0] / self.lin_coef
if abs(event.translation[1]) > 30:
cmd.z = -1 * event.translation[1] / self.lin_coef
if abs(event.translation[2]) > 30:
cmd.x = event.translation[2] / self.lin_coef
if abs(event.rotation[0]) > 20:
cmd.ry = event.rotation[0] / self.lin_coef
if abs(event.rotation[1]) > 20:
cmd.rz = -1 * event.rotation[1] / self.lin_coef
if abs(event.rotation[2]) > 20:
cmd.rx = event.rotation[2] / self.lin_coef
if (time.time() - ts) > 0.12:
ts = time.time()
speeds = cmd.get_speeds()
if btn0_state:
self.robot.speedl_tool(speeds, acc=0.10, min_time=2)
else:
self.robot.speedl(speeds, acc=0.10, min_time=2)
btn_event = None
speeds = cmd.get_speeds()
#if speeds != [0 for _ in speeds]:
print(event)
print("Sending", speeds)
if __name__ == '__main__':
spnav.spnav_open()
robot = urx.Robot("192.168.0.90")
#robot = urx.Robot("localhost")
robot.set_tcp((0, 0, 0.27, 0, 0, 0))
trx = m3d.Transform()
trx.orient.rotate_zb(pi/4)
robot.set_csys("mycsys", trx)
service = Service(robot)
try:
service.loop()
finally:
robot.close()
spnav.spnav_close()
| 2,806 | 28.547368 | 76 |
py
|
python-urx
|
python-urx-master/examples/joystick_control.py
|
"""
example program to control a universal robot with a joystick
All joysticks are differens, so you will need to modify the script to work with your joystick
"""
import time
import pygame
import math3d as m3d
from math import pi
import urx
class Cmd(object):
def __init__(self):
self.reset()
def reset(self):
self.axis0 = 0
self.axis1 = 0
self.axis2 = 0
self.axis3 = 0
self.axis4 = 0
self.axis5 = 0
self.btn0 = 0
self.btn1 = 0
self.btn2 = 0
self.btn3 = 0
self.btn4 = 0
self.btn5 = 0
self.btn6 = 0
self.btn7 = 0
self.btn8 = 0
self.btn9 = 0
class Service(object):
def __init__(self, robot, linear_velocity=0.1, rotational_velocity=0.1, acceleration=0.1):
self.joystick = None
self.robot = robot
#max velocity and acceleration to be send to robot
self.linear_velocity = linear_velocity
self.rotational_velocity = rotational_velocity
self.acceleration = acceleration
#one button send the robot to a preprogram position defined by this variable in join space
self.init_pose = [-2.0782002408411593, -1.6628931459654561, 2.067930303382134, -1.9172217394630149, 1.5489023943220621, 0.6783171005488982]
self.cmd = Cmd()
def init_joystick(self):
pygame.init()
self.joystick = pygame.joystick.Joystick(0)
self.joystick.init()
print('Initialized Joystick : %s' % self.joystick.get_name())
def loop(self):
print("Starting loop")
air = False
while True:
self.cmd.reset()
pygame.event.pump()#Seems we need polling in pygame...
#get joystick state
for i in range(0, self.joystick.get_numaxes()):
val = self.joystick.get_axis(i)
if i in (2, 5) and val != 0:
val += 1
if abs(val) < 0.2:
val = 0
tmp = "self.cmd.axis" + str(i) + " = " + str(val)
if val != 0:
print(tmp)
exec(tmp)
#get button state
for i in range(0, self.joystick.get_numbuttons()):
if self.joystick.get_button(i) != 0:
tmp = "self.cmd.btn" + str(i) + " = 1"
print(tmp)
exec(tmp)
if self.cmd.btn0:
#toggle IO
air = not air
self.robot.set_digital_out(2, air)
if self.cmd.btn9:
print("moving to init pose")
self.robot.movej(self.init_pose, acc=1, vel=0.1)
#initalize speed array to 0
speeds = [0, 0, 0, 0, 0, 0]
#get linear speed from joystick
speeds[0] = -1 * self.cmd.axis0 * self.linear_velocity
speeds[1] = self.cmd.axis1 * self.linear_velocity
if self.cmd.btn4 and not self.cmd.axis2:
speeds[2] = -self.linear_velocity
if self.cmd.axis2 and not self.cmd.btn4:
speeds[2] = self.cmd.axis2 * self.linear_velocity
#get rotational speed from joystick
speeds[4] = -1 * self.cmd.axis3 * self.rotational_velocity
speeds[3] = -1 * self.cmd.axis4 * self.rotational_velocity
if self.cmd.btn5 and not self.cmd.axis5:
speeds[5] = self.rotational_velocity
if self.cmd.axis5 and not self.cmd.btn5:
speeds[5] = self.cmd.axis5 * -self.rotational_velocity
#for some reasons everything is inversed
speeds = [-i for i in speeds]
#Now sending to robot. tol by default and base csys if btn2 is on
if speeds != [0 for _ in speeds]:
print("Sending ", speeds)
if self.cmd.btn7:
self.robot.speedl_tool(speeds, acc=self.acceleration, min_time=2)
else:
self.robot.speedl(speeds, acc=self.acceleration, min_time=2)
def close(self):
if self.joystick:
self.joystick.quit()
if __name__ == "__main__":
robot = urx.Robot("192.168.1.100")
r = robot
#start joystick service with given max speed and acceleration
service = Service(robot, linear_velocity=0.1, rotational_velocity=0.1, acceleration=0.1)
service.init_joystick()
try:
service.loop()
finally:
robot.close()
service.close()
| 4,580 | 31.721429 | 147 |
py
|
python-urx
|
python-urx-master/examples/test_all.py
|
"""
Testing script that runs many of the urx methods, while attempting to keep robot pose around its starting pose
"""
from math import pi
import time
import sys
import urx
import logging
if sys.version_info[0] < 3: # support python v2
input = raw_input
def wait():
if do_wait:
print("Click enter to continue")
input()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
do_wait = True
if len(sys.argv) > 1:
do_wait = False
rob = urx.Robot("192.168.1.100")
#rob = urx.Robot("localhost")
rob.set_tcp((0, 0, 0, 0, 0, 0))
rob.set_payload(0.5, (0, 0, 0))
try:
l = 0.05
v = 0.05
a = 0.3
r = 0.01
print("Digital out 0 and 1 are: ", rob.get_digital_out(0), rob.get_digital_out(1))
print("Analog inputs are: ", rob.get_analog_inputs())
initj = rob.getj()
print("Initial joint configuration is ", initj)
t = rob.get_pose()
print("Transformation from base to tcp is: ", t)
print("Translating in x")
wait()
rob.translate((l, 0, 0), acc=a, vel=v)
pose = rob.getl()
print("robot tcp is at: ", pose)
print("moving in z")
wait()
pose[2] += l
rob.movel(pose, acc=a, vel=v, wait=False)
print("Waiting 2s for end move")
time.sleep(2)
print("Moving through several points with a radius")
wait()
pose[0] -= l
p1 = pose[:]
pose[2] -= l
p2 = pose[:]
rob.movels([p1, p2], vel=v, acc=a, radius=r)
print("rotate tcp around around base z ")
wait()
t.orient.rotate_zb(pi / 8)
rob.set_pose(t, vel=v, acc=a)
print("moving in tool z")
wait()
rob.translate_tool((0, 0, l), vel=v, acc=a)
print("moving in tool -z using speed command")
wait()
rob.speedl_tool((0, 0, -v, 0, 0, 0), acc=a, min_time=3)
print("Waiting 2 seconds2")
time.sleep(2)
print("stop robot")
rob.stopj()
print("Test movec")
wait()
pose = rob.get_pose()
via = pose.copy()
via.pos[0] += l
to = via.copy()
to.pos[1] += l
rob.movec(via, to, acc=a, vel=v)
print("Sending robot back to original position")
rob.movej(initj, acc=0.8, vel=0.2)
finally:
rob.close()
| 2,420 | 24.484211 | 110 |
py
|
python-urx
|
python-urx-master/docs/conf.py
|
# -*- coding: utf-8 -*-
#
# Python URx documentation build configuration file, created by
# sphinx-quickstart on Mon May 11 21:37:43 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.coverage',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Python URx'
copyright = u'2015, Olivier Roulet-Dubonnet'
author = u'Olivier Roulet-Dubonnet'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'PythonURxdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'PythonURx.tex', u'Python URx Documentation',
u'Olivier Roulet-Dubonnet', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'pythonurx', u'Python URx Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'PythonURx', u'Python URx Documentation',
author, 'PythonURx', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| 9,300 | 31.183391 | 79 |
py
|
python-urx
|
python-urx-master/urx/urrtmon.py
|
'''
Module for implementing a UR controller real-time monitor over socket port 30003.
Confer http://support.universal-robots.com/Technical/RealTimeClientInterface
Note: The packet lenght given in the web-page is 740. What is actually received from the controller is 692.
It is assumed that the motor currents, the last group of 48 bytes, are not send.
Originally Written by Morten Lind
Parsing for Firmware 5.9 is added by Byeongdu Lee
'''
import logging
import socket
import struct
import time
import threading
from copy import deepcopy
import numpy as np
import math3d as m3d
__author__ = "Morten Lind, Olivier Roulet-Dubonnet"
__copyright__ = "Copyright 2011, NTNU/SINTEF Raufoss Manufacturing AS"
__credits__ = ["Morten Lind, Olivier Roulet-Dubonnet"]
__license__ = "LGPLv3"
class URRTMonitor(threading.Thread):
# Struct for revision of the UR controller giving 692 bytes
rtstruct692 = struct.Struct('>d6d6d6d6d6d6d6d6d18d6d6d6dQ')
# for revision of the UR controller giving 540 byte. Here TCP
# pose is not included!
rtstruct540 = struct.Struct('>d6d6d6d6d6d6d6d6d18d')
rtstruct5_1 = struct.Struct('>d1d6d6d6d6d6d6d6d6d6d6d6d6d6d6d1d6d1d1d1d6d1d6d3d6d1d1d1d1d1d1d1d6d1d1d3d3d')
rtstruct5_9 = struct.Struct('>d6d6d6d6d6d6d6d6d6d6d6d6d6d6d1d6d1d1d1d6d1d6d3d6d1d1d1d1d1d1d1d6d1d1d3d3d1d')
def __init__(self, urHost, urFirm=None):
threading.Thread.__init__(self)
self.logger = logging.getLogger(self.__class__.__name__)
self.daemon = True
self._stop_event = True
self._dataEvent = threading.Condition()
self._dataAccess = threading.Lock()
self._rtSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._rtSock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self._urHost = urHost
self.urFirm = urFirm
# Package data variables
self._timestamp = None
self._ctrlTimestamp = None
self._qActual = None
self._qTarget = None
self._tcp = None
self._tcp_force = None
self._joint_temperature = None
self._joint_voltage = None
self._joint_current = None
self._main_voltage = None
self._robot_voltage = None
self._robot_current = None
self._qdTarget = None
self._qddTarget = None
self._iTarget = None
self._mTarget = None
self._qdActual = None
self._tcp_speed = None
self._tcp = None
self._robot_mode = None
self._joint_modes = None
self._digital_outputs = None
self._program_state = None
self._safety_status = None
self.__recvTime = 0
self._last_ctrl_ts = 0
# self._last_ts = 0
self._buffering = False
self._buffer_lock = threading.Lock()
self._buffer = []
self._csys = None
self._csys_lock = threading.Lock()
def set_csys(self, csys):
with self._csys_lock:
self._csys = csys
def __recv_bytes(self, nBytes):
''' Facility method for receiving exactly "nBytes" bytes from
the robot connector socket.'''
# Record the time of arrival of the first of the stream block
recvTime = 0
pkg = b''
while len(pkg) < nBytes:
pkg += self._rtSock.recv(nBytes - len(pkg))
if recvTime == 0:
recvTime = time.time()
self.__recvTime = recvTime
return pkg
def wait(self):
with self._dataEvent:
self._dataEvent.wait()
def q_actual(self, wait=False, timestamp=False):
""" Get the actual joint position vector."""
if wait:
self.wait()
with self._dataAccess:
if timestamp:
return self._timestamp, self._qActual
else:
return self._qActual
getActual = q_actual
def qd_actual(self, wait=False, timestamp=False):
""" Get the actual joint velocity vector."""
if wait:
self.wait()
with self._dataAccess:
if timestamp:
return self._timestamp, self._qdActual
else:
return self._qdActual
def q_target(self, wait=False, timestamp=False):
""" Get the target joint position vector."""
if wait:
self.wait()
with self._dataAccess:
if timestamp:
return self._timestamp, self._qTarget
else:
return self._qTarget
getTarget = q_target
def tcf_pose(self, wait=False, timestamp=False, ctrlTimestamp=False):
""" Return the tool pose values."""
if wait:
self.wait()
with self._dataAccess:
tcf = self._tcp
if ctrlTimestamp or timestamp:
ret = [tcf]
if timestamp:
ret.insert(-1, self._timestamp)
if ctrlTimestamp:
ret.insert(-1, self._ctrlTimestamp)
return ret
else:
return tcf
getTCF = tcf_pose
def tcf_force(self, wait=False, timestamp=False):
""" Get the tool force. The returned tool force is a
six-vector of three forces and three moments."""
if wait:
self.wait()
with self._dataAccess:
# tcf = self._fwkin(self._qActual)
tcf_force = self._tcp_force
if timestamp:
return self._timestamp, tcf_force
else:
return tcf_force
getTCFForce = tcf_force
def joint_temperature(self, wait=False, timestamp=False):
""" Get the joint temperature."""
if wait:
self.wait()
with self._dataAccess:
joint_temperature = self._joint_temperature
if timestamp:
return self._timestamp, joint_temperature
else:
return joint_temperature
getJOINTTemperature = joint_temperature
def joint_voltage(self, wait=False, timestamp=False):
""" Get the joint voltage."""
if wait:
self.wait()
with self._dataAccess:
joint_voltage = self._joint_voltage
if timestamp:
return self._timestamp, joint_voltage
else:
return joint_voltage
getJOINTVoltage = joint_voltage
def joint_current(self, wait=False, timestamp=False):
""" Get the joint current."""
if wait:
self.wait()
with self._dataAccess:
joint_current = self._joint_current
if timestamp:
return self._timestamp, joint_current
else:
return joint_current
getJOINTCurrent = joint_current
def main_voltage(self, wait=False, timestamp=False):
""" Get the Safety Control Board: Main voltage."""
if wait:
self.wait()
with self._dataAccess:
main_voltage = self._main_voltage
if timestamp:
return self._timestamp, main_voltage
else:
return main_voltage
getMAINVoltage = main_voltage
def robot_voltage(self, wait=False, timestamp=False):
""" Get the Safety Control Board: Robot voltage (48V)."""
if wait:
self.wait()
with self._dataAccess:
robot_voltage = self._robot_voltage
if timestamp:
return self._timestamp, robot_voltage
else:
return robot_voltage
getROBOTVoltage = robot_voltage
def robot_current(self, wait=False, timestamp=False):
""" Get the Safety Control Board: Robot current."""
if wait:
self.wait()
with self._dataAccess:
robot_current = self._robot_current
if timestamp:
return self._timestamp, robot_current
else:
return robot_current
getROBOTCurrent = robot_current
def __recv_rt_data(self):
head = self.__recv_bytes(4)
# Record the timestamp for this logical package
timestamp = self.__recvTime
pkgsize = struct.unpack('>i', head)[0]
self.logger.debug(
'Received header telling that package is %s bytes long',
pkgsize)
payload = self.__recv_bytes(pkgsize - 4)
if self.urFirm is not None:
if self.urFirm == 5.1:
unp = self.rtstruct5_1.unpack(payload[:self.rtstruct5_1.size])
if self.urFirm == 5.9:
unp = self.rtstruct5_9.unpack(payload[:self.rtstruct5_9.size])
else:
if pkgsize >= 692:
unp = self.rtstruct692.unpack(payload[:self.rtstruct692.size])
elif pkgsize >= 540:
unp = self.rtstruct540.unpack(payload[:self.rtstruct540.size])
else:
self.logger.warning(
'Error, Received packet of length smaller than 540: %s ',
pkgsize)
return
with self._dataAccess:
self._timestamp = timestamp
# it seems that packet often arrives packed as two... maybe TCP_NODELAY is not set on UR controller??
# if (self._timestamp - self._last_ts) > 0.010:
# self.logger.warning("Error the we did not receive a packet for {}s ".format( self._timestamp - self._last_ts))
# self._last_ts = self._timestamp
self._ctrlTimestamp = np.array(unp[0])
if self._last_ctrl_ts != 0 and (
self._ctrlTimestamp -
self._last_ctrl_ts) > 0.010:
self.logger.warning(
"Error the controller failed to send us a packet: time since last packet %s s ",
self._ctrlTimestamp - self._last_ctrl_ts)
self._last_ctrl_ts = self._ctrlTimestamp
self._qActual = np.array(unp[31:37])
self._qdActual = np.array(unp[37:43])
self._qTarget = np.array(unp[1:7])
self._tcp_force = np.array(unp[67:73])
self._tcp = np.array(unp[73:79])
self._joint_current = np.array(unp[43:49])
if self.urFirm >= 3.1:
self._joint_temperature = np.array(unp[86:92])
self._joint_voltage = np.array(unp[124:130])
self._main_voltage = unp[121]
self._robot_voltage = unp[122]
self._robot_current = unp[123]
if self.urFirm>= 5.9:
self._qdTarget = np.array(unp[7:13])
self._qddTarget = np.array(unp[13:19])
self._iTarget = np.array(unp[19:25])
self._mTarget = np.array(unp[25:31])
self._tcp_speed = np.array(unp[61:67])
self._joint_current = np.array(unp[49:55])
self._joint_voltage = np.array(unp[124:130])
self._robot_mode = unp[94]
self._joint_modes = np.array(unp[95:101])
self._digital_outputs = unp[130]
self._program_state = unp[131]
self._safety_status = unp[138]
if self._csys:
with self._csys_lock:
# might be a godd idea to remove dependancy on m3d
tcp = self._csys.inverse * m3d.Transform(self._tcp)
self._tcp = tcp.pose_vector
if self._buffering:
with self._buffer_lock:
self._buffer.append(
(self._timestamp,
self._ctrlTimestamp,
self._tcp,
self._qActual)) # FIXME use named arrays of allow to configure what data to buffer
with self._dataEvent:
self._dataEvent.notifyAll()
def start_buffering(self):
"""
start buffering all data from controller
"""
self._buffer = []
self._buffering = True
def stop_buffering(self):
self._buffering = False
def try_pop_buffer(self):
"""
return oldest value in buffer
"""
with self._buffer_lock:
if len(self._buffer) > 0:
return self._buffer.pop(0)
else:
return None
def pop_buffer(self):
"""
return oldest value in buffer
"""
while True:
with self._buffer_lock:
if len(self._buffer) > 0:
return self._buffer.pop(0)
time.sleep(0.001)
def get_buffer(self):
"""
return a copy of the entire buffer
"""
with self._buffer_lock:
return deepcopy(self._buffer)
def get_all_data(self, wait=True):
"""
return all data parsed from robot as a dict
"""
if wait:
self.wait()
with self._dataAccess:
return dict(
timestamp=self._timestamp,
ctrltimestamp=self._ctrlTimestamp,
qActual=self._qActual,
qTarget=self._qTarget,
qdActual=self._qdActual,
qdTarget=self._qdTarget,
tcp=self._tcp,
tcp_force=self._tcp_force,
tcp_speed=self._tcp_speed,
joint_temperature=self._joint_temperature,
joint_voltage=self._joint_voltage,
joint_current=self._joint_current,
joint_modes=self._joint_modes,
robot_modes=self._robot_mode,
main_voltage=self._main_voltage,
robot_voltage=self._robot_voltage,
robot_current=self._robot_current,
digital_outputs=self._digital_outputs,
program_state=self._program_state,
safety_status=self._safety_status)
getALLData = get_all_data
def stop(self):
# print(self.__class__.__name__+': Stopping')
self._stop_event = True
def close(self):
self.stop()
self.join()
def run(self):
self._stop_event = False
self._rtSock.connect((self._urHost, 30003))
while not self._stop_event:
self.__recv_rt_data()
self._rtSock.close()
| 14,305 | 34.410891 | 124 |
py
|
python-urx
|
python-urx-master/urx/robot.py
|
"""
Python library to control an UR robot through its TCP/IP interface
DOC LINK
http://support.universal-robots.com/URRobot/RemoteAccess
"""
import math3d as m3d
import numpy as np
from urx.urrobot import URRobot
__author__ = "Olivier Roulet-Dubonnet"
__copyright__ = "Copyright 2011-2016, Sintef Raufoss Manufacturing"
__license__ = "LGPLv3"
class Robot(URRobot):
"""
Generic Python interface to an industrial robot.
Compared to the URRobot class, this class adds the possibilty to work directly with matrices
and includes support for setting a reference coordinate system
"""
def __init__(self, host, use_rt=False, urFirm=None):
URRobot.__init__(self, host, use_rt, urFirm)
self.csys = m3d.Transform()
def _get_lin_dist(self, target):
pose = URRobot.getl(self, wait=True)
target = m3d.Transform(target)
pose = m3d.Transform(pose)
return pose.dist(target)
def set_tcp(self, tcp):
"""
set robot flange to tool tip transformation
"""
if isinstance(tcp, m3d.Transform):
tcp = tcp.pose_vector
URRobot.set_tcp(self, tcp)
def set_csys(self, transform):
"""
Set reference coordinate system to use
"""
self.csys = transform
def set_orientation(self, orient, acc=0.01, vel=0.01, wait=True, threshold=None):
"""
set tool orientation using a orientation matric from math3d
or a orientation vector
"""
if not isinstance(orient, m3d.Orientation):
orient = m3d.Orientation(orient)
trans = self.get_pose()
trans.orient = orient
self.set_pose(trans, acc, vel, wait=wait, threshold=threshold)
def translate_tool(self, vect, acc=0.01, vel=0.01, wait=True, threshold=None):
"""
move tool in tool coordinate, keeping orientation
"""
t = m3d.Transform()
if not isinstance(vect, m3d.Vector):
vect = m3d.Vector(vect)
t.pos += vect
return self.add_pose_tool(t, acc, vel, wait=wait, threshold=threshold)
def back(self, z=0.05, acc=0.01, vel=0.01):
"""
move in z tool
"""
self.translate_tool((0, 0, -z), acc=acc, vel=vel)
def set_pos(self, vect, acc=0.01, vel=0.01, wait=True, threshold=None):
"""
set tool to given pos, keeping constant orientation
"""
if not isinstance(vect, m3d.Vector):
vect = m3d.Vector(vect)
trans = m3d.Transform(self.get_orientation(), m3d.Vector(vect))
return self.set_pose(trans, acc, vel, wait=wait, threshold=threshold)
def movec(self, pose_via, pose_to, acc=0.01, vel=0.01, wait=True, threshold=None):
"""
Move Circular: Move to position (circular in tool-space)
see UR documentation
"""
pose_via = self.csys * m3d.Transform(pose_via)
pose_to = self.csys * m3d.Transform(pose_to)
pose = URRobot.movec(self, pose_via.pose_vector, pose_to.pose_vector, acc=acc, vel=vel, wait=wait, threshold=threshold)
if pose is not None:
return self.csys.inverse * m3d.Transform(pose)
def set_pose(self, trans, acc=0.01, vel=0.01, wait=True, command="movel", threshold=None):
"""
move tcp to point and orientation defined by a transformation
UR robots have several move commands, by default movel is used but it can be changed
using the command argument
"""
self.logger.debug("Setting pose to %s", trans.pose_vector)
t = self.csys * trans
pose = URRobot.movex(self, command, t.pose_vector, acc=acc, vel=vel, wait=wait, threshold=threshold)
if pose is not None:
return self.csys.inverse * m3d.Transform(pose)
def add_pose_base(self, trans, acc=0.01, vel=0.01, wait=True, command="movel", threshold=None):
"""
Add transform expressed in base coordinate
"""
pose = self.get_pose()
return self.set_pose(trans * pose, acc, vel, wait=wait, command=command, threshold=threshold)
def add_pose_tool(self, trans, acc=0.01, vel=0.01, wait=True, command="movel", threshold=None):
"""
Add transform expressed in tool coordinate
"""
pose = self.get_pose()
return self.set_pose(pose * trans, acc, vel, wait=wait, command=command, threshold=threshold)
def get_pose(self, wait=False, _log=True):
"""
get current transform from base to to tcp
"""
pose = URRobot.getl(self, wait, _log)
trans = self.csys.inverse * m3d.Transform(pose)
if _log:
self.logger.debug("Returning pose to user: %s", trans.pose_vector)
return trans
def get_orientation(self, wait=False):
"""
get tool orientation in base coordinate system
"""
trans = self.get_pose(wait)
return trans.orient
def get_pos(self, wait=False):
"""
get tool tip pos(x, y, z) in base coordinate system
"""
trans = self.get_pose(wait)
return trans.pos
def speedl(self, velocities, acc, min_time):
"""
move at given velocities until minimum min_time seconds
"""
v = self.csys.orient * m3d.Vector(velocities[:3])
w = self.csys.orient * m3d.Vector(velocities[3:])
vels = np.concatenate((v.array, w.array))
return self.speedx("speedl", vels, acc, min_time)
def speedj(self, velocities, acc, min_time):
"""
move at given joint velocities until minimum min_time seconds
"""
return self.speedx("speedj", velocities, acc, min_time)
def speedl_tool(self, velocities, acc, min_time):
"""
move at given velocities in tool csys until minimum min_time seconds
"""
pose = self.get_pose()
v = pose.orient * m3d.Vector(velocities[:3])
w = pose.orient * m3d.Vector(velocities[3:])
self.speedl(np.concatenate((v.array, w.array)), acc, min_time)
def movex(self, command, pose, acc=0.01, vel=0.01, wait=True, relative=False, threshold=None):
"""
Send a move command to the robot. since UR robotene have several methods this one
sends whatever is defined in 'command' string
"""
t = m3d.Transform(pose)
if relative:
return self.add_pose_base(t, acc, vel, wait=wait, command=command, threshold=threshold)
else:
return self.set_pose(t, acc, vel, wait=wait, command=command, threshold=threshold)
def movexs(self, command, pose_list, acc=0.01, vel=0.01, radius=0.01, wait=True, threshold=None):
"""
Concatenate several movex commands and applies a blending radius
pose_list is a list of pose.
This method is usefull since any new command from python
to robot make the robot stop
"""
new_poses = []
for pose in pose_list:
t = self.csys * m3d.Transform(pose)
pose = t.pose_vector
new_poses.append(pose)
return URRobot.movexs(self, command, new_poses, acc, vel, radius, wait=wait, threshold=threshold)
def movel_tool(self, pose, acc=0.01, vel=0.01, wait=True, threshold=None):
"""
move linear to given pose in tool coordinate
"""
return self.movex_tool("movel", pose, acc=acc, vel=vel, wait=wait, threshold=threshold)
def movex_tool(self, command, pose, acc=0.01, vel=0.01, wait=True, threshold=None):
t = m3d.Transform(pose)
self.add_pose_tool(t, acc, vel, wait=wait, command=command, threshold=threshold)
def getl(self, wait=False, _log=True):
"""
return current transformation from tcp to current csys
"""
t = self.get_pose(wait, _log)
return t.pose_vector.tolist()
def set_gravity(self, vector):
if isinstance(vector, m3d.Vector):
vector = vector.list
return URRobot.set_gravity(self, vector)
def new_csys_from_xpy(self):
"""
Restores and returns new coordinate system calculated from three points: X, Origin, Y
based on math3d: Transform.new_from_xyp
"""
# Set coord. sys. to 0
self.csys = m3d.Transform()
print("A new coordinate system will be defined from the next three points")
print("Firs point is X, second Origin, third Y")
print("Set it as a new reference by calling myrobot.set_csys(new_csys)")
input("Move to first point and click Enter")
# we do not use get_pose so we avoid rounding values
pose = URRobot.getl(self)
print("Introduced point defining X: {}".format(pose[:3]))
px = m3d.Vector(pose[:3])
input("Move to second point and click Enter")
pose = URRobot.getl(self)
print("Introduced point defining Origo: {}".format(pose[:3]))
p0 = m3d.Vector(pose[:3])
input("Move to third point and click Enter")
pose = URRobot.getl(self)
print("Introduced point defining Y: {}".format(pose[:3]))
py = m3d.Vector(pose[:3])
new_csys = m3d.Transform.new_from_xyp(px - p0, py - p0, p0)
self.set_csys(new_csys)
return new_csys
@property
def x(self):
return self.get_pos().x
@x.setter
def x(self, val):
p = self.get_pos()
p.x = val
self.set_pos(p)
@property
def y(self):
return self.get_pos().y
@y.setter
def y(self, val):
p = self.get_pos()
p.y = val
self.set_pos(p)
@property
def z(self):
return self.get_pos().z
@z.setter
def z(self, val):
p = self.get_pos()
p.z = val
self.set_pos(p)
@property
def rx(self):
return 0
@rx.setter
def rx(self, val):
p = self.get_pose()
p.orient.rotate_xb(val)
self.set_pose(p)
@property
def ry(self):
return 0
@ry.setter
def ry(self, val):
p = self.get_pose()
p.orient.rotate_yb(val)
self.set_pose(p)
@property
def rz(self):
return 0
@rz.setter
def rz(self, val):
p = self.get_pose()
p.orient.rotate_zb(val)
self.set_pose(p)
@property
def x_t(self):
return 0
@x_t.setter
def x_t(self, val):
t = m3d.Transform()
t.pos.x += val
self.add_pose_tool(t)
@property
def y_t(self):
return 0
@y_t.setter
def y_t(self, val):
t = m3d.Transform()
t.pos.y += val
self.add_pose_tool(t)
@property
def z_t(self):
return 0
@z_t.setter
def z_t(self, val):
t = m3d.Transform()
t.pos.z += val
self.add_pose_tool(t)
@property
def rx_t(self):
return 0
@rx_t.setter
def rx_t(self, val):
t = m3d.Transform()
t.orient.rotate_xb(val)
self.add_pose_tool(t)
@property
def ry_t(self):
return 0
@ry_t.setter
def ry_t(self, val):
t = m3d.Transform()
t.orient.rotate_yb(val)
self.add_pose_tool(t)
@property
def rz_t(self):
return 0
@rz_t.setter
def rz_t(self, val):
t = m3d.Transform()
t.orient.rotate_zb(val)
self.add_pose_tool(t)
| 11,388 | 29.94837 | 127 |
py
|
python-urx
|
python-urx-master/urx/robotiq_two_finger_gripper.py
|
#! /usr/bin/env python
"""
Python library to control Robotiq Two Finger Gripper connected to UR robot via
Python-URX
Tested using a UR5 Version CB3 and Robotiq 2-Finger Gripper Version 85
SETUP
You must install the driver first and then power on the gripper from the
gripper UI. The driver can be found here:
http://support.robotiq.com/pages/viewpage.action?pageId=5963876
FAQ
Q: Why does this class group all the commands together and run them as a single
program as opposed to running each line seperately (like most of URX)?
A: The gripper is controlled by connecting to the robot's computer (TCP/IP) and
then communicating with the gripper via a socket (127.0.0.1:63352). The scope
of the socket is at the program level. It will be automatically closed
whenever a program finishes. Therefore it's important that we run all commands
as a single program.
DOCUMENTATION
- This code was developed by downloading the gripper package "DCU-1.0.10" from
http://support.robotiq.com/pages/viewpage.action?pageId=5963876. Or more
directly from http://support.robotiq.com/download/attachments/5963876/DCU-1.0.10.zip
- The file robotiq_2f_gripper_programs_CB3/rq_script.script was referenced to
create this class
FUTURE FEATURES
Though I haven't developed it yet, if you look in
robotiq_2f_gripper_programs_CB3/advanced_template_test.script and view function
"rq_get_var" there is an example of how to determine the current state of the
gripper and if it's holding an object.
""" # noqa
import logging
import os
import time
from urx.urscript import URScript
# Gripper Variables
ACT = "ACT"
GTO = "GTO"
ATR = "ATR"
ARD = "ARD"
FOR = "FOR"
SPE = "SPE"
OBJ = "OBJ"
STA = "STA"
FLT = "FLT"
POS = "POS"
SOCKET_HOST = "127.0.0.1"
SOCKET_PORT = 63352
SOCKET_NAME = "gripper_socket"
class RobotiqScript(URScript):
def __init__(self,
socket_host=SOCKET_HOST,
socket_port=SOCKET_PORT,
socket_name=SOCKET_NAME):
self.socket_host = socket_host
self.socket_port = socket_port
self.socket_name = socket_name
super(RobotiqScript, self).__init__()
# Reset connection to gripper
self._socket_close(self.socket_name)
self._socket_open(self.socket_host,
self.socket_port,
self.socket_name)
def _import_rq_script(self):
dir_path = os.path.dirname(os.path.realpath(__file__))
rq_script = os.path.join(dir_path, 'rq_script.script')
with open(rq_script, 'rb') as f:
rq_script = f.read()
self.add_header_to_program(rq_script)
def _rq_get_var(self, var_name, nbytes):
self._socket_send_string("GET {}".format(var_name))
self._socket_read_byte_list(nbytes)
def _get_gripper_fault(self):
self._rq_get_var(FLT, 2)
def _get_gripper_object(self):
self._rq_get_var(OBJ, 1)
def _get_gripper_status(self):
self._rq_get_var(STA, 1)
def _set_gripper_activate(self):
self._socket_set_var(GTO, 1, self.socket_name)
def _set_gripper_force(self, value):
"""
FOR is the variable
range is 0 - 255
0 is no force
255 is full force
"""
value = self._constrain_unsigned_char(value)
self._socket_set_var(FOR, value, self.socket_name)
def _set_gripper_position(self, value):
"""
SPE is the variable
range is 0 - 255
0 is no speed
255 is full speed
"""
value = self._constrain_unsigned_char(value)
self._socket_set_var(POS, value, self.socket_name)
def _set_gripper_speed(self, value):
"""
SPE is the variable
range is 0 - 255
0 is no speed
255 is full speed
"""
value = self._constrain_unsigned_char(value)
self._socket_set_var(SPE, value, self.socket_name)
def _set_robot_activate(self):
self._socket_set_var(ACT, 1, self.socket_name)
class Robotiq_Two_Finger_Gripper(object):
def __init__(self,
robot,
payload=0.85,
speed=255,
force=50,
socket_host=SOCKET_HOST,
socket_port=SOCKET_PORT,
socket_name=SOCKET_NAME):
self.robot = robot
self.payload = payload
self.speed = speed
self.force = force
self.socket_host = socket_host
self.socket_port = socket_port
self.socket_name = socket_name
self.logger = logging.getLogger(u"robotiq")
def _get_new_urscript(self):
"""
Set up a new URScript to communicate with gripper
"""
urscript = RobotiqScript(socket_host=self.socket_host,
socket_port=self.socket_port,
socket_name=self.socket_name)
# Set input and output voltage ranges
urscript._set_analog_inputrange(0, 0)
urscript._set_analog_inputrange(1, 0)
urscript._set_analog_inputrange(2, 0)
urscript._set_analog_inputrange(3, 0)
urscript._set_analog_outputdomain(0, 0)
urscript._set_analog_outputdomain(1, 0)
urscript._set_tool_voltage(0)
urscript._set_runstate_outputs()
# Set payload, speed and force
urscript._set_payload(self.payload)
urscript._set_gripper_speed(self.speed)
urscript._set_gripper_force(self.force)
# Initialize the gripper
urscript._set_robot_activate()
urscript._set_gripper_activate()
# Wait on activation to avoid USB conflicts
urscript._sleep(0.1)
return urscript
def gripper_action(self, value):
"""
Activate the gripper to a given value from 0 to 255
0 is open
255 is closed
"""
urscript = self._get_new_urscript()
# Move to the position
sleep = 2.0
urscript._set_gripper_position(value)
urscript._sleep(sleep)
# Send the script
self.robot.send_program(urscript())
# sleep the code the same amount as the urscript to ensure that
# the action completes
time.sleep(sleep)
def open_gripper(self):
self.gripper_action(0)
def close_gripper(self):
self.gripper_action(255)
| 6,377 | 28.391705 | 86 |
py
|
python-urx
|
python-urx-master/urx/__init__.py
|
"""
Python library to control an UR robot through its TCP/IP interface
"""
from urx.urrobot import RobotException, URRobot # noqa
__version__ = "0.11.0"
try:
from urx.robot import Robot
except ImportError as ex:
print("Exception while importing math3d base robot, disabling use of matrices", ex)
Robot = URRobot
| 327 | 24.230769 | 87 |
py
|
python-urx
|
python-urx-master/urx/urscript.py
|
#! /usr/bin/env python
import logging
# Controller Settings
CONTROLLER_PORTS = [0, 1]
CONTROLLER_VOLTAGE = [
0, # 0-5V
2, # 0-10V
]
# Tool Settings
TOOL_PORTS = [2, 3]
TOOL_VOLTAGE = [
0, # 0-5V
1, # 0-10V
2, # 4-20mA
]
OUTPUT_DOMAIN_VOLTAGE = [
0, # 4-20mA
1, # 0-10V
]
class URScript(object):
def __init__(self):
self.logger = logging.getLogger(u"urscript")
# The header is code that is before and outside the myProg() method
self.header = ""
# The program is code inside the myProg() method
self.program = ""
def __call__(self):
if(self.program == ""):
self.logger.debug(u"urscript program is empty")
return ""
# Construct the program
myprog = """def myProg():{}\nend""".format(self.program)
# Construct the full script
script = ""
if self.header:
script = "{}\n\n".format(self.header)
script = "{}{}".format(script, myprog)
return script
def reset(self):
self.header = ""
self.program = ""
def add_header_to_program(self, header_line):
self.header = "{}\n{}".format(self.header, header_line)
def add_line_to_program(self, new_line):
self.program = "{}\n\t{}".format(self.program, new_line)
def _constrain_unsigned_char(self, value):
"""
Ensure that unsigned char values are constrained
to between 0 and 255.
"""
assert(isinstance(value, int))
if value < 0:
value = 0
elif value > 255:
value = 255
return value
def _set_analog_inputrange(self, port, vrange):
if port in CONTROLLER_PORTS:
assert(vrange in CONTROLLER_VOLTAGE)
elif port in TOOL_PORTS:
assert(vrange in TOOL_VOLTAGE)
msg = "set_analog_inputrange({},{})".format(port, vrange)
self.add_line_to_program(msg)
def _set_analog_output(self, input_id, signal_level):
assert(input_id in [0, 1])
assert(signal_level in [0, 1])
msg = "set_analog_output({}, {})".format(input_id, signal_level)
self.add_line_to_program(msg)
def _set_analog_outputdomain(self, port, domain):
assert(domain in OUTPUT_DOMAIN_VOLTAGE)
msg = "set_analog_outputdomain({},{})".format(port, domain)
self.add_line_to_program(msg)
def _set_payload(self, mass, cog=None):
msg = "set_payload({}".format(mass)
if cog:
assert(len(cog) == 3)
msg = "{},{}".format(msg, cog)
msg = "{})".format(msg)
self.add_line_to_program(msg)
def _set_runstate_outputs(self, outputs=None):
if not outputs:
outputs = []
msg = "set_runstate_outputs({})".format(outputs)
self.add_line_to_program(msg)
def _set_tool_voltage(self, voltage):
assert(voltage in [0, 12, 24])
msg = "set_tool_voltage({})".format(voltage)
self.add_line_to_program(msg)
def _sleep(self, value):
msg = "sleep({})".format(value)
self.add_line_to_program(msg)
def _socket_close(self, socket_name):
msg = "socket_close(\"{}\")".format(socket_name)
self.add_line_to_program(msg)
def _socket_get_var(self, var, socket_name):
msg = "socket_get_var(\"{}\",\"{}\")".format(var, socket_name)
self.add_line_to_program(msg)
self._sync()
def _socket_open(self, socket_host, socket_port, socket_name):
msg = "socket_open(\"{}\",{},\"{}\")".format(socket_host,
socket_port,
socket_name)
self.add_line_to_program(msg)
def _socket_read_byte_list(self, nbytes, socket_name):
msg = "global var_value = socket_read_byte_list({},\"{}\")".format(nbytes, socket_name) # noqa
self.add_line_to_program(msg)
self._sync()
def _socket_send_string(self, message, socket_name):
msg = "socket_send_string(\"{}\",\"{}\")".format(message, socket_name) # noqa
self.add_line_to_program(msg)
self._sync()
def _socket_set_var(self, var, value, socket_name):
msg = "socket_set_var(\"{}\",{},\"{}\")".format(var, value, socket_name) # noqa
self.add_line_to_program(msg)
self._sync()
def _socket_get_var2var(self, var, varout, socket_name, prefix = ''):
msg = "{}{} = socket_get_var(\"{}\",\"{}\")".format(prefix, varout, var, socket_name)
self.add_line_to_program(msg)
def _socket_send_byte(self, byte, socket_name):
msg = "socket_send_byte(\"{}\",\"{}\")".format(str(byte), socket_name) # noqa
self.add_line_to_program(msg)
self._sync()
def _sync(self):
msg = "sync()"
self.add_line_to_program(msg)
| 4,900 | 30.216561 | 103 |
py
|
python-urx
|
python-urx-master/urx/urrobot.py
|
"""
Python library to control an UR robot through its TCP/IP interface
Documentation from universal robots:
http://support.universal-robots.com/URRobot/RemoteAccess
"""
import logging
import numbers
try:
from collections.abc import Sequence
except ImportError:
from collections import Sequence
from urx import urrtmon
from urx import ursecmon
__author__ = "Olivier Roulet-Dubonnet"
__copyright__ = "Copyright 2011-2015, Sintef Raufoss Manufacturing"
__license__ = "LGPLv3"
class RobotException(Exception):
pass
class URRobot(object):
"""
Python interface to socket interface of UR robot.
programs are send to port 3002
data is read from secondary interface(10Hz?) and real-time interface(125Hz) (called Matlab interface in documentation)
Since parsing the RT interface uses som CPU, and does not support all robots versions, it is disabled by default
The RT interfaces is only used for the get_force related methods
Rmq: A program sent to the robot i executed immendiatly and any running program is stopped
"""
def __init__(self, host, use_rt=False, urFirm=None):
self.logger = logging.getLogger("urx")
self.host = host
self.urFirm = urFirm
self.csys = None
self.logger.debug("Opening secondary monitor socket")
self.secmon = ursecmon.SecondaryMonitor(self.host) # data from robot at 10Hz
self.rtmon = None
if use_rt:
self.rtmon = self.get_realtime_monitor()
# precision of joint movem used to wait for move completion
# the value must be conservative! otherwise we may wait forever
self.joinEpsilon = 0.01
# It seems URScript is limited in the character length of floats it accepts
self.max_float_length = 6 # FIXME: check max length!!!
self.secmon.wait() # make sure we get data from robot before letting clients access our methods
def __repr__(self):
return "Robot Object (IP=%s, state=%s)" % (self.host, self.secmon.get_all_data()["RobotModeData"])
def __str__(self):
return self.__repr__()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def is_running(self):
"""
Return True if robot is running (not
necessary running a program, it might be idle)
"""
return self.secmon.running
def is_program_running(self):
"""
check if program is running.
Warning!!!!!: After sending a program it might take several 10th of
a second before the robot enters the running state
"""
return self.secmon.is_program_running()
def send_program(self, prog):
"""
send a complete program using urscript to the robot
the program is executed immediatly and any runnning
program is interrupted
"""
self.logger.info("Sending program: " + prog)
self.secmon.send_program(prog)
def get_tcp_force(self, wait=True):
"""
return measured force in TCP
if wait==True, waits for next packet before returning
"""
return self.rtmon.getTCFForce(wait)
def get_force(self, wait=True):
"""
length of force vector returned by get_tcp_force
if wait==True, waits for next packet before returning
"""
tcpf = self.get_tcp_force(wait)
force = 0
for i in tcpf:
force += i**2
return force**0.5
def get_joint_temperature(self, wait=True):
"""
return measured joint temperature
if wait==True, waits for next packet before returning
"""
return self.rtmon.getJOINTTemperature(wait)
def get_joint_voltage(self, wait=True):
"""
return measured joint voltage
if wait==True, waits for next packet before returning
"""
return self.rtmon.getJOINTVoltage(wait)
def get_joint_current(self, wait=True):
"""
return measured joint current
if wait==True, waits for next packet before returning
"""
return self.rtmon.getJOINTCurrent(wait)
def get_main_voltage(self, wait=True):
"""
return measured Safety Control Board: Main voltage
if wait==True, waits for next packet before returning
"""
return self.rtmon.getMAINVoltage(wait)
def get_robot_voltage(self, wait=True):
"""
return measured Safety Control Board: Robot voltage (48V)
if wait==True, waits for next packet before returning
"""
return self.rtmon.getROBOTVoltage(wait)
def get_robot_current(self, wait=True):
"""
return measured Safety Control Board: Robot current
if wait==True, waits for next packet before returning
"""
return self.rtmon.getROBOTCurrent(wait)
def get_all_rt_data(self, wait=True):
"""
return all data parsed from robot real-time interace as a dict
if wait==True, waits for next packet before returning
"""
return self.rtmon.getALLData(wait)
def set_tcp(self, tcp):
"""
set robot flange to tool tip transformation
"""
prog = "set_tcp(p[{}, {}, {}, {}, {}, {}])".format(*tcp)
self.send_program(prog)
def set_payload(self, weight, cog=None):
"""
set payload in Kg
cog is a vector x,y,z
if cog is not specified, then tool center point is used
"""
if cog:
cog = list(cog)
cog.insert(0, weight)
prog = "set_payload({}, ({},{},{}))".format(*cog)
else:
prog = "set_payload(%s)" % weight
self.send_program(prog)
def set_gravity(self, vector):
"""
set direction of gravity
"""
prog = "set_gravity(%s)" % list(vector)
self.send_program(prog)
def send_message(self, msg):
"""
send message to the GUI log tab on the robot controller
"""
prog = "textmsg(%s)" % msg
self.send_program(prog)
def set_digital_out(self, output, val):
"""
set digital output. val is a bool
"""
if val in (True, 1):
val = "True"
else:
val = "False"
self.send_program('digital_out[%s]=%s' % (output, val))
def get_analog_inputs(self):
"""
get analog input
"""
return self.secmon.get_analog_inputs()
def get_analog_in(self, nb, wait=False):
"""
get analog input
"""
return self.secmon.get_analog_in(nb, wait=wait)
def get_digital_in_bits(self):
"""
get digital output
"""
return self.secmon.get_digital_in_bits()
def get_digital_in(self, nb, wait=False):
"""
get digital output
"""
return self.secmon.get_digital_in(nb, wait)
def get_digital_out(self, val, wait=False):
"""
get digital output
"""
return self.secmon.get_digital_out(val, wait=wait)
def get_digital_out_bits(self, wait=False):
"""
get digital output as a byte
"""
return self.secmon.get_digital_out_bits(wait=wait)
def set_analog_out(self, output, val):
"""
set analog output, val is a float
"""
prog = "set_analog_out(%s, %s)" % (output, val)
self.send_program(prog)
def set_tool_voltage(self, val):
"""
set voltage to be delivered to the tool, val is 0, 12 or 24
"""
prog = "set_tool_voltage(%s)" % (val)
self.send_program(prog)
def _wait_for_move(self, target, threshold=None, timeout=5, joints=False):
"""
wait for a move to complete. Unfortunately there is no good way to know when a move has finished
so for every received data from robot we compute a dist equivalent and when it is lower than
'threshold' we return.
if threshold is not reached within timeout, an exception is raised
"""
self.logger.debug("Waiting for move completion using threshold %s and target %s", threshold, target)
start_dist = self._get_dist(target, joints)
if threshold is None:
threshold = start_dist * 0.8
if threshold < 0.001: # roboten precision is limited
threshold = 0.001
self.logger.debug("No threshold set, setting it to %s", threshold)
count = 0
while True:
if not self.is_running():
raise RobotException("Robot stopped")
dist = self._get_dist(target, joints)
self.logger.debug("distance to target is: %s, target dist is %s", dist, threshold)
if not self.secmon.is_program_running():
if dist < threshold:
self.logger.debug("we are threshold(%s) close to target, move has ended", threshold)
return
count += 1
if count > timeout * 10:
raise RobotException("Goal not reached but no program has been running for {} seconds. dist is {}, threshold is {}, target is {}, current pose is {}".format(timeout, dist, threshold, target, URRobot.getl(self)))
else:
count = 0
def _get_dist(self, target, joints=False):
if joints:
return self._get_joints_dist(target)
else:
return self._get_lin_dist(target)
def _get_lin_dist(self, target):
# FIXME: we have an issue here, it seems sometimes the axis angle received from robot
pose = URRobot.getl(self, wait=True)
dist = 0
for i in range(3):
dist += (target[i] - pose[i]) ** 2
for i in range(3, 6):
dist += ((target[i] - pose[i]) / 5) ** 2 # arbitraty length like
return dist ** 0.5
def _get_joints_dist(self, target):
joints = self.getj(wait=True)
dist = 0
for i in range(6):
dist += (target[i] - joints[i]) ** 2
return dist ** 0.5
def getj(self, wait=False):
"""
get joints position
"""
jts = self.secmon.get_joint_data(wait)
return [jts["q_actual0"], jts["q_actual1"], jts["q_actual2"], jts["q_actual3"], jts["q_actual4"], jts["q_actual5"]]
def speedx(self, command, velocities, acc, min_time):
vels = [round(i, self.max_float_length) for i in velocities]
vels.append(acc)
vels.append(min_time)
prog = "{}([{},{},{},{},{},{}], {}, {})".format(command, *vels)
self.send_program(prog)
def movej(self, joints, acc=0.1, vel=0.05, wait=True, relative=False, threshold=None):
"""
move in joint space
"""
if relative:
l = self.getj()
joints = [v + l[i] for i, v in enumerate(joints)]
prog = self._format_move("movej", joints, acc, vel)
self.send_program(prog)
if wait:
self._wait_for_move(joints[:6], threshold=threshold, joints=True)
return self.getj()
def movel(self, tpose, acc=0.01, vel=0.01, wait=True, relative=False, threshold=None):
"""
Send a movel command to the robot. See URScript documentation.
"""
return self.movex("movel", tpose, acc=acc, vel=vel, wait=wait, relative=relative, threshold=threshold)
def movep(self, tpose, acc=0.01, vel=0.01, wait=True, relative=False, threshold=None):
"""
Send a movep command to the robot. See URScript documentation.
"""
return self.movex("movep", tpose, acc=acc, vel=vel, wait=wait, relative=relative, threshold=threshold)
def servoc(self, tpose, acc=0.01, vel=0.01, wait=True, relative=False, threshold=None):
"""
Send a servoc command to the robot. See URScript documentation.
"""
return self.movex("servoc", tpose, acc=acc, vel=vel, wait=wait, relative=relative, threshold=threshold)
def servoj(self, tjoints, acc=0.01, vel=0.01, t=0.1, lookahead_time=0.2, gain=100, wait=True, relative=False, threshold=None):
"""
Send a servoj command to the robot. See URScript documentation.
"""
if relative:
l = self.getj()
tjoints = [v + l[i] for i, v in enumerate(tjoints)]
prog = self._format_servo("servoj", tjoints, acc=acc, vel=vel, t=t, lookahead_time=lookahead_time, gain=gain)
self.send_program(prog)
if wait:
self._wait_for_move(tjoints[:6], threshold=threshold, joints=True)
return self.getj()
def _format_servo(self, command, tjoints, acc=0.01, vel=0.01, t=0.1, lookahead_time=0.2, gain=100, prefix=""):
tjoints = [round(i, self.max_float_length) for i in tjoints]
tjoints.append(acc)
tjoints.append(vel)
tjoints.append(t)
tjoints.append(lookahead_time)
tjoints.append(gain)
return "{}({}[{},{},{},{},{},{}], a={}, v={}, t={}, lookahead_time={}, gain={})".format(command, prefix, *tjoints)
def _format_move(self, command, tpose, acc, vel, radius=0, prefix=""):
tpose = [round(i, self.max_float_length) for i in tpose]
tpose.append(acc)
tpose.append(vel)
tpose.append(radius)
return "{}({}[{},{},{},{},{},{}], a={}, v={}, r={})".format(command, prefix, *tpose)
def movex(self, command, tpose, acc=0.01, vel=0.01, wait=True, relative=False, threshold=None):
"""
Send a move command to the robot. since UR robotene have several methods this one
sends whatever is defined in 'command' string
"""
if relative:
l = self.getl()
tpose = [v + l[i] for i, v in enumerate(tpose)]
prog = self._format_move(command, tpose, acc, vel, prefix="p")
self.send_program(prog)
if wait:
self._wait_for_move(tpose[:6], threshold=threshold)
return self.getl()
def getl(self, wait=False, _log=True):
"""
get TCP position
"""
pose = self.secmon.get_cartesian_info(wait)
if pose:
pose = [pose["X"], pose["Y"], pose["Z"], pose["Rx"], pose["Ry"], pose["Rz"]]
if _log:
self.logger.debug("Received pose from robot: %s", pose)
return pose
def movec(self, pose_via, pose_to, acc=0.01, vel=0.01, wait=True, threshold=None):
"""
Move Circular: Move to position (circular in tool-space)
see UR documentation
"""
pose_via = [round(i, self.max_float_length) for i in pose_via]
pose_to = [round(i, self.max_float_length) for i in pose_to]
prog = "movec(p%s, p%s, a=%s, v=%s, r=%s)" % (pose_via, pose_to, acc, vel, "0")
self.send_program(prog)
if wait:
self._wait_for_move(pose_to, threshold=threshold)
return self.getl()
def movejs(self, joint_positions_list, acc=0.01, vel=0.01, radius=0.01,
wait=True, threshold=None):
"""
Concatenate several movej commands and applies a blending radius
joint_positions_list is a list of joint_positions.
This method is usefull since any new command from python
to robot make the robot stop
"""
return URRobot.movexs(self, "movej", joint_positions_list, acc, vel, radius,
wait, threshold=threshold)
def movels(self, pose_list, acc=0.01, vel=0.01, radius=0.01,
wait=True, threshold=None):
"""
Concatenate several movel commands and applies a blending radius
pose_list is a list of pose.
This method is usefull since any new command from python
to robot make the robot stop
"""
return self.movexs("movel", pose_list, acc, vel, radius,
wait, threshold=threshold)
def movexs(self, command, pose_list, acc=0.01, vel=0.01, radius=0.01,
wait=True, threshold=None):
"""
Concatenate several movex commands and applies a blending radius
pose_list is a list of pose.
This method is usefull since any new command from python
to robot make the robot stop
"""
header = "def myProg():\n"
end = "end\n"
prog = header
# Check if 'vel' is a single number or a sequence.
if isinstance(vel, numbers.Number):
# Make 'vel' a sequence
vel = len(pose_list) * [vel]
elif not isinstance(vel, Sequence):
raise RobotException(
'movexs: "vel" must be a single number or a sequence!')
# Check for adequate number of speeds
if len(vel) != len(pose_list):
raise RobotException(
'movexs: "vel" must be a number or a list '
+ 'of numbers the same length as "pose_list"!')
# Check if 'radius' is a single number.
if isinstance(radius, numbers.Number):
# Make 'radius' a sequence
radius = len(pose_list) * [radius]
elif not isinstance(radius, Sequence):
raise RobotException(
'movexs: "radius" must be a single number or a sequence!')
# Ensure that last pose a stopping pose.
radius[-1] = 0.0
# Require adequate number of radii.
if len(radius) != len(pose_list):
raise RobotException(
'movexs: "radius" must be a number or a list '
+ 'of numbers the same length as "pose_list"!')
prefix = ''
if command in ['movel', 'movec']:
prefix = 'p'
for idx, pose in enumerate(pose_list):
prog += self._format_move(command, pose, acc,
vel[idx], radius[idx],
prefix=prefix) + "\n"
prog += end
self.send_program(prog)
if wait:
if command == 'movel':
self._wait_for_move(target=pose_list[-1], threshold=threshold, joints=False)
elif command == 'movej':
self._wait_for_move(target=pose_list[-1], threshold=threshold, joints=True)
return self.getl()
def stopl(self, acc=0.5):
self.send_program("stopl(%s)" % acc)
def stopj(self, acc=1.5):
self.send_program("stopj(%s)" % acc)
def stop(self):
self.stopj()
def close(self):
"""
close connection to robot and stop internal thread
"""
self.logger.info("Closing sockets to robot")
self.secmon.close()
if self.rtmon:
self.rtmon.stop()
def set_freedrive(self, val, timeout=60):
"""
set robot in freedrive/backdrive mode where an operator can jog
the robot to wished pose.
Freedrive will timeout at 60 seconds.
"""
if val:
self.send_program("def myProg():\n\tfreedrive_mode()\n\tsleep({})\nend".format(timeout))
else:
# This is a non-existant program, but running it will stop freedrive
self.send_program("def myProg():\n\tend_freedrive_mode()\nend")
def set_simulation(self, val):
if val:
self.send_program("set sim")
else:
self.send_program("set real")
def get_realtime_monitor(self):
"""
return a pointer to the realtime monitor object
usefull to track robot position for example
"""
if not self.rtmon:
self.logger.info("Opening real-time monitor socket")
self.rtmon = urrtmon.URRTMonitor(self.host, self.urFirm) # som information is only available on rt interface
self.rtmon.start()
self.rtmon.set_csys(self.csys)
return self.rtmon
def translate(self, vect, acc=0.01, vel=0.01, wait=True, command="movel"):
"""
move tool in base coordinate, keeping orientation
"""
p = self.getl()
p[0] += vect[0]
p[1] += vect[1]
p[2] += vect[2]
return self.movex(command, p, vel=vel, acc=acc, wait=wait)
def up(self, z=0.05, acc=0.01, vel=0.01):
"""
Move up in csys z
"""
p = self.getl()
p[2] += z
self.movel(p, acc=acc, vel=vel)
def down(self, z=0.05, acc=0.01, vel=0.01):
"""
Move down in csys z
"""
self.up(-z, acc, vel)
| 20,532 | 35.086116 | 231 |
py
|
python-urx
|
python-urx-master/urx/ursecmon.py
|
"""
This file contains 2 classes:
- ParseUtils containing utilies to parse data from UR robot
- SecondaryMonitor, a class opening a socket to the robot and with methods to
access data and send programs to the robot
Both use data from the secondary port of the URRobot.
Only the last connected socket on 3001 is the primary client !!!!
So do not rely on it unless you know no other client is running (Hint the UR java interface is a client...)
http://support.universal-robots.com/Technical/PrimaryAndSecondaryClientInterface
"""
from threading import Thread, Condition, Lock
import logging
import struct
import socket
from copy import copy
import time
__author__ = "Olivier Roulet-Dubonnet"
__copyright__ = "Copyright 2011-2013, Sintef Raufoss Manufacturing"
__credits__ = ["Olivier Roulet-Dubonnet"]
__license__ = "LGPLv3"
class ParsingException(Exception):
def __init__(self, *args):
Exception.__init__(self, *args)
class Program(object):
def __init__(self, prog):
self.program = prog
self.condition = Condition()
def __str__(self):
return "Program({})".format(self.program)
__repr__ = __str__
class TimeoutException(Exception):
def __init__(self, *args):
Exception.__init__(self, *args)
class ParserUtils(object):
def __init__(self):
self.logger = logging.getLogger("ursecmon")
self.version = (0, 0)
def parse(self, data):
"""
parse a packet from the UR socket and return a dictionary with the data
"""
allData = {}
# print "Total size ", len(data)
while data:
psize, ptype, pdata, data = self.analyze_header(data)
# print "We got packet with size %i and type %s" % (psize, ptype)
if ptype == 16:
allData["SecondaryClientData"] = self._get_data(pdata, "!iB", ("size", "type"))
data = (pdata + data)[5:] # This is the total size so we resend data to parser
elif ptype == 0:
# this parses RobotModeData for versions >=3.0 (i.e. 3.0)
if psize == 38:
self.version = (3, 0)
allData['RobotModeData'] = self._get_data(pdata, "!IBQ???????BBdd", ("size", "type", "timestamp", "isRobotConnected", "isRealRobotEnabled", "isPowerOnRobot", "isEmergencyStopped", "isSecurityStopped", "isProgramRunning", "isProgramPaused", "robotMode", "controlMode", "speedFraction", "speedScaling"))
elif psize == 46: # It's 46 bytes in 3.2
self.version = (3, 2)
allData['RobotModeData'] = self._get_data(pdata, "!IBQ???????BBdd", ("size", "type", "timestamp", "isRobotConnected", "isRealRobotEnabled", "isPowerOnRobot", "isEmergencyStopped", "isSecurityStopped", "isProgramRunning", "isProgramPaused", "robotMode", "controlMode", "speedFraction", "speedScaling", "speedFractionLimit"))
elif psize == 47:
self.version = (3, 5)
allData['RobotModeData'] = self._get_data(pdata, "!IBQ???????BBddc", ("size", "type", "timestamp", "isRobotConnected", "isRealRobotEnabled", "isPowerOnRobot", "isEmergencyStopped", "isSecurityStopped", "isProgramRunning", "isProgramPaused", "robotMode", "controlMode", "speedFraction", "speedScaling", "speedFractionLimit", "reservedByUR"))
else:
allData["RobotModeData"] = self._get_data(pdata, "!iBQ???????Bd", ("size", "type", "timestamp", "isRobotConnected", "isRealRobotEnabled", "isPowerOnRobot", "isEmergencyStopped", "isSecurityStopped", "isProgramRunning", "isProgramPaused", "robotMode", "speedFraction"))
elif ptype == 1:
tmpstr = ["size", "type"]
for i in range(0, 6):
tmpstr += ["q_actual%s" % i, "q_target%s" % i, "qd_actual%s" % i, "I_actual%s" % i, "V_actual%s" % i, "T_motor%s" % i, "T_micro%s" % i, "jointMode%s" % i]
allData["JointData"] = self._get_data(pdata, "!iB dddffffB dddffffB dddffffB dddffffB dddffffB dddffffB", tmpstr)
elif ptype == 4:
if self.version < (3, 2):
allData["CartesianInfo"] = self._get_data(pdata, "iBdddddd", ("size", "type", "X", "Y", "Z", "Rx", "Ry", "Rz"))
else:
allData["CartesianInfo"] = self._get_data(pdata, "iBdddddddddddd", ("size", "type", "X", "Y", "Z", "Rx", "Ry", "Rz", "tcpOffsetX", "tcpOffsetY", "tcpOffsetZ", "tcpOffsetRx", "tcpOffsetRy", "tcpOffsetRz"))
elif ptype == 5:
allData["LaserPointer(OBSOLETE)"] = self._get_data(pdata, "iBddd", ("size", "type"))
elif ptype == 3:
if self.version >= (3, 0):
fmt = "iBiibbddbbddffffBBb" # firmware >= 3.0
else:
fmt = "iBhhbbddbbddffffBBb" # firmware < 3.0
allData["MasterBoardData"] = self._get_data(pdata, fmt, ("size", "type", "digitalInputBits", "digitalOutputBits", "analogInputRange0", "analogInputRange1", "analogInput0", "analogInput1", "analogInputDomain0", "analogInputDomain1", "analogOutput0", "analogOutput1", "masterBoardTemperature", "robotVoltage48V", "robotCurrent", "masterIOCurrent")) # , "masterSafetyState" ,"masterOnOffState", "euromap67InterfaceInstalled" ))
elif ptype == 2:
allData["ToolData"] = self._get_data(pdata, "iBbbddfBffB", ("size", "type", "analoginputRange2", "analoginputRange3", "analogInput2", "analogInput3", "toolVoltage48V", "toolOutputVoltage", "toolCurrent", "toolTemperature", "toolMode"))
elif ptype == 9:
continue # This package has a length of 53 bytes. It is used internally by Universal Robots software only and should be skipped.
elif ptype == 8 and self.version >= (3, 2):
allData["AdditionalInfo"] = self._get_data(pdata, "iB??", ("size", "type", "teachButtonPressed", "teachButtonEnabled"))
elif ptype == 7 and self.version >= (3, 2):
allData["ForceModeData"] = self._get_data(pdata, "iBddddddd", ("size", "type", "x", "y", "z", "rx", "ry", "rz", "robotDexterity"))
# elif ptype == 8:
# allData["varMessage"] = self._get_data(pdata, "!iBQbb iiBAcAc", ("size", "type", "timestamp", "source", "robotMessageType", "code", "argument", "titleSize", "messageTitle", "messageText"))
# elif ptype == 7:
# allData["keyMessage"] = self._get_data(pdata, "!iBQbb iiBAcAc", ("size", "type", "timestamp", "source", "robotMessageType", "code", "argument", "titleSize", "messageTitle", "messageText"))
elif ptype == 20:
tmp = self._get_data(pdata, "!iB Qbb", ("size", "type", "timestamp", "source", "robotMessageType"))
if tmp["robotMessageType"] == 3:
allData["VersionMessage"] = self._get_data(pdata, "!iBQbb bAbBBiAb", ("size", "type", "timestamp", "source", "robotMessageType", "projectNameSize", "projectName", "majorVersion", "minorVersion", "svnRevision", "buildDate"))
elif tmp["robotMessageType"] == 6:
allData["robotCommMessage"] = self._get_data(pdata, "!iBQbb iiAc", ("size", "type", "timestamp", "source", "robotMessageType", "code", "argument", "messageText"))
elif tmp["robotMessageType"] == 1:
allData["labelMessage"] = self._get_data(pdata, "!iBQbb iAc", ("size", "type", "timestamp", "source", "robotMessageType", "id", "messageText"))
elif tmp["robotMessageType"] == 2:
allData["popupMessage"] = self._get_data(pdata, "!iBQbb ??BAcAc", ("size", "type", "timestamp", "source", "robotMessageType", "warning", "error", "titleSize", "messageTitle", "messageText"))
elif tmp["robotMessageType"] == 0:
allData["messageText"] = self._get_data(pdata, "!iBQbb Ac", ("size", "type", "timestamp", "source", "robotMessageType", "messageText"))
elif tmp["robotMessageType"] == 8:
allData["varMessage"] = self._get_data(pdata, "!iBQbb iiBAcAc", ("size", "type", "timestamp", "source", "robotMessageType", "code", "argument", "titleSize", "messageTitle", "messageText"))
elif tmp["robotMessageType"] == 7:
allData["keyMessage"] = self._get_data(pdata, "!iBQbb iiBAcAc", ("size", "type", "timestamp", "source", "robotMessageType", "code", "argument", "titleSize", "messageTitle", "messageText"))
elif tmp["robotMessageType"] == 5:
allData["keyMessage"] = self._get_data(pdata, "!iBQbb iiAc", ("size", "type", "timestamp", "source", "robotMessageType", "code", "argument", "messageText"))
else:
self.logger.debug("Message type parser not implemented %s", tmp)
else:
self.logger.debug("Unknown packet type %s with size %s", ptype, psize)
return allData
def _get_data(self, data, fmt, names):
"""
fill data into a dictionary
data is data from robot packet
fmt is struct format, but with added A for arrays and no support for numerical in fmt
names args are strings used to store values
"""
tmpdata = copy(data)
fmt = fmt.strip() # space may confuse us
d = dict()
i = 0
j = 0
while j < len(fmt) and i < len(names):
f = fmt[j]
if f in (" ", "!", ">", "<"):
j += 1
elif f == "A": # we got an array
# first we need to find its size
if j == len(fmt) - 2: # we are last element, size is the rest of data in packet
arraysize = len(tmpdata)
else: # size should be given in last element
asn = names[i - 1]
if not asn.endswith("Size"):
raise ParsingException("Error, array without size ! %s %s" % (asn, i))
else:
arraysize = d[asn]
d[names[i]] = tmpdata[0:arraysize]
# print "Array is ", names[i], d[names[i]]
tmpdata = tmpdata[arraysize:]
j += 2
i += 1
else:
fmtsize = struct.calcsize(fmt[j])
# print "reading ", f , i, j, fmtsize, len(tmpdata)
if len(tmpdata) < fmtsize: # seems to happen on windows
raise ParsingException("Error, length of data smaller than advertized: ", len(tmpdata), fmtsize, "for names ", names, f, i, j)
d[names[i]] = struct.unpack("!" + f, tmpdata[0:fmtsize])[0]
# print names[i], d[names[i]]
tmpdata = tmpdata[fmtsize:]
j += 1
i += 1
return d
def get_header(self, data):
return struct.unpack("!iB", data[0:5])
def analyze_header(self, data):
"""
read first 5 bytes and return complete packet
"""
if len(data) < 5:
raise ParsingException("Packet size %s smaller than header size (5 bytes)" % len(data))
else:
psize, ptype = self.get_header(data)
if psize < 5:
raise ParsingException("Error, declared length of data smaller than its own header(5): ", psize)
elif psize > len(data):
raise ParsingException("Error, length of data smaller (%s) than declared (%s)" % (len(data), psize))
return psize, ptype, data[:psize], data[psize:]
def find_first_packet(self, data):
"""
find the first complete packet in a string
returns None if none found
"""
counter = 0
limit = 10
while True:
if len(data) >= 5:
psize, ptype = self.get_header(data)
if psize < 5 or psize > 2000 or ptype != 16:
data = data[1:]
counter += 1
if counter > limit:
self.logger.warning("tried %s times to find a packet in data, advertised packet size: %s, type: %s", counter, psize, ptype)
self.logger.warning("Data length: %s", len(data))
limit = limit * 10
elif len(data) >= psize:
self.logger.debug("Got packet with size %s and type %s", psize, ptype)
if counter:
self.logger.info("Remove %s bytes of garbage at begining of packet", counter)
# ok we we have somehting which looks like a packet"
return (data[:psize], data[psize:])
else:
# packet is not complete
self.logger.debug("Packet is not complete, advertised size is %s, received size is %s, type is %s", psize, len(data), ptype)
return None
else:
# self.logger.debug("data smaller than 5 bytes")
return None
class SecondaryMonitor(Thread):
"""
Monitor data from secondary port and send programs to robot
"""
def __init__(self, host):
Thread.__init__(self)
self.logger = logging.getLogger("ursecmon")
self._parser = ParserUtils()
self._dict = {}
self._dictLock = Lock()
self.host = host
secondary_port = 30002 # Secondary client interface on Universal Robots
self._s_secondary = socket.create_connection((self.host, secondary_port), timeout=0.5)
self._prog_queue = []
self._prog_queue_lock = Lock()
self._dataqueue = bytes()
self._trystop = False # to stop thread
self.running = False # True when robot is on and listening
self._dataEvent = Condition()
self.lastpacket_timestamp = 0
self.start()
try:
self.wait() # make sure we got some data before someone calls us
except TimeoutException as ex:
self.close()
raise ex
def send_program(self, prog):
"""
send program to robot in URRobot format
If another program is send while a program is running the first program is aborded.
"""
prog.strip()
self.logger.debug("Enqueueing program: %s", prog)
if not isinstance(prog, bytes):
prog = prog.encode()
data = Program(prog + b"\n")
with data.condition:
with self._prog_queue_lock:
self._prog_queue.append(data)
data.condition.wait()
self.logger.debug("program sendt: %s", data)
def run(self):
"""
check program execution status in the secondary client data packet we get from the robot
This interface uses only data from the secondary client interface (see UR doc)
Only the last connected client is the primary client,
so this is not guaranted and we cannot rely on information to the primary client.
"""
while not self._trystop:
with self._prog_queue_lock:
if len(self._prog_queue) > 0:
data = self._prog_queue.pop(0)
self._s_secondary.send(data.program)
with data.condition:
data.condition.notify_all()
data = self._get_data()
try:
tmpdict = self._parser.parse(data)
with self._dictLock:
self._dict = tmpdict
except ParsingException as ex:
self.logger.warning("Error parsing one packet from urrobot: %s", ex)
continue
if "RobotModeData" not in self._dict:
self.logger.warning("Got a packet from robot without RobotModeData, strange ...")
continue
self.lastpacket_timestamp = time.time()
rmode = 0
if self._parser.version >= (3, 0):
rmode = 7
if self._dict["RobotModeData"]["robotMode"] == rmode \
and self._dict["RobotModeData"]["isRealRobotEnabled"] is True \
and self._dict["RobotModeData"]["isEmergencyStopped"] is False \
and self._dict["RobotModeData"]["isSecurityStopped"] is False \
and self._dict["RobotModeData"]["isRobotConnected"] is True \
and self._dict["RobotModeData"]["isPowerOnRobot"] is True:
self.running = True
else:
if self.running:
self.logger.error("Robot not running: " + str(self._dict["RobotModeData"]))
self.running = False
with self._dataEvent:
# print("X: new data")
self._dataEvent.notifyAll()
def _get_data(self):
"""
returns something that looks like a packet, nothing is guaranted
"""
while True:
# self.logger.debug("data queue size is: {}".format(len(self._dataqueue)))
ans = self._parser.find_first_packet(self._dataqueue[:])
if ans:
self._dataqueue = ans[1]
# self.logger.debug("found packet of size {}".format(len(ans[0])))
return ans[0]
else:
# self.logger.debug("Could not find packet in received data")
tmp = self._s_secondary.recv(1024)
self._dataqueue += tmp
def wait(self, timeout=0.5):
"""
wait for next data packet from robot
"""
tstamp = self.lastpacket_timestamp
with self._dataEvent:
self._dataEvent.wait(timeout)
if tstamp == self.lastpacket_timestamp:
raise TimeoutException("Did not receive a valid data packet from robot in {}".format(timeout))
def get_cartesian_info(self, wait=False):
if wait:
self.wait()
with self._dictLock:
if "CartesianInfo" in self._dict:
return self._dict["CartesianInfo"]
else:
return None
def get_all_data(self, wait=False):
"""
return last data obtained from robot in dictionnary format
"""
if wait:
self.wait()
with self._dictLock:
return self._dict.copy()
def get_joint_data(self, wait=False):
if wait:
self.wait()
with self._dictLock:
if "JointData" in self._dict:
return self._dict["JointData"]
else:
return None
def get_digital_out(self, nb, wait=False):
if wait:
self.wait()
with self._dictLock:
output = self._dict["MasterBoardData"]["digitalOutputBits"]
mask = 1 << nb
if output & mask:
return 1
else:
return 0
def get_digital_out_bits(self, wait=False):
if wait:
self.wait()
with self._dictLock:
return self._dict["MasterBoardData"]["digitalOutputBits"]
def get_digital_in(self, nb, wait=False):
if wait:
self.wait()
with self._dictLock:
output = self._dict["MasterBoardData"]["digitalInputBits"]
mask = 1 << nb
if output & mask:
return 1
else:
return 0
def get_digital_in_bits(self, wait=False):
if wait:
self.wait()
with self._dictLock:
return self._dict["MasterBoardData"]["digitalInputBits"]
def get_analog_in(self, nb, wait=False):
if wait:
self.wait()
with self._dictLock:
return self._dict["MasterBoardData"]["analogInput" + str(nb)]
def get_analog_inputs(self, wait=False):
if wait:
self.wait()
with self._dictLock:
return self._dict["MasterBoardData"]["analogInput0"], self._dict["MasterBoardData"]["analogInput1"]
def is_program_running(self, wait=False):
"""
return True if robot is executing a program
Rmq: The refresh rate is only 10Hz so the information may be outdated
"""
if wait:
self.wait()
with self._dictLock:
return self._dict["RobotModeData"]["isProgramRunning"]
def close(self):
self._trystop = True
self.join()
# with self._dataEvent: #wake up any thread that may be waiting for data before we close. Should we do that?
# self._dataEvent.notifyAll()
if self._s_secondary:
with self._prog_queue_lock:
self._s_secondary.close()
| 20,776 | 45.795045 | 443 |
py
|
CANTM
|
CANTM-main/updateTopics_covid.py
|
import sys
from GateMIcateLib import ModelUltiUpdateCAtopic as ModelUlti
from GateMIcateLib import BatchIterBert, DictionaryProcess
from GateMIcateLib.batchPostProcessors import bowBertBatchProcessor as batchPostProcessor
from GateMIcateLib import ScholarPostProcessor as ReaderPostProcessor
from GateMIcateLib.readers import WVmisInfoDataIter as dataIter
from configobj import ConfigObj
from torch.nn import init
import argparse
import json
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("testReaderargs", help="args for test reader")
parser.add_argument("--configFile", help="config files if needed")
parser.add_argument("--cachePath", help="save models")
parser.add_argument("--randomSeed", type=int, help="randomSeed for reproduction")
parser.add_argument("--num_epoches", type=int, default=5, help="num epoches")
parser.add_argument("--patient", type=int, default=40, help="early_stop_patient")
parser.add_argument("--earlyStopping", default='cls_loss', help="early stopping")
parser.add_argument("--corpusType", default='wvmisinfo', help="corpus type, for select reader")
parser.add_argument("--x_fields", help="x fileds", default='Claim,Explaination')
parser.add_argument("--y_field", help="y filed", default='Label')
args = parser.parse_args()
testReaderargs = args.testReaderargs.split(',')
x_fields = args.x_fields.split(',')
config = ConfigObj(args.configFile)
mUlti = ModelUlti(load_path=args.cachePath, gpu=True)
trainable_weights = ['xy_topics.topic.weight',
'z_y_hidden.hidden1.weight',
'z2y_classifier.layer_output.weight',
]
trainable_bias = [
'xy_topics.topic.bias',
'z_y_hidden.hidden1.bias',
'z2y_classifier.layer_output.bias'
]
trainable_no_init = [
'mu_z2.weight',
'mu_z2.bias',
'log_sigma_z2.weight',
'log_sigma_z2.bias',
'x_y_hidden.hidden1.weight',
'x_y_hidden.hidden1.bias'
]
for name, param in mUlti.net.named_parameters():
print(name)
if name in trainable_weights:
param.requires_grad = True
param.data.uniform_(-1.0, 1.0)
elif name in trainable_bias:
param.requires_grad = True
param.data.fill_(0)
elif name in trainable_no_init:
param.requires_grad = True
else:
param.requires_grad = False
postProcessor = ReaderPostProcessor(config=config, word2id=True, remove_single_list=False, add_spec_tokens=True, x_fields=x_fields, y_field=args.y_field, max_sent_len=300)
postProcessor.dictProcess = mUlti.bowdict
testDataIter = dataIter(*testReaderargs, label_field=args.y_field, postProcessor=postProcessor, config=config, shuffle=True)
testBatchIter = BatchIterBert(testDataIter, filling_last_batch=True, postProcessor=batchPostProcessor, batch_size=32)
mUlti.train(testBatchIter, num_epohs=args.num_epoches, cache_path=args.cachePath)
| 3,093 | 37.675 | 175 |
py
|
CANTM
|
CANTM-main/getPerpare.py
|
import os
import torch
from transformers import *
import nltk
from pathlib import Path
nltk.download('stopwords')
nltk.download('punkt')
model = BertModel.from_pretrained('bert-base-uncased')
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
script_path = os.path.abspath(__file__)
print(script_path)
parent = os.path.dirname(script_path)
parent = os.path.join(parent, 'bert-base-uncased')
print(parent)
model_save_path = os.path.join(parent,'model')
path = Path(model_save_path)
path.mkdir(parents=True, exist_ok=True)
model.save_pretrained(model_save_path)
tokenizer_save_path = os.path.join(parent,'tokenizer')
path = Path(tokenizer_save_path)
path.mkdir(parents=True, exist_ok=True)
tokenizer.save_pretrained(tokenizer_save_path)
| 753 | 25 | 62 |
py
|
CANTM
|
CANTM-main/raw2folds.py
|
import json
import os
import sys
import random
import math
from pathlib import Path
import copy
def outputChunk(output_dir, chunkIdx, chunks):
output_path = os.path.join(output_dir, str(chunkIdx))
path = Path(output_path)
path.mkdir(parents=True, exist_ok=True)
for i, item in enumerate(chunks):
if i == chunkIdx:
json_path = os.path.join(output_path, 'test.jsonlist')
else:
json_path = os.path.join(output_path, 'train.jsonlist')
with open(json_path, 'a') as jsout:
for line in item:
jsout.write(json.dumps(line) + '\n')
input_json = sys.argv[1]
num_fold = int(sys.argv[2])
output_dir = sys.argv[3]
with open(input_json, 'r') as inf:
data = json.load(inf)
random.shuffle(data)
num_data = len(data)
chunkSize = math.ceil(num_data/num_fold)
chunks = []
for i in range(0, len(data), chunkSize):
chunks.append(copy.deepcopy(data[i:i+chunkSize]))
for idx, eachchunk in enumerate(chunks):
outputChunk(output_dir, idx, chunks)
| 1,062 | 22.108696 | 67 |
py
|
CANTM
|
CANTM-main/evaluation.py
|
import argparse
import json
import os
from GateMIcateLib import EvaluationManager
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("trainReaderargs", help="args for train reader")
parser.add_argument("--testReaderargs", help="args for test reader")
parser.add_argument("--valReaderargs", help="args for val reader")
parser.add_argument("--configFile", help="config files if needed")
parser.add_argument("--cachePath", help="save models")
parser.add_argument("--nFold", type=int, default=5, help="n fold")
parser.add_argument("--randomSeed", type=int, help="randomSeed for reproduction")
parser.add_argument("--preEmbd", default=False, action='store_true', help="calculate embedding before training")
parser.add_argument("--dynamicSampling", default=False, action='store_true', help="sample based on class count")
parser.add_argument("--model", default='clsTopic', help="model used for evaluation")
parser.add_argument("--num_epoches", type=int, default=200, help="num epoches")
parser.add_argument("--patient", type=int, default=4, help="early_stop_patient")
parser.add_argument("--max_sent_len", type=int, default=300, help="maximum words in the sentence")
parser.add_argument("--earlyStopping", default='cls_loss', help="early stopping")
parser.add_argument("--corpusType", default='wvmisinfo', help="corpus type, for select reader")
parser.add_argument("--splitValidation", type=float, help="split data from training for validation")
parser.add_argument("--inspectTest", default=False, action='store_true', help="inspect testing data performance")
parser.add_argument("--x_fields", help="x fileds", default='Claim,Explaination')
parser.add_argument("--y_field", help="y filed", default='category')
parser.add_argument("--trainOnly", help="only train the model, no split or test", default=False, action='store_true')
parser.add_argument("--export_json", help="export json for scholar, need file path")
parser.add_argument("--export_doc", help="export doc for npmi, need file path")
parser.add_argument("--trainLDA", help="lda test", default=False, action='store_true')
args = parser.parse_args()
dictargs = vars(args)
trainReaderargs = args.trainReaderargs.split(',')
if args.testReaderargs:
testReaderargs = args.testReaderargs.split(',')
else:
testReaderargs = None
if args.valReaderargs:
valReaderargs = args.valReaderargs.split(',')
else:
valReaderargs = None
evaluaton = EvaluationManager(trainReaderargs, dictargs, testReaderargs=testReaderargs, valReaderargs=valReaderargs)
if args.export_json:
jsonData = evaluaton.get_covid_train_json_for_scholar()
with open(args.export_json, 'w') as fo:
json.dump(jsonData, fo)
elif args.export_doc:
all_doc = evaluaton.outputCorpus4NPMI()
with open(args.export_doc, 'w') as fo:
for item in all_doc:
item = item.strip()
fo.write(item+'\n')
elif args.trainOnly:
evaluaton.train_model_only()
elif testReaderargs:
evaluaton.train_test_evaluation()
else:
evaluaton.cross_fold_evaluation()
| 3,273 | 42.653333 | 121 |
py
|
CANTM
|
CANTM-main/updateTopics.py
|
import sys
from GateMIcateLib import ModelUltiUpdateCAtopic as ModelUlti
from GateMIcateLib import BatchIterBert, DictionaryProcess
from GateMIcateLib.batchPostProcessors import bowBertBatchProcessor as batchPostProcessor
from GateMIcateLib import ScholarPostProcessor as ReaderPostProcessor
from GateMIcateLib.readers import ACLimdbReader as dataIter
from configobj import ConfigObj
from torch.nn import init
import argparse
import json
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("testReaderargs", help="args for test reader")
parser.add_argument("--configFile", help="config files if needed")
parser.add_argument("--cachePath", help="save models")
parser.add_argument("--randomSeed", type=int, help="randomSeed for reproduction")
parser.add_argument("--num_epoches", type=int, default=5, help="num epoches")
parser.add_argument("--patient", type=int, default=40, help="early_stop_patient")
parser.add_argument("--earlyStopping", default='cls_loss', help="early stopping")
parser.add_argument("--corpusType", default='wvmisinfo', help="corpus type, for select reader")
parser.add_argument("--x_fields", help="x fileds", default='text')
parser.add_argument("--y_field", help="y filed", default='selected_label')
args = parser.parse_args()
testReaderargs = args.testReaderargs.split(',')
x_fields = args.x_fields.split(',')
config = ConfigObj(args.configFile)
mUlti = ModelUlti(load_path=args.cachePath, gpu=True)
trainable_weights = ['xy_topics.topic.weight',
'z_y_hidden.hidden1.weight',
'z2y_classifier.layer_output.weight',
]
trainable_bias = [
'xy_topics.topic.bias',
'z_y_hidden.hidden1.bias',
'z2y_classifier.layer_output.bias'
]
for name, param in mUlti.net.named_parameters():
if name in trainable_weights:
param.requires_grad = True
param.data.uniform_(-1.0, 1.0)
elif name in trainable_bias:
param.requires_grad = True
param.data.fill_(0)
else:
param.requires_grad = False
postProcessor = ReaderPostProcessor(config=config, word2id=True, remove_single_list=False, add_spec_tokens=True, x_fields=x_fields, y_field=args.y_field, max_sent_len=510)
postProcessor.dictProcess = mUlti.bowdict
testDataIter = dataIter(*testReaderargs, postProcessor=postProcessor, config=config, shuffle=True)
testBatchIter = BatchIterBert(testDataIter, filling_last_batch=True, postProcessor=batchPostProcessor, batch_size=32)
mUlti.train(testBatchIter, num_epohs=args.num_epoches, cache_path=args.cachePath)
| 2,718 | 38.405797 | 175 |
py
|
CANTM
|
CANTM-main/wvCovidData/update_wv_unique_id.py
|
import json
import re
import nltk
import argparse
import copy
import os
import sys
script_path = os.path.abspath(__file__)
print(script_path)
global parent
parent = os.path.dirname(script_path)
print(parent)
gatePython = os.path.join(parent, 'GATEpythonInterface')
sys.path.append(gatePython)
from GateInterface import *
import string
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("inputJson", help="args for test reader")
parser.add_argument("outputJson", help="args for test reader")
args = parser.parse_args()
input_json = args.inputJson
output_json = args.outputJson
with open(input_json, 'r') as fj:
raw_data = json.load(fj)
doc_id = 0
new_data = []
for item in raw_data:
doc_id += 1
item['unique_wv_id'] = str(doc_id)
new_data.append(copy.deepcopy(item))
print(doc_id)
with open(output_json, 'w') as fo:
json.dump(new_data, fo)
| 902 | 19.066667 | 62 |
py
|
CANTM
|
CANTM-main/wvCovidData/downloadIFCNSource.py
|
import sys
from bs4 import BeautifulSoup
import json
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
def download_source(url):
options = Options()
options.headless = True
driver = webdriver.Firefox(options=options)
driver.get(url)
html = driver.page_source
driver.close()
soup = BeautifulSoup(html, 'html.parser')
factcheck_Org = soup.find('p', attrs={'class':'entry-content__text entry-content__text--org'}).get_text()[17:]
date = soup.find('p', attrs={'class':'entry-content__text entry-content__text--topinfo'}).get_text()[0:10]
country = soup.find('p', attrs={'class':'entry-content__text entry-content__text--topinfo'}).get_text()[13:]
ct = soup.find('h1', attrs={'class':'entry-title'})
for tag in ct.find_all('span'):
tag.replaceWith('')
claim = ct.get_text()
explain = soup.find('p', attrs={'class':'entry-content__text entry-content__text--explanation'}).get_text()[13:]
print(claim)
print(explain)
print(country)
print(date)
print(factcheck_Org)
return claim,explain,country,date,factcheck_Org
input_json = sys.argv[1]
output_json = sys.argv[2]
with open(input_json, 'r') as fin:
data = json.load(fin)
for i, each_data in enumerate(data):
claim,explain,country,date,factcheck_Org = download_source(each_data['Link'])
each_data['Claim'] = claim
each_data['Explaination'] = explain
each_data['Country'] = country
each_data['Date'] = date
each_data['Factcheck_Org'] = factcheck_Org
print(i, len(data))
#break
with open(output_json, 'w') as fo:
json.dump(data, fo)
| 1,648 | 29.537037 | 116 |
py
|
CANTM
|
CANTM-main/wvCovidData/update_label.py
|
import json
import re
import nltk
import argparse
import copy
import os
import sys
script_path = os.path.abspath(__file__)
print(script_path)
global parent
parent = os.path.dirname(script_path)
print(parent)
gatePython = os.path.join(parent, 'GATEpythonInterface')
sys.path.append(gatePython)
from GateInterface import *
import string
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("inputJson", help="args for test reader")
parser.add_argument("outputJson", help="args for test reader")
args = parser.parse_args()
input_json = args.inputJson
output_json = args.outputJson
label_dict = {
'no_evidence':['NO EVIDENCE', 'No evidence', 'No Evidence', 'no evidence', 'Unproven', 'Unverified'],
'misleading': ['misleading', 'Misleading', 'MISLEADING', 'mislEADING', 'MiSLEADING'],
'false': ['Pants on Fire!', 'False', 'FALSE', 'Not true', 'false and misleading', 'false', 'PANTS ON FIRE', 'Fake news', 'Misleading/False', 'Fake', 'Incorrect'],
'partial_false': ['Partially correct', 'mostly false', 'HALF TRUTH', 'HALF TRUE', 'partly false', 'Mostly true', 'Partly true', 'Mixed', 'half true', 'True but', 'MOSTLY FALSE', 'Partially false', 'PARTLY FALSE', 'Partially true', 'MOSTLY TRUE', 'Partly false', 'Mostly False', 'Partly False', 'PARTLY TRUE', 'Mostly True', 'Half True', 'Mostly false'],
}
with open(input_json, 'r') as fj:
raw_data = json.load(fj)
doc_id = 0
new_data = []
for item in raw_data:
item_keys = item.keys()
print(item_keys)
label = item['Label']
label_group = 'other'
for each_label_group in label_dict:
if label in label_dict[each_label_group]:
label_group = each_label_group
break
doc_id += 1
item['ori_label'] = label
item['Label'] = label_group
new_data.append(copy.deepcopy(item))
print(doc_id)
with open(output_json, 'w') as fo:
json.dump(new_data, fo)
| 1,941 | 30.322581 | 361 |
py
|
CANTM
|
CANTM-main/wvCovidData/update_type_media.py
|
import json
import re
import nltk
import argparse
import copy
import os
import sys
script_path = os.path.abspath(__file__)
print(script_path)
global parent
parent = os.path.dirname(script_path)
print(parent)
gatePython = os.path.join(parent, 'GATEpythonInterface')
sys.path.append(gatePython)
from GateInterface import *
import string
from pathlib import Path
source_out_folder = os.path.join(parent, 'test_text')
Path(source_out_folder).mkdir(parents=True, exist_ok=True)
printable = set(string.printable)
ignore_explist=[
['please', 'click', 'the', 'link', 'to', 'read', 'the', 'full', 'article'],
['please', 'read', 'the', 'full', 'article'],
]
def check_ori_claim_type(claim_web_ori):
media_type = set()
image = ['image', 'photo', 'picture', 'images', 'pictures', 'photos', 'infograph']
video = ['video', 'videos', 'television']
audio = ['audio', 'radio']
text = ['text', 'articles', 'article','message', 'messages']
#print(claim_web_ori)
for each_tok in claim_web_ori:
if each_tok in image:
media_type.add('image')
if each_tok in video:
media_type.add('video')
if each_tok in audio:
media_type.add('audio')
if each_tok in text:
media_type.add('text')
return list(media_type)
class JapeCheck:
def __init__(self):
self.gate = GateInterFace()
self.gate.init()
self.checkPipeline = GatePipeline('checkPipeline')
self.checkPipeline.loadPipelineFromFile(os.path.join(parent, 'japeCheck.xgapp'))
def check_jape(self, doc_name, claim_website):
print(doc_name)
document = GateDocument()
document.loadDocumentFromFile(doc_name)
#print(document)
testCorpus = GateCorpus('testCorpus')
testCorpus.addDocument(document)
self.checkPipeline.setCorpus(testCorpus)
self.checkPipeline.runPipeline()
ats = document.getAnnotations('')
media_type = ats.getType('mediaType')
#print(media_type.annotationSet)
media_type_dict = []
for item in media_type:
#print(item.features)
media_type_dict.append(item.features)
mediaTypeMatchedList, mediaTypeUnMatchedList = self.match_type(media_type_dict, claim_website)
loose_media_dict = []
loose_media = ats.getType('looseMedia')
for item in loose_media:
#print(item.features)
loose_media_dict.append(item.features)
looseMatchedList, looseUnMatchedList = self.match_type(loose_media_dict, claim_website)
document.clearDocument()
testCorpus.clearCorpus()
return self.select_type(mediaTypeMatchedList, mediaTypeUnMatchedList, looseMatchedList, looseUnMatchedList)
def count_match(self, matchedList):
current_max_type = None
current_max_count = 0
all_possible_types = set(matchedList)
for possible_type in all_possible_types:
current_possible_count = matchedList.count(possible_type)
if current_possible_count > current_max_count:
current_max_type = possible_type
current_max_count = current_possible_count
elif current_possible_count == current_max_count:
if possible_type == 'video':
current_max_type == 'video'
source_media = [current_max_type]
return source_media
def select_type(self, mediaTypeMatchedList, mediaTypeUnMatchedList, looseMatchedList, looseUnMatchedList):
source_media = []
if len(mediaTypeMatchedList) > 0:
source_media = mediaTypeMatchedList
elif len(looseMatchedList) > 0:
source_media = self.count_match(looseMatchedList)
#source_media = [looseMatchedList[0]]
elif len(mediaTypeUnMatchedList) > 0:
source_media = mediaTypeUnMatchedList
elif len(looseUnMatchedList) > 0:
source_media = self.count_match(looseUnMatchedList)
#current_max_type = None
#current_max_count = 0
#all_possible_types = set(looseUnMatchedList)
#for possible_type in all_possible_types:
# current_possible_count = looseUnMatchedList.count(possible_type)
# if current_possible_count > current_max_count:
# current_max_type = possible_type
# current_max_count = current_possible_count
#source_media = [current_max_type]
return source_media
def match_type(self,media_type_dict, webSite_list):
matched_list = []
unmatched_list = []
for item in media_type_dict:
try:
current_web = item['oriWeb']
except:
current_web = 'unknown'
try:
current_media = item['mediaType']
except:
current_media = 'unknown_web'
#print(current_web, current_media)
current_web_list = current_web.split(',')
#print(current_web_list)
current_media_list_raw = current_media.split(',')
current_media_list = []
for media_item in current_media_list_raw:
if len(media_item) > 0:
current_media_list.append(media_item)
web_match = False
for current_web_item in current_web_list:
if current_web_item in webSite_list:
#matched_list.append(current_media)
web_match = True
break
#unmatched_list.append(current_media)
if web_match:
matched_list += current_media_list
else:
unmatched_list += current_media_list
return matched_list, unmatched_list
parser = argparse.ArgumentParser()
parser.add_argument("inputJson", help="args for test reader")
parser.add_argument("outputJson", help="args for test reader")
parser.add_argument("--updateOnly", help="reverse selection criteria", default=False, action='store_true')
args = parser.parse_args()
input_json = args.inputJson
output_json = args.outputJson
with open(input_json, 'r') as fj:
raw_data = json.load(fj)
japeCheck = JapeCheck()
num_video_source = 0
doc_id = 0
new_data = []
punct_chars = list(set(string.punctuation)-set("_"))
punctuation = ''.join(punct_chars)
pun_replace = re.compile('[%s]' % re.escape(punctuation))
for item in raw_data:
update = True
type_of_media = item['Type_of_media']
claim = item['Claim']
explanation = item['Explaination']
claim = claim.lower()
claim = pun_replace.sub(' ', claim)
claim_tok = nltk.word_tokenize(claim)
explanation = explanation.lower()
explanation = pun_replace.sub(' ', explanation)
explanation_tok = nltk.word_tokenize(explanation)
#print(type_of_media)
if args.updateOnly:
if len(type_of_media) > 0:
update = False
else:
print(doc_id)
update = True
#print(update)
if update:
item_keys = item.keys()
#print(item_keys)
claim_website = item['Claim_Website']
#print(claim_website)
claim_website_ori = item['Claim_web_ori']
if 'p_tag' in item:
text_source = item['p_tag']
elif 'Source_PageTextEnglish' in item:
text_source = item['Source_PageTextEnglish']
else:
#print(doc_id)
text_source = item['Source_PageTextOriginal']
source_media = []
if ('youtube' in claim_website) or ('tv' in claim_website) or ('tiktok' in claim_website):
num_video_source += 1
source_media = ['video']
else:
media_type = check_ori_claim_type(claim_website_ori)
claim_media_type = check_ori_claim_type(claim_tok)
if explanation_tok not in ignore_explist:
exp_media_type = check_ori_claim_type(explanation_tok)
else:
print('!!!!!!!!', explanation_tok)
exp_media_type = []
if len(media_type) > 0:
num_video_source += 1
source_media = media_type
elif len(claim_media_type) > 0:
num_video_source += 1
source_media = claim_media_type
#print(source_media, claim_tok)
elif len(exp_media_type) > 0:
num_video_source += 1
source_media = exp_media_type
print(source_media, explanation_tok)
else:
print(claim_website_ori)
text_out = os.path.join(parent, 'test_text')
text_out = os.path.join(text_out, str(doc_id)+'.txt')
filterd_text_source = ''.join(filter(lambda x: x in printable, text_source))
#print(filterd_text_source)
if len(filterd_text_source) > 10:
with open(text_out, 'w') as fo:
fo.write(filterd_text_source)
source_media = japeCheck.check_jape(text_out, claim_website)
num_video_source += 1
doc_id += 1
print(source_media)
item['Type_of_media'] = list(set(source_media))
new_data.append(copy.deepcopy(item))
print(num_video_source)
with open(output_json, 'w') as fo:
json.dump(new_data, fo)
| 9,461 | 33.786765 | 115 |
py
|
CANTM
|
CANTM-main/wvCovidData/mergeAnnos.py
|
import sys
from WvLibs import WVdataIter
import re
from itertools import combinations
import argparse
import json
import logging
global logger
class Wv_loger:
def __init__(self, logging_level):
self.logger = logging.getLogger('root')
if logging_level == 'info':
self.logger.setLevel(logging.INFO)
elif logging_level == 'debug':
self.logger.setLevel(logging.DEBUG)
elif logging_level == 'warning':
self.logger.setLevel(logging.WARNING)
#self.logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('ROOT: %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
#self.logger.info('info message')
def logging(self, *args, logtype='debug', sep=' '):
getattr(self.logger, logtype)(sep.join(str(a) for a in args))
def info(self, *args, sep=' '):
getattr(self.logger, 'info')(sep.join(str(a) for a in args))
def debug(self, *args, sep=' '):
getattr(self.logger, 'debug')(sep.join(str(a) for a in args))
def warning(self, *args, sep=' '):
getattr(self.logger, 'warning')(sep.join(str(a) for a in args))
def clean_string(text):
text = text.strip()
text = text.replace('\t','')
text = text.replace('\n','')
return text
def getList(dict):
list = []
for key in dict.keys():
list.append(key)
return list
def check_pare(ann1, ann2, agreeDict):
combine1 = ann1+'|'+ann2
combine2 = ann2+'|'+ann1
combines = [combine1, combine2]
combineInDict = False
for combine in combines:
if combine in agreeDict:
combineInDict = True
break
return combine, combineInDict
def update_disagreement_dict(disagreeLabel1, disagreeLabel2, class_disagree_check_dict):
if disagreeLabel1 not in class_disagree_check_dict:
class_disagree_check_dict[disagreeLabel1] = {}
if disagreeLabel2 not in class_disagree_check_dict[disagreeLabel1]:
class_disagree_check_dict[disagreeLabel1][disagreeLabel2] = 0
class_disagree_check_dict[disagreeLabel1][disagreeLabel2] += 1
return class_disagree_check_dict
def calAgreement(dataIter, numlabels=11):
compare_list = []
pe = 1/numlabels
## get all paires
for item in dataIter:
tmp_list = []
anno_list = []
for annotation in item['annotations']:
label = annotation['label']
confident = annotation['confident']
annotator = annotation['annotator']
if annotator not in anno_list:
anno_list.append(annotator)
tmp_list.append([annotator, label])
combine_list = list(combinations(tmp_list, 2))
compare_list += combine_list
t=0
a=0
agreeDict = {}
for compare_pair in compare_list:
ann1 = compare_pair[0][0]
label1 = compare_pair[0][1]
ann2 = compare_pair[1][0]
label2 = compare_pair[1][1]
t+=1
combine, combineInDict = check_pare(ann1, ann2, agreeDict)
if combineInDict:
agreeDict[combine]['t'] += 1
else:
agreeDict[combine] = {}
agreeDict[combine]['t'] = 1
agreeDict[combine]['a'] = 0
agreeDict[combine]['disagree'] = {}
agreeDict[combine]['disagree'][ann1] = []
agreeDict[combine]['disagree'][ann2] = []
if label1 == label2:
a+=1
agreeDict[combine]['a'] += 1
else:
agreeDict[combine]['disagree'][ann1].append(label1)
agreeDict[combine]['disagree'][ann2].append(label2)
pa = a/t
#pe = 1/numlabels
#print(pe)
overall_kappa = (pa-pe)/(1-pe)
logger.warning('overall agreement: ', pa)
logger.warning('overall kappa: ', overall_kappa)
logger.warning('total pair compareed: ', t)
logger.warning('annotator pair agreement kappa num_compared')
class_disagree_check_dict = {}
for annPair in agreeDict:
logger.info('\n')
logger.info('============')
num_compared = agreeDict[annPair]['t']
cpa = agreeDict[annPair]['a']/agreeDict[annPair]['t']
kappa = (cpa-pe)/(1-pe)
logger.info(annPair, cpa, kappa, num_compared)
keys = getList(agreeDict[annPair]['disagree'])
logger.info(keys)
for i in range(len(agreeDict[annPair]['disagree'][keys[0]])):
disagreeLabel1 = agreeDict[annPair]['disagree'][keys[0]][i]
disagreeLabel2 = agreeDict[annPair]['disagree'][keys[1]][i]
logger.info(disagreeLabel1, disagreeLabel2)
class_disagree_check_dict = update_disagreement_dict(disagreeLabel1, disagreeLabel2, class_disagree_check_dict)
class_disagree_check_dict = update_disagreement_dict(disagreeLabel2, disagreeLabel1, class_disagree_check_dict)
logger.info('\n')
logger.info('=========================')
logger.info('class level disagreement')
logger.info('=========================')
for item_label in class_disagree_check_dict:
logging.info(item_label)
logging.info(class_disagree_check_dict[item_label])
logging.info('===================')
logging.info('\n')
return pa, overall_kappa
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("raw_json_dir", help="Unannotated Json file dir")
parser.add_argument("annoed_json_dir", help="Annotated Json file dir")
parser.add_argument("merged_json", help="merged json")
parser.add_argument("--ignoreLabel", help="ignore label, splited by using ,")
parser.add_argument("--ignoreUser", help="ignore user, splited by using ,")
parser.add_argument("--min_anno_filter", type=int, default=1, help="min annotation frequence")
parser.add_argument("--min_conf_filter", type=int, default=-1, help="min confident")
parser.add_argument("--output2csv", help="output to csv")
parser.add_argument("--transfer_label", default=None, help="trasfer label to another category, in format: orilabel1:tranlabel1,orilabel2:tranlabel2")
parser.add_argument("--cal_agreement", action='store_true',help="calculate annotation agreement")
parser.add_argument("--logging_level", default='warning', help="logging level, default warning, other option inlcude info and debug")
parser.add_argument("--user_conf", default=None, help="User level confident cutoff threshold, in format: user1:thres1,user2:thres2")
parser.add_argument("--set_reverse", default=False, action='store_true', help="reverse the selection condition, to check what discared")
#parser.add_argument("--logging_file", default='default.log',help="logging file")
args = parser.parse_args()
#logger = logging.getLogger()
output2csv = None
trans_dict = {}
raw_json_dir = args.raw_json_dir
annoed_json_dir = args.annoed_json_dir
merged_json = args.merged_json
min_frequence = args.min_anno_filter
min_conf = args.min_conf_filter
list2ignor = []
user2ignor = []
if args.ignoreLabel:
list2ignor = args.ignoreLabel.split(',')
if args.ignoreUser:
user2ignor = args.ignoreUser.split(',')
logging_level = args.logging_level
logger = Wv_loger(logging_level)
if args.output2csv:
output2csv = args.output2csv
if args.transfer_label:
all_trans_labels = args.transfer_label.split(',')
for label_pair in all_trans_labels:
tokened_pair = label_pair.split(':')
trans_dict[tokened_pair[0]] = tokened_pair[1]
user_conf_dict = {}
if args.user_conf:
all_user_conf = args.user_conf.split(',')
for conf_pair in all_user_conf:
tokened_pair = conf_pair.split(':')
user_conf_dict[tokened_pair[0]] = int(tokened_pair[1])
logger.warning(trans_dict)
dataIter = WVdataIter(annoed_json_dir, raw_json_dir, min_anno_filter=min_frequence, ignoreLabelList=list2ignor, ignoreUserList=user2ignor, label_trans_dict=trans_dict, check_validation=False, confThres=min_conf, reverse_selection_condition=args.set_reverse, logging_level=logging_level, annotator_level_confident=user_conf_dict)
data2merge = dataIter.getMergedData()
print('num selected data:', len(data2merge))
with open(merged_json, 'w') as fj:
json.dump(data2merge, fj)
num_labels = 11
if output2csv:
t=0
num_anno_dict = {}
num_label_dict = {}
with open(output2csv, 'w') as fo:
outline = 'id\tclaim\texplaination\tselected_label\tlables_from_annotator\n'
fo.write(outline)
for item in data2merge:
t += 1
num_annotation = len(item['annotations'])
if num_annotation not in num_anno_dict:
num_anno_dict[num_annotation] = 0
num_anno_dict[num_annotation] += 1
claim = clean_string(item['Claim'])
explaination = clean_string(item['Explaination'])
unique_id = item['unique_wv_id'].strip()
if 'selected_label' in item:
selected_label = item['selected_label']
else:
selected_label = ''
outline = unique_id+'\t'+claim+'\t'+explaination+'\t'+selected_label
for annotation in item['annotations']:
label = annotation['label']
confident = annotation['confident']
annotator = annotation['annotator']
if label not in num_label_dict:
num_label_dict[label] = 0
num_label_dict[label] += 1
outline += '\t'+label+'\t'+confident+'\t'+annotator
outline += '\n'
fo.write(outline)
print(num_anno_dict)
print(num_label_dict)
num_labels = len(num_label_dict)
if args.cal_agreement:
pa, kappa = calAgreement(dataIter, num_labels)
print('agreement: ', pa)
print('kappa: ', kappa)
| 10,180 | 33.986254 | 332 |
py
|
CANTM
|
CANTM-main/wvCovidData/update_website.py
|
import json
import re
import nltk
import sys
import string
import copy
class MediaTypeOrg:
def __init__(self):
punct_chars = list(set(string.punctuation)-set("_"))
print(punct_chars)
punctuation = ''.join(punct_chars)
self.replace = re.compile('[%s]' % re.escape(punctuation))
self.multi_word_dict = {'social media':'social_media'}
self.facebook = ['facebook', 'fb', 'faceboos', 'facebok', 'faceboook', 'facebooks', 'facebbok','faacebook','facebookk']
self.twitter = ['twitter', 'tweets','tweet']
self.news = ['media', 'news', 'newspaper', 'newspapers', 'times', 'abcnews','cgtn']
self.whatsApp = ['whatsapp', 'wa']
self.email = ['email']
self.social_media = ['social_media', 'weibo', 'wechat'] #######
self.youtube = ['youtube', 'youtuber']
self.blog = ['blog', 'bloggers', 'blogs', 'blogger']
self.instagram = ['instagram', 'ig']
self.tv = ['tv', 'television']
self.line = ['line']
self.tiktok = ['tiktok']
self.chainMessage = ['chain', 'telegram']
self.type_dict={
'facebook': self.facebook,
'twitter': self.twitter,
'news': self.news,
'whatsapp': self.whatsApp,
'email': self.email,
'youtube': self.youtube,
'blog': self.blog,
'instagram': self.instagram,
'tv': self.tv,
'line': self.line,
'chain_message': self.chainMessage,
'other_social_media': self.social_media,
'social_media': self.social_media+self.facebook+self.twitter+self.instagram,
'tiktok': self.tiktok
}
def type_org(self, data):
addi_type_dict = {}
ori_web_claim_dict = {}
num_other = 0
new_data = []
for each_data in data:
website_ori = each_data['Claim_web_ori']
included_type_list, tokened = self.get_type(website_ori)
if len(included_type_list) == 0:
num_other += 1
print(website_ori)
included_type_list.append('other')
each_data['Claim_Website'] = included_type_list
new_data.append(copy.deepcopy(each_data))
return new_data
def _check_item_in_list(self, tokened, check_list):
for item in tokened:
if item in check_list:
return True
return False
def _get_multiword(self, lower_case_string):
for item in self.multi_word_dict:
lower_case_string = re.sub(item, self.multi_word_dict[item], lower_case_string)
return lower_case_string
def get_type(self, tokened):
#print(tokened)
#print(raw_media_type)
#lc_raw_mt = raw_media_type.lower()
#lc_raw_mt = self._get_multiword(lc_raw_mt)
#lc_raw_mt_re = self.replace.sub(' ', lc_raw_mt)
#tokened = nltk.word_tokenize(lc_raw_mt_re)
included_type_list = []
for media_type in self.type_dict:
check_list = self.type_dict[media_type]
type_included = self._check_item_in_list(tokened, check_list)
if type_included:
included_type_list.append(media_type)
###check media
#for search_string in self.social_media:
# m = re.search(search_string, lc_raw_mt)
# if m:
# #print(raw_media_type)
# included_type_list.append('social_media')
#print(included_type_list)
return included_type_list, tokened
json_file = sys.argv[1]
output_file = sys.argv[2]
with open(json_file, 'r') as fj:
data = json.load(fj)
typeCheck = MediaTypeOrg()
new_data = typeCheck.type_org(data)
with open(output_file, 'w') as fo:
json.dump(new_data, fo)
| 3,918 | 30.352 | 127 |
py
|
CANTM
|
CANTM-main/wvCovidData/getData.py
|
import wget
import os
import zipfile
script_path = os.path.abspath(__file__)
print(script_path)
parent = os.path.dirname(script_path)
print(parent)
data_url = 'https://gate.ac.uk/g8/page/show/2/gatewiki/cow/covid19catedata/covidCateData.zip'
wget.download(data_url, parent)
zip_path = os.path.join(parent, 'covidCateData.zip')
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(parent)
| 411 | 21.888889 | 93 |
py
|
CANTM
|
CANTM-main/wvCovidData/WvLibs/WVdataIter.py
|
from .DataReader import DataReader
import random
def disagreementSolver(annotations, local_logger=None):
mergeMethodList = ['single_annotation', 'all_agreement', 'majority_agreement', 'majority_confidence', 'highest_confidence']
mergeMethod = None
annotation_list = []
label_list = []
annotator_list = []
all_labels_include_duplicats = []
for annotation in annotations:
label = annotation['label']
confident = annotation['confident']
annotator = annotation['annotator']
all_labels_include_duplicats.append([label, confident, annotator])
# for each annotator, we only consider once
if annotator not in annotator_list:
annotator_list.append(annotator)
annotation_list.append([label, confident, annotator])
label_list.append(label)
label_set = list(set(label_list))
set_count = [0]*len(label_set)
conf_sum = [0]*len(label_set)
for idx, current_label in enumerate(label_set):
set_count[idx] = label_list.count(current_label)
sorted_count = sorted(set_count, reverse=True)
for each_annotation in annotation_list:
label_set_idx = label_set.index(each_annotation[0])
try:
conf_sum[label_set_idx] += int(each_annotation[1])
except:
pass
sorted_conf_sum = sorted(conf_sum, reverse=True)
## if only 1 label, or all annotator agree eachother
if len(label_set) == 1:
selected_label = label_set[0]
if len(annotation_list) == 1:
mergeMethod = 'single_annotation'
else:
mergeMethod = 'all_agreement'
## if have majority agreement
elif sorted_count[0] > sorted_count[1]:
selected_label_idx = set_count.index(sorted_count[0])
selected_label = label_set[selected_label_idx]
mergeMethod = 'majority_agreement'
## if have higer summed confidence
elif sorted_conf_sum[0] > sorted_conf_sum[1]:
selected_label_idx = conf_sum.index(sorted_conf_sum[0])
selected_label = label_set[selected_label_idx]
mergeMethod = 'majority_confidence'
## else pick the lable have highest confidence
else:
sorted_annotation_list = sorted(annotation_list, key=lambda s:s[1], reverse=True)
selected_label = sorted_annotation_list[0][0]
mergeMethod = 'highest_confidence'
if local_logger:
local_logger(selected_label, annotation_list, logtype='debug')
return selected_label, mergeMethod
class WVdataIter(DataReader):
def __init__(self, annoed_json_dir, raw_json, min_anno_filter=-1, postProcessor=None, shuffle=False, check_validation=False, **kwargs):
super().__init__(annoed_json_dir, raw_json, kwargs)#ignoreLabelList=ignoreLabelList, ignoreUserList=ignoreUserList, confThres=confThres, ignore_empty=ignore_empty)
self.shuffle = shuffle
self.check_validation = check_validation
self.filterByMinAnno(min_anno_filter)
self._reset_iter()
self.postProcessor = postProcessor
def filterByMinAnno(self, min_anno_filter):
self.min_anno_filter = min_anno_filter
all_links = []
for link in self.data_dict:
num_annotations = len(self.data_dict[link]['annotations'])
if num_annotations >= self.min_anno_filter:
if self.check_validation:
if self._check_annotation_valid(self.data_dict[link]['annotations']):
all_links.append(link)
else:
all_links.append(link)
self.all_links = all_links
def _check_annotation_valid(self, annotation):
at_least_one_ture = False
for item in annotation:
current_label = item['label']
current_confident = item['confident']
if len(current_label) > 0 and len(current_confident)>0:
at_least_one_ture = True
return at_least_one_ture
def __iter__(self):
if self.shuffle:
random.shuffle(self.all_links)
self._reset_iter()
return self
def __next__(self):
if self.current_sample_idx < len(self.all_links):
current_sample = self._readNextSample()
self.current_sample_idx += 1
if self.postProcessor:
return self.postProcessor(current_sample)
else:
return current_sample
else:
self._reset_iter()
raise StopIteration
def _readNextSample(self):
current_link = self.all_links[self.current_sample_idx]
current_sample = self.data_dict[current_link]
return current_sample
def __len__(self):
return len(self.all_links)
def _reset_iter(self):
self.current_sample_idx = 0
def getMergedData(self, disagreementSolver=disagreementSolver):
merge_method_dict = {}
merged_data_list = []
merged_label_count = {}
for item in self:
if (len(item['annotations']) > 0) and disagreementSolver:
annotations = item['annotations']
selected_label,merge_method = disagreementSolver(annotations, self.logging)
if merge_method not in merge_method_dict:
merge_method_dict[merge_method] = 0
if selected_label not in merged_label_count:
merged_label_count[selected_label] = 0
item['selected_label'] = selected_label
merge_method_dict[merge_method] += 1
merged_label_count[selected_label] += 1
merged_data_list.append(item)
self.logging(merge_method_dict, logtype='info')
self.logging(merged_label_count, logtype='info')
return merged_data_list
| 5,834 | 36.403846 | 171 |
py
|
CANTM
|
CANTM-main/wvCovidData/WvLibs/__init__.py
|
from .DataReader import DataReader
from .WVdataIter import WVdataIter
| 70 | 22.666667 | 34 |
py
|
CANTM
|
CANTM-main/wvCovidData/WvLibs/DataReader.py
|
import json
import glob
import os
import re
import hashlib
import logging
import sys
class DataReader:
def __init__(self, annoed_json_dir, raw_json_dir, kwargs):
self._read_input_options(kwargs)
print('label ignored: ', self.ignoreLabelList)
print('user ignored: ', self.ignoreUserList)
self._setReaderLogger()
self._anno_user_regex()
self._read_raw_json(raw_json_dir)
self._read_annoed_data(annoed_json_dir)
def _setReaderLogger(self):
self.readerLogger = logging.getLogger('readerLogger')
if self.logging_level == 'info':
self.readerLogger.setLevel(logging.INFO)
elif self.logging_level == 'debug':
self.readerLogger.setLevel(logging.DEBUG)
elif self.logging_level == 'warning':
self.readerLogger.setLevel(logging.WARNING)
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('DataReader: %(message)s')
handler.setFormatter(formatter)
self.readerLogger.addHandler(handler)
def logging(self, *args, logtype='info', sep=' '):
getattr(self.readerLogger, logtype)(sep.join(str(a) for a in args))
def _read_input_options(self, kwargs):
self.ignoreLabelList = kwargs.get('ignoreLabelList', [])
self.ignoreUserList = kwargs.get('ignoreUserList', [])
self.confThres = kwargs.get('confThres', -1)
self.filter_no_conf = kwargs.get('filter_no_conf', False)
self.ignore_empty = kwargs.get('ignore_empty', False)
self.label_trans_dict = kwargs.get('label_trans_dict', None)
self.logging_level = kwargs.get('logging_level', 'warning')
self.reverse_selection_condition = kwargs.get('reverse_selection_condition', False)
self.annotator_level_confident = kwargs.get('annotator_level_confident', {})
def _anno_user_regex(self):
self.label_field_regex = re.compile('ann\d*\_label')
self.annotator_id_regex = re.compile('(?<=ann)\d*(?=\_label)')
self.confident_field_regex = re.compile('ann\d*\_conf')
self.remark_field_regex = re.compile('ann\d*\_remarks')
def _read_annoed_data(self, annoed_json_dir):
all_jsons = glob.glob(annoed_json_dir+'/*.json')
for each_annoed_json_file in all_jsons:
self._read_annoed_json(each_annoed_json_file)
#print(all_jsons)
def _read_annoed_json(self, annoed_json):
with open(annoed_json, 'r') as f_json:
all_json_data = json.load(f_json)
for each_annoed_data in all_json_data:
uniqueIdentifier = self._get_unique_identifier(each_annoed_data)
annotation_info, include = self._get_annotation_info(each_annoed_data)
if len(annotation_info['label']) < 0 and ignore_empty:
include = False
if self.reverse_selection_condition:
if include == False:
include = True
else:
include = False
if include:
self.data_dict[uniqueIdentifier]['annotations'].append(annotation_info)
def _translabel(self, label):
if label in self.label_trans_dict:
transferd_label = self.label_trans_dict[label]
else:
transferd_label = label
return transferd_label
def _get_annotation_info(self, dict_data):
annotation_info_dict = {}
dict_keys = dict_data.keys()
include = True
annotator_id = None
for current_key in dict_keys:
m_label = self.label_field_regex.match(current_key)
if m_label:
raw_label_field = m_label.group()
#print(raw_label_field)
annotator_id = self.annotator_id_regex.search(raw_label_field).group()
#print(annotator_id)
annotation_info_dict['annotator'] = annotator_id
label = dict_data[raw_label_field]
if self.label_trans_dict:
label = self._translabel(label)
annotation_info_dict['label'] = label
if label in self.ignoreLabelList:
include = False
if annotator_id in self.ignoreUserList:
include = False
m_conf = self.confident_field_regex.match(current_key)
if m_conf:
raw_conf_field = m_conf.group()
confident = dict_data[raw_conf_field]
annotation_info_dict['confident'] = confident
if len(confident) < 1:
if self.filter_no_conf:
include = False
elif annotator_id in self.annotator_level_confident:
if int(confident) <= self.annotator_level_confident[annotator_id]:
include = False
elif (int(confident) <= self.confThres):
include = False
m_remark = self.remark_field_regex.match(current_key)
if m_remark:
raw_remark_field = m_remark.group()
remark = dict_data[raw_remark_field]
#print(remark)
annotation_info_dict['remark'] = remark
return annotation_info_dict, include
def _get_unique_identifier(self, each_data):
source_link = each_data['Source'].strip()
claim = each_data['Claim'].strip()
explaination = each_data['Explaination'].strip()
sourceToken = source_link.split('/')
top3Source = ' '.join(sourceToken[:3])
top200claim = claim[:200]
top200expl = explaination[:200]
uniqueString = top200claim+top200expl+top3Source
#sourceQuesionToken = source_link.split('?')
#uniqueString = sourceQuesionToken[0]
#print(uniqueString)
uniqueIdentifier = hashlib.sha224(uniqueString.encode('utf-8')).hexdigest()
return uniqueIdentifier
def _read_raw_json(self, raw_json_dir):
self.data_dict = {}
all_raw_jsons = glob.glob(raw_json_dir+'/*.json')
duplicated = 0
total_data = 0
for each_raw_json in all_raw_jsons:
ct=0
cd=0
with open(each_raw_json, 'r') as f_json:
raw_data = json.load(f_json)
for each_data in raw_data:
#data_link = each_data['Link']
uniqueIdentifier = self._get_unique_identifier(each_data)
if uniqueIdentifier not in self.data_dict:
each_data['unique_wv_id'] = uniqueIdentifier
each_data['annotations'] = []
self.data_dict[uniqueIdentifier] = each_data
else:
duplicated += 1
cd+=1
self.logging(uniqueIdentifier, logtype='debug')
self.logging('id: ', self.data_dict[uniqueIdentifier]['unique_wv_id'], logtype='debug')
self.logging(self.data_dict[uniqueIdentifier], logtype='debug')
self.logging(each_data, logtype='debug')
self.logging('\n', logtype='debug')
total_data += 1
ct+=1
#print(ct, cd)
#self.logging('Num selected data: ', len(self.data_dict), logtype='warning')
self.logging('num duplicated: ', duplicated, logtype='info')
self.logging('total num data: ', total_data, logtype='info')
| 7,530 | 39.058511 | 107 |
py
|
CANTM
|
CANTM-main/wvCovidData/GATEpythonInterface/example.py
|
from GateInterface import *
#initialise gate
gate= GateInterFace()
# path to gate interface, for my case is /Users/xingyi/Gate/gateCodes/pythonInferface
# this will open java tcp server (on port 7899) to execute GATE operation
#gate.init('/Users/xingyi/Gate/gateCodes/pythonInferface')
gate.init('./')
# load document from url
document = GateDocument()
document.loadDocumentFromURL("https://gate.ac.uk")
# load document from local file e.g.
#document.loadDocumentFromFile("/Users/xingyi/Gate/gateCodes/pythonInferface/ft-airlines-27-jul-2001.xml")
# get content from file
content = document.getDocumentContent()
print(content)
# get annotation set name
atsName = document.getAnnotationSetNames()
print(atsName)
#get Original markups annotation set
ats = document.getAnnotations('Original markups')
# load maven plugins
gate.loadMvnPlugins("uk.ac.gate.plugins", "annie", "8.5")
# load PRs
gate.loadPRs('gate.creole.annotdelete.AnnotationDeletePR', 'anndeletePR')
gate.loadPRs('gate.creole.tokeniser.DefaultTokeniser', 'defToken')
# set initialise parameter for PR
#prparameter['grammarURL'] = 'file:////Users/xingyi//Gate/ifpri/JAPE/main.jape'
#gate.loadPRs('gate.creole.Transducer', prparameter)
# create a pipeline
testPipeLine = GatePipeline('testpipeline')
testPipeLine.createPipeline()
# add PRs to the pipeline
testPipeLine.addPR('anndeletePR')
testPipeLine.addPR('defToken')
# get params
print(testPipeLine.checkRunTimeParams('anndeletePR', 'setsToKeep'))
# set run time params
testPipeLine.setRunTimeParams('anndeletePR', 'keepOriginalMarkupsAS', 'false', 'Boolean')
testPipeLine.setRunTimeParams('anndeletePR', 'setsToKeep', 'Key,Target', 'List')
print(testPipeLine.checkRunTimeParams('anndeletePR', 'setsToKeep'))
# create gate corpus
testCorpus = GateCorpus('testCorpus')
# add document to the corpus
testCorpus.addDocument(document)
# set corpus for pipeline
testPipeLine.setCorpus(testCorpus)
# run pipeline
testPipeLine.runPipeline()
# get default annotation set after run the pipeline, the annotation is stored in local python format
defaultats = document.getAnnotations('')
# load appilication from file
#testPipeline2 = GatePipeline('testpipeline2')
#testPipeLine.loadPipelineFromFile('/Users/xingyi/Gate/ifpri/ifpri.xgapp')
# close the port
gate.close()
| 2,298 | 28.101266 | 106 |
py
|
CANTM
|
CANTM-main/wvCovidData/GATEpythonInterface/GateInterface/GateInterface.py
|
import socket
import json
import re
import os
import subprocess
import time
import signal
import pathlib
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(MyEncoder, self).default(obj)
class GateInterFace:
def __init__(self):
self.PORT = 7899
self.HOST = "localhost"
self.maxSendChar = 512
self.maxRecvChar = 512
self.loadedPlugins = []
self.loadedPrs = []
self.pro = None
self.logFile = "gpiterface"+str(self.PORT)+".log"
self.interfaceJavaPath = None
def init(self, interfaceJavaPath=None):
if interfaceJavaPath:
self.interfaceJavaPath = interfaceJavaPath
else:
interfaceJavaPath = pathlib.Path(__file__).parent.absolute()
self.interfaceJavaPath = interfaceJavaPath.parent
cwd = os.getcwd()
runScript = os.path.join(self.interfaceJavaPath,'run.sh')
os.chdir(self.interfaceJavaPath)
if (os.path.isfile(self.logFile)):
print("logfile existed, try to close previous session")
try:
with open(self.logFile,'r') as fin:
line = fin.readline().strip()
pid = int(line)
os.killpg(os.getpgid(pid), signal.SIGTERM)
except:
print("can not kill process-"+str(pid)+"please close manully")
print(runScript)
#self.pro = subprocess.Popen(["bash", runScript])
hostportArg = "-Dexec.args=\""+str(self.PORT)+"\""
args=["mvn", "exec:java", "-Dexec.mainClass=uk.ac.gate.python.pythonInferface.GateServer",hostportArg]
#self.pro = subprocess.Popen(["mvn", "exec:java -Dexec.mainClass=uk.ac.gate.python.pythonInferface.GateServer -Dexec.args="7899""])
self.pro = subprocess.Popen(args)
with open(self.logFile,'w') as fo:
fo.write(str(self.pro.pid))
os.chdir(cwd)
time.sleep(5)
def close(self):
print(self.pro.pid)
logFile = os.path.join(self.interfaceJavaPath, self.logFile)
print(logFile)
os.remove(logFile)
os.killpg(os.getpgid(self.pro.pid), signal.SIGTERM)
#try:
# os.killpg(os.getpgid(self.pro.pid), signal.SIGTERM)
# logFile = os.path.join(self.interfaceJavaPath, self.logFile)
# print(logFile)
# os.remove(logFile)
#except:
# print("logfile not correctly removed")
def test(self):
self._sendDoc2Java('test','this is test sent')
def _sendDoc2Java(self, jsonKey, jsonValue):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.HOST, self.PORT))
previ = 0
i = self.maxSendChar
eov = False #if value length larger than self.maxChar then send in sepate packages to java
valueLen = len(jsonValue)
while(eov == False):
subValue = jsonValue[previ:i]
if i < valueLen:
eov = False
else:
eov = True
jsonSend = {'fromClient':{jsonKey:subValue, 'eov':eov}}
previ = i
i += self.maxSendChar
sock.sendall((json.dumps(jsonSend, cls=MyEncoder)+"\n").encode('utf-8'))
serverReturn = self._recvDocFromJava(sock)
sock.close()
#print(serverReturn)
return serverReturn
def _send2Java(self, jsonDict):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#print(self.HOST,self.PORT)
sock.connect((self.HOST, int(self.PORT)))
#print(jsonDict)
for jsonKey in jsonDict:
#print(jsonKey)
jsonValue = jsonDict[jsonKey]
valueLen = len(jsonValue)
previ = 0
i = self.maxSendChar
eov = False #if value length larger than self.maxChar then send in sepate packages to java
while(eov == False):
subValue = jsonValue[previ:i]
if i < valueLen:
eov = False
else:
eov = True
jsonSend = {'fromClient':{jsonKey:subValue, 'eov':False}}
previ = i
i += self.maxSendChar
#print(jsonSend)
sock.sendall((json.dumps(jsonSend, cls=MyEncoder)+"\n").encode('utf-8'))
#print('finish')
jsonSend = {'fromClient':{'eov':True}}
sock.sendall((json.dumps(jsonSend, cls=MyEncoder)+"\n").encode('utf-8'))
serverReturn = self._recvDocFromJava(sock)
sock.close()
#print(serverReturn)
return serverReturn
def _recvDocFromJava(self, sock):
fullReturn = ""
eov = False
fullReturn = {}
while(eov ==False):
data_recv = sock.recv(self.maxRecvChar)
data = json.loads(data_recv)
eov = data['eov']
for item in data:
partReturn = data[item]
if item not in fullReturn:
fullReturn[item] = partReturn
else:
fullReturn[item] += partReturn
sock.sendall("success\n".encode('utf-8'))
return fullReturn
def loadMvnPlugins(self, group, artifact, version):
jsonDict = {}
jsonDict['plugin'] = 'maven'
jsonDict['group'] = group
jsonDict['artifact'] = artifact
jsonDict['version'] = version
response = self._send2Java(jsonDict)
if response['message'] == 'success':
self.loadedPlugins.append(response['pluginLoaded'])
return response
def loadPRs(self, resourcePath, name, features=None):
jsonDict = {}
if features == None:
jsonDict['loadPR'] = 'withoutFeature'
else:
jsonDict['loadPR'] = 'withFeature'
i = 0
for featureKey in features:
keyName = 'prFeatureName'+str(i)
valueName = 'prFeatureValue'+str(i)
jsonDict[keyName] = featureKey
jsonDict[valueName] = features[featureKey]
i+=1
jsonDict['resourcePath'] = resourcePath
jsonDict['name'] = name
response = self._send2Java(jsonDict)
if response['message'] == 'success':
self.loadedPrs.append(response['PRLoaded'])
return response
def reinitPRs(self, name):
jsonDict = {}
jsonDict['reInitPR'] = 'none'
jsonDict['name'] = name
response = self._send2Java(jsonDict)
if response['message'] != 'success':
print('error unable to reinit pr', name)
return response['message']
class AnnotationSet(GateInterFace):
def __init__(self):
GateInterFace.__init__(self)
self.annotationSet = []
def __len__(self):
return len(self.annotationSet)
def __iter__(self):
for node in self.annotationSet:
yield node
def getType(self, annotationType, startidx=None, endidx=None):
newList = []
for annotation in self.annotationSet:
if annotation.type == annotationType:
if startidx and endidx:
if annotation.startNode.offset >= startidx and annotation.endNode.offset <= endidx:
newList.append(annotation)
else:
newList.append(annotation)
subSet = AnnotationSet()
subSet.annotationSet = newList
return subSet
def getbyRange(self, startidx=0, endidx=None):
newList = []
for annotation in self.annotationSet:
if annotation.startNode.offset >= startidx:
if endidx:
if annotation.endNode.offset <= endidx:
newList.append(annotation)
else:
newList.append(annotation)
subSet = AnnotationSet()
subSet.annotationSet = newList
return subSet
def get(self,i):
return self.annotationSet[i]
def getbyId(self, annoId):
returnAnno = None
for annotation in self.annotationSet:
if annotation.id == annoId:
returnAnno = annotation
break
return returnAnno
def append(self, annotation):
self.annotationSet.append(annotation)
def _getAnnotationFromResponse(self,response):
annotationResponse = response['annotationSet']
annotationList = annotationResponse.split('\n, Anno')
#print('getting annotation from response')
#print(len(annotationList))
#print(annotationList[0])
idPattern = '(?<=tationImpl\: id\=)\d*(?=\; type\=.*\;)'
typePattern = '(?<=; type\=).*(?=\; features\=)'
featurePattern = '(?<=; features\=\{)[\S\s]*(?=\}\; start\=.*\;)'
startNodePattern = '(?<=; start\=NodeImpl\: ).*(?= end\=NodeImpl)'
endNodePattern = '(?<=; end\=NodeImpl\: ).*'
fullPattern = 'AnnotationImpl\: id\=\d*\; type\=.*\; features\=\{.*\}\; start\=NodeImpl\: id\=\d*\; offset\=\d*\; end\=NodeImpl\: id\=\d*\; offset\=\d*'
for rawAnnotationLine in annotationList:
#print(rawAnnotationLine)
#m = re.search(fullPattern, rawAnnotationLine)
#print(m)
#if m:
# print('match')
try:
#if 1:
#print(rawAnnotationLine)
currentAnnotation = Annotation()
currentAnnotation.id = int(re.search(idPattern,rawAnnotationLine).group(0))
currentAnnotation.type = re.search(typePattern,rawAnnotationLine).group(0)
#print(len(re.search(featurePattern,rawAnnotationLine).group(0)))
currentAnnotation._setFeatureFromRawLine(re.search(featurePattern,rawAnnotationLine).group(0))
#print(currentAnnotation.id)
#print(currentAnnotation.type)
#print(currentAnnotation.features)
currentAnnotation._setStartNode(re.search(startNodePattern,rawAnnotationLine).group(0))
currentAnnotation._setEndNode(re.search(endNodePattern,rawAnnotationLine).group(0))
#print(currentAnnotation.startNode.id, currentAnnotation.startNode.offset)
#print(currentAnnotation.endNode.id, currentAnnotation.endNode.offset)
self.annotationSet.append(currentAnnotation)
except:
#print('bad line, ignore')
#print(rawAnnotationLine)
pass
#currentAnnotation = Annotation()
#currentAnnotation.id = int(re.search(idPattern,rawAnnotationLine).group(0))
#currentAnnotation.type = re.search(typePattern,rawAnnotationLine).group(0)
#currentAnnotation._setFeatureFromRawLine(re.search(featurePattern,rawAnnotationLine).group(0))
#print(currentAnnotation.id)
#print(currentAnnotation.type)
#print(currentAnnotation.features)
#currentAnnotation._setStartNode(re.search(startNodePattern,rawAnnotationLine).group(0))
#currentAnnotation._setEndNode(re.search(endNodePattern,rawAnnotationLine).group(0))
#print(currentAnnotation.startNode.id, currentAnnotation.startNode.offset)
#print(currentAnnotation.endNode.id, currentAnnotation.endNode.offset)
#self.annotationSet.append(currentAnnotation)
class Annotation:
def __init__(self):
self.id = None
self.type = None
self.features = {}
self.startNode = None
self.endNode = None
def overlap_set(self, compareSet):
overlap = False
for compare_annotation in compareSet:
overlap = self.overlaps(compare_annotation)
if overlap:
break
return overlap
def matches(self, compareAnno):
startNodeOffsetMatch = self.startNode.offset == compareAnno.startNode.offset
endNodeOffsetMatch = self.endNode.offset == compareAnno.endNode.offset
if startNodeOffsetMatch and endNodeOffsetMatch:
return True
def overlaps(self, compareAnno):
selfStart = self.startNode.offset
selfEnd = self.endNode.offset-1
compareStart = compareAnno.startNode.offset
compareEnd = compareAnno.endNode.offset-1
if selfStart <= compareStart:
if selfEnd >= compareStart:
return True
else:
return False
elif selfStart >= compareStart:
if compareEnd >= selfStart:
return True
else:
return False
def _setFeatureFromRawLine(self, rawFeatureLine):
#print(rawFeatureLine)
if len(rawFeatureLine) > 0:
#replace comma in list to |||
listPattern = '(?<=\=)\[[\w \,]+\]'
listFeatures = re.findall(listPattern, rawFeatureLine)
for listFeature in listFeatures:
newPattern = re.sub(', ',' ||| ', listFeature)
rawFeatureLine = rawFeatureLine.replace(listFeature, newPattern)
splittedFeatures = re.split(', ',rawFeatureLine)
#print(splittedFeatures)
for splittedFeature in splittedFeatures:
featureTok = splittedFeature.split('=')
featureKey = featureTok[0]
featureValue = featureTok[1]
if self._isListFeature(featureValue):
#self.features[featureKey] = []
listValues = featureValue[1:-1].split(' ||| ')
self.features[featureKey] = listValues
else:
self.features[featureKey] = featureValue
def _isListFeature(self, featureValue):
pattern = '\[.*\]'
m = re.match(pattern, featureValue)
if m:
return True
else:
return False
def _setStartNode(self, rawLine):
idPattern = '(?<=id\=)\d*(?=\;)'
offSetPattern = '(?<=offset\=)\d*(?=(\;)|($))'
nodeId = int(re.search(idPattern, rawLine).group(0))
offset = int(re.search(offSetPattern, rawLine).group(0))
#print(nodeId, offset)
startNode = Node()
startNode.id = nodeId
startNode.offset = offset
self.startNode = startNode
def _setEndNode(self, rawLine):
idPattern = '(?<=id\=)\d*(?=\;)'
offSetPattern = '(?<=offset\=)\d*(?=(\;)|($))'
nodeId = int(re.search(idPattern, rawLine).group(0))
offset = int(re.search(offSetPattern, rawLine).group(0))
#print(nodeId, offset)
endNode = Node()
endNode.id = nodeId
endNode.offset = offset
self.endNode = endNode
class Node:
def __init__(self):
self.id = None
self.offset = None
class GateDocument(GateInterFace):
def __init__(self):
GateInterFace.__init__(self)
self.documentName = None
def loadDocumentFromURL(self, documentURL):
documentName = documentURL
serverReturn = self._sendDoc2Java('loadDocumentFromURL', documentURL)
if serverReturn['message'] == 'success':
self.documentName = documentName
#print(serverReturn)
def loadDocumentFromFile(self, documentPath):
documentName = documentPath
serverReturn = self._sendDoc2Java('loadDocumentFromFile', documentPath)
#print(serverReturn)
if serverReturn['message'] == 'success':
self.documentName = documentName
#print(serverReturn)
def getDocumentContent(self):
jsonDict = {}
jsonDict['document'] = 'getDocumentContent'
jsonDict['docName'] = self.documentName
response = self._send2Java(jsonDict)
docContent = response['docContent']
return docContent
def getAnnotationSetNames(self):
jsonDict = {}
jsonDict['document'] = 'getAnnotationSetName'
jsonDict['docName'] = self.documentName
response = self._send2Java(jsonDict)
astName = response['annotationSetName']
return astName
def getAnnotations(self, annotationSetName):
jsonDict = {}
jsonDict['document'] = 'getAnnotations'
jsonDict['docName'] = self.documentName
jsonDict['annotationSetName'] = annotationSetName
currentAnnotationSet = AnnotationSet()
#print(jsonDict)
response = self._send2Java(jsonDict)
#print(response)
currentAnnotationSet._getAnnotationFromResponse(response)
return currentAnnotationSet
def clearDocument(self):
jsonDict = {}
jsonDict['clearDocument'] = self.documentName
response = self._send2Java(jsonDict)
class GatePipeline(GateInterFace):
def __init__(self, pipelineName):
GateInterFace.__init__(self)
self.pipelineName = pipelineName
self.corpus = None
self.prList = []
def loadPipelineFromFile(self, filePath):
jsonDict = {}
jsonDict['pipeline'] = 'loadPipelineFromFile'
jsonDict['pipelineName'] = self.pipelineName
jsonDict['filtPath'] = filePath
response = self._send2Java(jsonDict)
#print(response)
def createPipeline(self):
jsonDict = {}
jsonDict['pipeline'] = 'createPipeline'
jsonDict['pipelineName'] = self.pipelineName
response = self._send2Java(jsonDict)
#print(response)
def addPR(self, prName):
jsonDict = {}
jsonDict['pipeline'] = 'addPR'
jsonDict['pipelineName'] = self.pipelineName
jsonDict['prName'] = prName
response = self._send2Java(jsonDict)
#print(response)
self.prList.append(prName)
def setCorpus(self, corpus):
corpusName = corpus.corpusName
jsonDict = {}
jsonDict['pipeline'] = 'setCorpus'
jsonDict['pipelineName'] = self.pipelineName
jsonDict['corpusName'] = corpusName
response = self._send2Java(jsonDict)
#print(response)
self.corpus = corpus
def runPipeline(self):
jsonDict = {}
jsonDict['pipeline'] = 'runPipeline'
jsonDict['pipelineName'] = self.pipelineName
response = self._send2Java(jsonDict)
#print(response)
def checkRunTimeParams(self, prName, paramName):
jsonDict = {}
jsonDict['pipeline'] = 'checkParams'
jsonDict['pipelineName'] = self.pipelineName
jsonDict['resourceName'] = prName
jsonDict['paramsName'] = paramName
response = self._send2Java(jsonDict)
#print(response)
return response['message']
def setRunTimeParams(self, prName, paramName, paramValue, paramType):
jsonDict = {}
jsonDict['pipeline'] = 'setParams'
jsonDict['pipelineName'] = self.pipelineName
jsonDict['resourceName'] = prName
jsonDict['paramsName'] = paramName
jsonDict['paramsValue'] = paramValue
jsonDict['paramsType'] = paramType
response = self._send2Java(jsonDict)
class GateCorpus(GateInterFace):
def __init__(self, corpusName):
GateInterFace.__init__(self)
self.corpusName = corpusName
self._createCorpus()
self.documentList = []
def _createCorpus(self):
jsonDict = {}
jsonDict['corpus'] = 'createCorpus'
jsonDict['corpusName'] = self.corpusName
response = self._send2Java(jsonDict)
#print(response)
def clearCorpus(self):
jsonDict = {}
jsonDict['corpus'] = 'clearCorpus'
jsonDict['corpusName'] = self.corpusName
response = self._send2Java(jsonDict)
def addDocument(self, document):
documentName = document.documentName
jsonDict = {}
jsonDict['corpus'] = 'addDocument'
jsonDict['corpusName'] = self.corpusName
jsonDict['documentName'] = documentName
response = self._send2Java(jsonDict)
#print(response)
self.documentList.append(document)
#if __name__ == "__main__":
# gate= GateInterFace()
# gate.init('/Users/xingyi/Gate/gateCodes/pythonInferface')
# #gate.test()
# document = GateDocument()
# document.loadDocumentFromURL("https://gate.ac.uk")
# #document.loadDocumentFromFile("/Users/xingyi/Gate/gateCodes/pythonInferface/ft-airlines-27-jul-2001.xml")
# #print(document.documentName)
# #content = document.getDocumentContent()
# #print(content)
# #atsName = document.getAnnotationSetNames()
# #print(atsName)
# #ats = document.getAnnotations('')
# #print(len(ats.annotationSet))
# #print(ats.annotationSet[0])
# response=gate.loadMvnPlugins("uk.ac.gate.plugins", "annie", "8.5")
# print(response)
# prparameter={}
# response=gate.loadPRs('gate.creole.annotdelete.AnnotationDeletePR')
# response=gate.loadPRs('gate.creole.tokeniser.DefaultTokeniser')
# prparameter['grammarURL'] = 'file:////Users/xingyi//Gate/ifpri/JAPE/main.jape'
# response=gate.loadPRs('gate.creole.Transducer', prparameter)
# print(response)
# print(gate.loadedPrs)
# testPipeLine = GatePipeline('testpipeline')
# testPipeLine.createPipeline()
# testPipeLine.addPR('gate.creole.annotdelete.AnnotationDeletePR')
# testPipeLine.addPR('gate.creole.tokeniser.DefaultTokeniser')
# testCorpus = GateCorpus('testCorpus')
# testCorpus.addDocument(document)
# testPipeLine.setCorpus(testCorpus)
# testPipeLine.runPipeline()
# #ats = document.getAnnotations('Original markups')
# ats = document.getAnnotations('')
# print(len(ats.annotationSet))
# print(ats.annotationSet[0])
# testPipeline2 = GatePipeline('testpipeline2')
# testPipeLine.loadPipelineFromFile('/Users/xingyi/Gate/ifpri/ifpri.xgapp')
# gate.close()
#
| 22,190 | 34.335987 | 160 |
py
|
CANTM
|
CANTM-main/wvCovidData/GATEpythonInterface/GateInterface/__init__.py
|
from .GateInterface import GateInterFace, AnnotationSet, Annotation, Node, GateDocument, GatePipeline, GateCorpus
| 115 | 37.666667 | 113 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/modelUltiClassTopic.py
|
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import copy
import os
from pathlib import Path
import pickle
import datetime
from .modelUlti import modelUlti
class ModelUltiClass(modelUlti):
def __init__(self, net=None, gpu=False, load_path=None):
super().__init__(net=net, gpu=gpu)
if load_path:
self.loadModel(load_path)
if self.gpu:
self.net.cuda()
def train(self, trainBatchIter, num_epohs=100, valBatchIter=None, cache_path=None, earlyStopping='cls_loss', patience=5):
pytorch_total_params = sum(p.numel() for p in self.net.parameters())
print('total_params: ',pytorch_total_params)
pytorch_train_params = sum(p.numel() for p in self.net.parameters() if p.requires_grad)
print('train_params: ',pytorch_train_params)
self.bowdict = trainBatchIter.dataIter.postProcessor.dictProcess
self.labels = trainBatchIter.dataIter.postProcessor.labelsFields
if earlyStopping == 'None':
earlyStopping = None
self.cache_path = cache_path
output_dict = {}
output_dict['accuracy'] = 'no val iter'
output_dict['perplexity'] = 'no val iter'
output_dict['perplexity_x_only'] = 'no val iter'
self.evaluation_history = []
self.optimizer = optim.Adam(self.net.parameters())
print(num_epohs)
for epoch in range(num_epohs):
begin_time = datetime.datetime.now()
all_loss = []
all_elboz1 = []
all_elboz2 = []
all_bow = []
trainIter = self.pred(trainBatchIter, train=True)
for current_prediction in trainIter:
self.optimizer.zero_grad()
pred = current_prediction['pred']
y = current_prediction['y']
atted = current_prediction['atted']
loss = pred['loss']
cls_loss = pred['cls_loss'].sum()
elbo_z1 = pred['elbo_x'].to('cpu').detach().numpy()
elbo_z2 = pred['elbo_xy'].to('cpu').detach().numpy()
bow_x = current_prediction['x_bow'].to('cpu').detach().numpy()
all_elboz1.append(elbo_z1)
all_elboz2.append(elbo_z2)
all_bow.append(bow_x)
loss.backward()
self.optimizer.step()
loss_value = float(cls_loss.data.item())
all_loss.append(loss_value)
all_elboz1
if epoch % 3 == 0:
topics = self.getTopics(trainBatchIter.dataIter.postProcessor.dictProcess, cache_path=self.cache_path)
#print('===========')
x_only_topic = self.get_x_only_Topics(trainBatchIter.dataIter.postProcessor.dictProcess, cache_path=self.cache_path)
#print('========================')
self.getClassTopics(trainBatchIter.dataIter.postProcessor.dictProcess, cache_path=self.cache_path)
cache_last_path = os.path.join(self.cache_path, 'last_net.model')
self.saveWeights(cache_last_path)
if valBatchIter:
output_dict = self.eval(valBatchIter, get_perp=True)
avg_loss = sum(all_loss)/len(all_loss)
output_dict['cls_loss'] = -avg_loss
perplexity_z1, log_perp_z1 = self._get_prep(all_elboz1, all_bow)
perplexity_z2, log_perp_z2 = self._get_prep(all_elboz2, all_bow)
output_dict['train_ppl_loss'] = -perplexity_z1
if earlyStopping:
stop_signal = self.earlyStop(output_dict, patience=patience, metric=earlyStopping, num_epoch=num_epohs)
if stop_signal:
print('stop signal received, stop training')
cache_load_path = os.path.join(self.cache_path, 'best_net.model')
print('finish training, load model from ', cache_load_path)
self.loadWeights(cache_load_path)
break
end_time = datetime.datetime.now()
timeused = end_time - begin_time
print('epoch ', epoch, 'loss', avg_loss, ' val acc: ', output_dict['accuracy'], 'test_pplz2: ', output_dict['perplexity'], 'test_perpz1: ', output_dict['perplexity_x_only'], 'train_pplz2: ', perplexity_z2, 'train_perpz1: ', perplexity_z1, 'time: ', timeused)
cache_last_path = os.path.join(self.cache_path, 'last_net.model')
self.saveWeights(cache_last_path)
self.saveModel(self.cache_path)
self.getTopics(trainBatchIter.dataIter.postProcessor.dictProcess, cache_path=self.cache_path)
#print('===========')
self.getClassTopics(trainBatchIter.dataIter.postProcessor.dictProcess, cache_path=self.cache_path)
#print('===========')
x_only_topic = self.get_x_only_Topics(trainBatchIter.dataIter.postProcessor.dictProcess, cache_path=self.cache_path)
def getClassTopics(self, dictProcess, ntop=10, cache_path=None):
termMatrix = self.net.get_class_topics()
topicWordList = []
for each_topic in termMatrix:
trans_list = list(enumerate(each_topic.cpu().numpy()))
#print(trans_list)
trans_list = sorted(trans_list, key=lambda k: k[1], reverse=True)
#print(trans_list)
topic_words = [dictProcess.get(item[0]) for item in trans_list[:ntop]]
#print(topic_words)
topicWordList.append(topic_words)
if cache_path:
save_path = os.path.join(cache_path, 'classtopics.txt')
self.saveTopic(topicWordList, save_path)
return topicWordList
def saveModel(self, cache_path):
model_path = os.path.join(cache_path, 'net.model')
dict_path = os.path.join(cache_path, 'dict.pkl')
label_path = os.path.join(cache_path, 'label.pkl')
torch.save(self.net, model_path)
with open(dict_path, 'wb') as fp:
pickle.dump(self.bowdict, fp)
with open(label_path, 'wb') as fp:
pickle.dump(self.labels, fp)
def loadModel(self, cache_path):
model_path = os.path.join(cache_path, 'net.model')
dict_path = os.path.join(cache_path, 'dict.pkl')
label_path = os.path.join(cache_path, 'label.pkl')
self.net = torch.load(model_path, map_location=torch.device("cpu"))
self.net.eval()
with open(dict_path, 'rb') as fp:
self.bowdict = pickle.load(fp)
with open(label_path, 'rb') as fp:
self.labels = pickle.load(fp)
def pred(self, batchGen, train=False, updateTopic=False):
if train or updateTopic:
self.net.train()
#self.optimizer.zero_grad()
else:
self.net.eval()
i=0
pre_embd = False
for x, x_bow, y in batchGen:
i+=1
print("processing batch", i, end='\r')
if self.gpu:
y = y.type(torch.cuda.LongTensor)
x_bow = x_bow.type(torch.cuda.FloatTensor)
x_bow.cuda()
y.cuda()
if batchGen.dataIter.postProcessor.embd_ready:
pre_embd = True
x = x.type(torch.cuda.FloatTensor).squeeze(1)
x.cuda()
else:
x = x.type(torch.cuda.LongTensor)
x.cuda()
if train:
one_hot_y = self.y2onehot(y)
if batchGen.dataIter.label_weights_list:
n_samples = self.get_num_samples(y, batchGen.dataIter.label_weights_list)
else:
n_samples = 10
#print(n_samples)
pred, atted = self.net(x, bow=x_bow, train=True, true_y=one_hot_y, n_samples=n_samples, pre_embd=pre_embd, true_y_ids=y)
elif updateTopic:
pred, atted = self.net(x, bow=x_bow, pre_embd=pre_embd, update_catopic=True)
else:
pred, atted = self.net(x, bow=x_bow, pre_embd=pre_embd)
#pred = pred['y_hat']
output_dict = {}
output_dict['pred'] = pred
output_dict['y'] = y
output_dict['atted'] = atted
output_dict['x_bow'] = x_bow
yield output_dict
def application_oneSent(self, x):
if self.gpu:
x = x.type(torch.cuda.LongTensor)
x.cuda()
pred, atted = self.net(x)
output_dict = {}
output_dict['pred'] = pred
output_dict['atted'] = atted
return output_dict
def get_num_samples(self, y, weight_list):
n_samples = 0
for y_item in y:
n_samples += weight_list[y_item.item()]
return n_samples
def y2onehot(self, y):
num_class = self.net.n_classes
one_hot_y_list = []
for i in range(len(y)):
current_one_hot = [0]*num_class
current_one_hot[y[i].item()] = 1
one_hot_y_list.append(copy.deepcopy(current_one_hot))
tensor_one_hot_y = torch.tensor(one_hot_y_list)
if self.gpu:
tensor_one_hot_y = tensor_one_hot_y.type(torch.cuda.FloatTensor)
tensor_one_hot_y = tensor_one_hot_y.cuda()
return tensor_one_hot_y
def getTopics(self, dictProcess, ntop=10, cache_path=None):
termMatrix = self.net.get_topics()
#print(termMatrix.shape)
topicWordList = []
for each_topic in termMatrix:
trans_list = list(enumerate(each_topic.cpu().numpy()))
#print(trans_list)
trans_list = sorted(trans_list, key=lambda k: k[1], reverse=True)
#print(trans_list)
topic_words = [dictProcess.get(item[0]) for item in trans_list[:ntop]]
#print(topic_words)
topicWordList.append(topic_words)
if cache_path:
save_path = os.path.join(cache_path, 'topics.txt')
self.saveTopic(topicWordList, save_path)
return topicWordList
def get_x_only_Topics(self, dictProcess, ntop=10, cache_path=None):
termMatrix = self.net.get_x_only_topics()
#print(termMatrix.shape)
topicWordList = []
for each_topic in termMatrix:
trans_list = list(enumerate(each_topic.cpu().numpy()))
#print(trans_list)
trans_list = sorted(trans_list, key=lambda k: k[1], reverse=True)
#print(trans_list)
topic_words = [dictProcess.get(item[0]) for item in trans_list[:ntop]]
#print(topic_words)
topicWordList.append(topic_words)
if cache_path:
save_path = os.path.join(cache_path, 'x_only_topics.txt')
self.saveTopic(topicWordList, save_path)
return topicWordList
def saveTopic(self, topics, save_path):
with open(save_path, 'w') as fo:
for each_topic in topics:
topic_line = ' '.join(each_topic)
fo.write(topic_line+'\n')
| 11,148 | 37.711806 | 270 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/PostprocessorBase.py
|
import nltk
from nltk.corpus import stopwords
import os
import re
class ReaderPostProcessorBase:
def __init__(self,
keep_case=False,
label2id=True,
config=None,
word2id=False,
exteralWord2idFunction=None,
return_mask=False,
remove_single_list=True,
max_sent_len = 300,
add_spec_tokens = False,
add_CLS_token = False,
):
self._init_defaults()
self.add_CLS_token = add_CLS_token
self.add_spec_tokens = add_spec_tokens
self.max_sent_len = max_sent_len
self.keep_case = keep_case
self.label2id = label2id
self.word2id = word2id
self.exteralWord2idFunction = exteralWord2idFunction
self.config = config
self.return_mask = return_mask
self.remove_single_list = remove_single_list
def _init_defaults(self):
self.labelsFields = None
self.stop_words = set(stopwords.words('english'))
self.dictProcess = None
self.embd_ready = False
def _remove_stop_words(self, tokened):
remain_list = []
for token in tokened:
contain_symbol, contain_number, contain_char, all_asii = self._check_string(token)
keep = True
if token in self.stop_words:
keep = False
elif len(token) == 1:
keep = False
elif token.isdigit():
keep = False
elif not contain_char:
keep = False
elif not all_asii:
keep = False
elif len(token) > 18:
keep = False
if keep == True:
remain_list.append(token)
else:
pass
#print(token)
return remain_list
def _check_string(self, inputString):
contain_symbol = False
contain_number = False
contain_char = False
all_asii = True
have_symbol = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
have_number = re.compile('\d')
have_char = re.compile('[a-zA-Z]')
ms = have_symbol.search(inputString)
if ms:
contain_symbol = True
mn = have_number.search(inputString)
if mn:
contain_number = True
mc = have_char.search(inputString)
if mc:
contain_char = True
if contain_char and not contain_number and not contain_symbol:
all_asii = all(ord(c) < 128 for c in inputString)
return contain_symbol, contain_number, contain_char, all_asii
def _removeSingleList(self, y):
if len(y) == 1:
return y[0]
else:
return y
def _get_sample(self, sample, sample_field):
current_rawx = sample[sample_field]
if self.keep_case == False:
current_rawx = current_rawx.lower()
return current_rawx
def label2ids(self, label):
label_index = self.labelsFields.index(label)
return label_index
def x_pipeline(self, raw_x, add_special_tokens=True):
raw_x = self.tokenizerProcessor(raw_x)
if self.word2id:
raw_x = self.word2idProcessor(raw_x, add_special_tokens=add_special_tokens)
return raw_x
def nltkTokenizer(self, text):
return nltk.word_tokenize(text)
def bertTokenizer(self, text):
tokened = self.bert_tokenizer.tokenize(text)
#print(tokened)
#ided = self.bert_tokenizer.encode_plus(tokened, max_length=100, pad_to_max_length=True, is_pretokenized=True, add_special_tokens=True)['input_ids']
#print(ided)
return tokened
def bertWord2id(self,tokened, add_special_tokens=True):
encoded = self.bert_tokenizer.encode_plus(tokened, max_length=self.max_sent_len, pad_to_max_length=True, is_pretokenized=True, add_special_tokens=add_special_tokens)
#print(encoded)
ided = encoded['input_ids']
if self.return_mask:
mask = encoded['attention_mask']
return ided, mask
else:
return ided
def get_label_desc_ids(self):
label_desc_list = []
for label in self.labelsFields:
label_desc = self.desctiptionDict[label]
current_desc_ids = self.x_pipeline(label_desc, max_length=100)
label_desc_list.append(current_desc_ids)
label_ids = [s[0] for s in label_desc_list]
label_mask_ids = [s[1] for s in label_desc_list]
return label_ids, label_mask_ids
| 4,597 | 29.25 | 173 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/modelUltiUpdateCATopic.py
|
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import copy
import os
from pathlib import Path
import pickle
from .modelUltiClassTopic import ModelUltiClass
class ModelUltiUpdateCAtopic(ModelUltiClass):
def __init__(self, net=None, gpu=False, load_path=None):
super().__init__(net=net, gpu=gpu, load_path=load_path)
def train(self, trainBatchIter, num_epohs=100, valBatchIter=None, cache_path=None, earlyStopping='cls_loss', patience=5):
self.bowdict = trainBatchIter.dataIter.postProcessor.dictProcess
self.labels = trainBatchIter.dataIter.postProcessor.labelsFields
if earlyStopping == 'None':
earlyStopping = None
self.cache_path = cache_path
output_dict = {}
output_dict['accuracy'] = 'no val iter'
output_dict['perplexity'] = 'no val iter'
output_dict['perplexity_x_only'] = 'no val iter'
self.evaluation_history = []
self.optimizer = optim.Adam(self.net.parameters())
print(num_epohs)
for epoch in range(num_epohs):
all_loss = []
all_elboz1 = []
all_elboz2 = []
all_bow = []
trainIter = self.pred(trainBatchIter, train=False, updateTopic=True)
for current_prediction in trainIter:
self.optimizer.zero_grad()
pred = current_prediction['pred']
atted = current_prediction['atted']
loss = pred['loss']
bow_x = current_prediction['x_bow'].to('cpu').detach().numpy()
all_bow.append(bow_x)
loss.backward()
self.optimizer.step()
topics = self.getTopics(trainBatchIter.dataIter.postProcessor.dictProcess, cache_path=self.cache_path)
topics = self.getTopics(trainBatchIter.dataIter.postProcessor.dictProcess, cache_path=self.cache_path)
cache_last_path = os.path.join(self.cache_path, 'last_net.model')
self.saveWeights(cache_last_path)
print('finish epoch ', epoch)
cache_last_path = os.path.join(self.cache_path, 'last_net.model')
self.saveWeights(cache_last_path)
self.saveModel(self.cache_path)
self.getTopics(trainBatchIter.dataIter.postProcessor.dictProcess, cache_path=self.cache_path)
| 2,399 | 31 | 125 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/batchPostProcessors.py
|
import torch
def xonlyBatchProcessor(x, y):
ss = [s[1] for s in x]
return ss[0]
def bowBertBatchProcessor(raw_x, y):
x = [s[0] for s in raw_x]
idded_words = [s[1] for s in raw_x]
y_class = y
return torch.tensor(x), torch.tensor(idded_words), torch.tensor(y_class)
def xyOnlyBertBatchProcessor(raw_x, y):
x = [s[0] for s in raw_x]
y_class = y
return torch.tensor(x), torch.tensor(y_class)
def singleProcessor_noy(raw_x):
x = [raw_x[0]]
return torch.tensor(x)
| 508 | 21.130435 | 76 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/modelUltiVAEtm_noatt.py
|
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import copy
import os
from pathlib import Path
from .modelUlti import modelUlti
class ModelUltiVAEtmNOatt(modelUlti):
def __init__(self, net=None, gpu=False):
super().__init__(net=net, gpu=gpu)
def train(self, trainBatchIter, num_epohs=100, valBatchIter=None, cache_path=None, earlyStopping='cls_loss', patience=5):
self.cache_path = cache_path
output_dict = {}
output_dict['accuracy'] = 'no val iter'
self.evaluation_history = []
classifier_paramters = list(self.net.wv_hidden.parameters()) + list(self.net.wv_classifier.parameters())
topic_model_paramters = list(self.net.mu.parameters())+ list(self.net.log_sigma.parameters()) + list(self.net.topics.parameters())
self.optimizer_classifier = optim.Adam(classifier_paramters)
self.optimizer_topic_modelling = optim.Adam(topic_model_paramters)
#self.optimizer = optim.Adam(self.net.parameters())
self.criterion = nn.CrossEntropyLoss()
if self.gpu:
self.criterion.cuda()
for epoch in range(num_epohs):
all_loss = []
trainIter = self.pred(trainBatchIter, train=True)
for current_prediction in trainIter:
#self.optimizer.zero_grad()
self.optimizer_classifier.zero_grad()
self.optimizer_topic_modelling.zero_grad()
pred = current_prediction['pred']
y = current_prediction['y']
atted = current_prediction['atted']
#y_desc_representation = current_prediction['y_desc_representation']
#class_loss = self.criterion(pred['pred'], y)
#topic_loss = pred['loss']
#print(class_loss)
#desc_loss = self.desc_criterion(input=atted, target=y_desc_representation)
loss = pred['loss']
cls_loss = pred['cls_loss'].sum()
loss.backward()
#self.optimizer.step()
self.optimizer_classifier.step()
self.optimizer_topic_modelling.step()
#loss_value = float(loss.data.item())
loss_value = float(cls_loss.data.item())
all_loss.append(loss_value)
if epoch % 20 == 0:
self.getTopics(trainBatchIter.dataIter.postProcessor.dictProcess)
cache_last_path = os.path.join(self.cache_path, 'last_net.model')
self.saveWeights(cache_last_path)
print("Finish Epoch ", epoch)
if valBatchIter:
output_dict = self.eval(valBatchIter)
avg_loss = sum(all_loss)/len(all_loss)
output_dict['cls_loss'] = -avg_loss
if earlyStopping:
stop_signal = self.earlyStop(output_dict, patience=patience, metric=earlyStopping, num_epoch=num_epohs)
if stop_signal:
print('stop signal received, stop training')
cache_load_path = os.path.join(self.cache_path, 'best_net.model')
print('finish training, load model from ', cache_load_path)
self.loadWeights(cache_load_path)
break
print('epoch ', epoch, 'loss', avg_loss, ' val acc: ', output_dict['accuracy'])
cache_last_path = os.path.join(self.cache_path, 'last_net.model')
self.saveWeights(cache_last_path)
#cache_load_path = os.path.join(self.cache_path, 'best_net.model')
#print('finish training, load model from ', cache_load_path)
#self.loadWeights(cache_load_path)
def pred(self, batchGen, train=False):
if train:
self.net.train()
#self.optimizer.zero_grad()
else:
self.net.eval()
i=0
pre_embd = False
for x, x_bow, y in batchGen:
i+=1
print("processing batch", i, end='\r')
if self.gpu:
y = y.type(torch.cuda.LongTensor)
x_bow = x_bow.type(torch.cuda.FloatTensor)
x_bow.cuda()
y.cuda()
if batchGen.dataIter.postProcessor.embd_ready:
pre_embd = True
x = x.type(torch.cuda.FloatTensor).squeeze(1)
x.cuda()
else:
x = x.type(torch.cuda.LongTensor)
x.cuda()
if train:
one_hot_y = self.y2onehot(y)
if batchGen.dataIter.label_weights_list:
n_samples = self.get_num_samples(y, batchGen.dataIter.label_weights_list)
else:
n_samples = 10
#print(n_samples)
pred, atted = self.net(x, bow=x_bow, train=True, true_y=one_hot_y, n_samples=n_samples, pre_embd=pre_embd, true_y_ids=y)
else:
pred, atted = self.net(x, bow=x_bow, pre_embd=pre_embd)
output_dict = {}
output_dict['pred'] = pred
output_dict['y'] = y
output_dict['atted'] = atted
yield output_dict
def application_oneSent(self, x):
if self.gpu:
x = x.type(torch.cuda.LongTensor)
x.cuda()
pred, atted = self.net(x)
output_dict = {}
output_dict['pred'] = pred
output_dict['atted'] = atted
return output_dict
def get_num_samples(self, y, weight_list):
n_samples = 0
for y_item in y:
n_samples += weight_list[y_item.item()]
return n_samples
def y2onehot(self, y):
num_class = self.net.n_classes
one_hot_y_list = []
for i in range(len(y)):
current_one_hot = [0]*num_class
current_one_hot[y[i].item()] = 1
one_hot_y_list.append(copy.deepcopy(current_one_hot))
tensor_one_hot_y = torch.tensor(one_hot_y_list)
if self.gpu:
tensor_one_hot_y = tensor_one_hot_y.type(torch.cuda.FloatTensor)
tensor_one_hot_y = tensor_one_hot_y.cuda()
return tensor_one_hot_y
def getTopics(self, dictProcess, ntop=10):
termMatrix = self.net.get_topics()
#print(termMatrix.shape)
topicWordList = []
for each_topic in termMatrix:
trans_list = list(enumerate(each_topic.cpu().numpy()))
#print(trans_list)
trans_list = sorted(trans_list, key=lambda k: k[1], reverse=True)
#print(trans_list)
topic_words = [dictProcess.get(item[0]) for item in trans_list[:ntop]]
#print(topic_words)
topicWordList.append(topic_words)
return topicWordList
| 6,838 | 38.304598 | 138 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/ScholarPostProcessor.py
|
import nltk
from nltk.corpus import stopwords
import os
import re
from .WVPostProcessor import WVPostProcessor
from transformers import BertTokenizer
import glob
import string
from collections import Counter
from nltk.tokenize import sent_tokenize
punct_chars = list(set(string.punctuation) - set("'"))
punct_chars.sort()
punctuation = ''.join(punct_chars)
replace = re.compile('[%s]' % re.escape(punctuation))
punct_chars_more = list(set(string.punctuation) - set(["'",","]))
punct_chars_more.sort()
punctuation_more = ''.join(punct_chars_more)
replace_more = re.compile('[%s]' % re.escape(punctuation_more))
alpha = re.compile('^[a-zA-Z_]+$')
alpha_or_num = re.compile('^[a-zA-Z_]+|[0-9_]+$')
alphanum = re.compile('^[a-zA-Z0-9_]+$')
def tokenize(text, strip_html=False, lower=True, keep_emails=False, keep_at_mentions=False, keep_numbers=False, keep_alphanum=False, min_length=3, stopwords=None, vocab=None, keep_pun=False):
text = clean_text(text, strip_html, lower, keep_emails, keep_at_mentions, keep_pun=keep_pun)
tokens = text.split()
if stopwords is not None:
tokens = ['_' if t in stopwords else t for t in tokens]
# remove tokens that contain numbers
if not keep_alphanum and not keep_numbers:
tokens = [t if alpha.match(t) else '_' for t in tokens]
# or just remove tokens that contain a combination of letters and numbers
elif not keep_alphanum:
tokens = [t if alpha_or_num.match(t) else '_' for t in tokens]
# drop short tokens
if min_length > 0:
tokens = [t if len(t) >= min_length else '_' for t in tokens]
counts = Counter()
unigrams = [t for t in tokens if t != '_']
counts.update(unigrams)
if vocab is not None:
tokens = [token for token in unigrams if token in vocab]
else:
tokens = unigrams
return tokens, counts
def clean_text(text, strip_html=False, lower=True, keep_emails=False, keep_at_mentions=False, keep_pun=False):
# remove html tags
if strip_html:
text = re.sub(r'<[^>]+>', '', text)
else:
# replace angle brackets
text = re.sub(r'<', '(', text)
text = re.sub(r'>', ')', text)
# lower case
if lower:
text = text.lower()
# eliminate email addresses
if not keep_emails:
text = re.sub(r'\S+@\S+', ' ', text)
# eliminate @mentions
if not keep_at_mentions:
text = re.sub(r'\s@\S+', ' ', text)
# replace underscores with spaces
text = re.sub(r'_', ' ', text)
# break off single quotes at the ends of words
text = re.sub(r'\s\'', ' ', text)
text = re.sub(r'\'\s', ' ', text)
if not keep_pun:
# remove periods
text = re.sub(r'\.', '', text)
# replace all other punctuation (except single quotes) with spaces
text = replace.sub(' ', text)
else:
# remove periods
text = re.sub(r'\.', '', text)
# replace all other punctuation (except single quotes) with spaces
text = replace_more.sub(' ', text)
# remove single quotes
text = re.sub(r'\'', '', text)
# replace all whitespace with a single space
text = re.sub(r'\s', ' ', text)
# strip off spaces on either end
text = text.strip()
return text
class ScholarPostProcessor(WVPostProcessor):
def __init__(self, stopwords_source=['snowball'], min_token_length=3, **kwargs):
super().__init__(**kwargs)
script_path = os.path.abspath(__file__)
parent = os.path.dirname(script_path)
self.stopwords_source = stopwords_source
self.min_token_length = min_token_length
stop_list_dir = os.path.join(parent, 'stopwords')
self._get_stop_words(stop_list_dir)
print(self.stop_words)
def _get_stop_words(self, stop_list_dir):
self.stop_words = set()
snowball_stopwords_list_file = os.path.join(stop_list_dir, 'snowball_stopwords.txt')
mallet_stopwords_list_file = os.path.join(stop_list_dir, 'mallet_stopwords.txt')
scholar_stopwords_list_file = os.path.join(stop_list_dir, 'custom_stopwords.txt')
if 'snowball' in self.stopwords_source:
with open(snowball_stopwords_list_file, 'r') as fin:
for line in fin:
stop_word = line.strip()
self.stop_words.add(stop_word)
def clean_source(self, source_text):
#split_lines = source_text.split('\n | _')
split_lines = re.split('\n|_|=|\*|\||\/', source_text)
added_sent = []
for splited_line in split_lines:
all_sents_split = sent_tokenize(splited_line)
for each_sent in all_sents_split:
keep = True
line_tok, _= tokenize(splited_line, stopwords=self.stop_words)
if len(line_tok) < 3:
keep=False
if keep:
added_sent.append(splited_line)
return ' '.join(added_sent)
def postProcess(self, sample):
split_x = []
for x_field in self.x_fields:
current_rawx = self._get_sample(sample, x_field)
split_x.append(current_rawx)
current_rawx = ' '.join(split_x)
current_rawx_tokened, _ = tokenize(current_rawx, keep_numbers=True, keep_alphanum=True, min_length=1, keep_pun=True)
current_rawx = ' '.join(current_rawx_tokened)
#print(current_rawx)
## Bert toknise for hidden layers. add_special_tokens not added, additional attention will be applied on token level (CLS not used)
if self.embd_ready:
current_x = sample['embd']
else:
#cleaned_raw_x = self.clean_source(current_rawx)
#print(cleaned_raw_x)
cleaned_raw_x = current_rawx
if len(cleaned_raw_x) > 10:
current_x = self.x_pipeline(cleaned_raw_x, add_special_tokens=self.add_spec_tokens)
else:
current_x = self.x_pipeline(current_rawx, add_special_tokens=self.add_spec_tokens)
## NLTK tokenise and remove stopwords for topic modelling
#current_x_nltk_tokened = self.nltkTokenizer(current_rawx)
#current_x_nltk_tokened = self._remove_stop_words(current_x_nltk_tokened)
current_x_nltk_tokened,_ = tokenize(current_rawx, stopwords=self.stop_words)
if self.dictProcess:
current_x_nltk_tokened = self.dictProcess.doc2countHot(current_x_nltk_tokened)
x=[current_x, current_x_nltk_tokened]
y = sample[self.y_field]
if self.label2id:
y = self.label2ids(y)
if self.remove_single_list:
x = self._removeSingleList(x)
y = self._removeSingleList(y)
return x, y
def _remove_stop_words(self, tokened):
remain_list = []
for token in tokened:
contain_symbol, contain_number, contain_char, all_asii = self._check_string(token)
keep = True
if token in self.stop_words:
keep = False
elif len(token) < self.min_token_length:
keep = False
elif token.isdigit():
keep = False
elif not contain_char:
keep = False
elif not all_asii:
keep = False
elif contain_number:
keep = False
if keep == True:
remain_list.append(token)
else:
pass
#print(token)
return remain_list
| 7,529 | 34.023256 | 191 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/BatchIter.py
|
import math
import random
class BatchIterBert:
def __init__(self, dataIter, batch_size=32, filling_last_batch=False, postProcessor=None):
self.dataIter = dataIter
self.batch_size = batch_size
self.num_batches = self._get_num_batches()
self.filling_last_batch = filling_last_batch
self.postProcessor = postProcessor
self.fillter = []
self._reset_iter()
def _get_num_batches(self):
num_batches = math.ceil(len(self.dataIter)/self.batch_size)
return num_batches
def _reset_iter(self):
self.current_batch_idx = 0
def __iter__(self):
self._reset_iter()
return self
def __next__(self):
if self.current_batch_idx < self.num_batches:
current_batch_x, current_batch_y = self._readNextBatch()
self.current_batch_idx += 1
if self.postProcessor:
return self.postProcessor(current_batch_x, current_batch_y)
else:
return current_batch_x, current_batch_y
else:
self._reset_iter()
raise StopIteration
def __len__(self):
return self.num_batches
def _readNextBatch(self):
i = 0
batch_list_x = []
batch_list_y = []
while i < self.batch_size:
try:
x, y = next(self.dataIter)
if self.filling_last_batch:
self._update_fillter(x, y)
batch_list_x.append(x)
batch_list_y.append(y)
i+=1
except StopIteration:
if self.filling_last_batch:
batch_list_x, batch_list_y = self._filling_last_batch(batch_list_x, batch_list_y)
i = self.batch_size
return batch_list_x, batch_list_y
def _filling_last_batch(self, batch_list_x, batch_list_y):
num_current_batch = len(batch_list_x)
num_filling = self.batch_size - num_current_batch
random.shuffle(self.fillter)
filler_x = [s[0] for s in self.fillter[:num_filling]]
filler_y = [s[1] for s in self.fillter[:num_filling]]
batch_list_x += filler_x
batch_list_y += filler_y
return batch_list_x, batch_list_y
def _update_fillter(self, x, y):
r = random.random()
if len(self.fillter) < self.batch_size:
self.fillter.append([x, y])
elif r>0.9:
self.fillter.pop(0)
self.fillter.append([x, y])
| 2,508 | 31.166667 | 101 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/DictionaryProcess.py
|
class DictionaryProcess:
def __init__(self, common_dictionary):
self.common_dictionary = common_dictionary
self.num_vocab = len(self.common_dictionary)
def doc2bow(self, input_doc):
gensim_bow_doc = self.common_dictionary.doc2bow(input_doc)
return gensim_bow_doc
def doc2countHot(self, input_doc):
gensim_bow_doc = self.doc2bow(input_doc)
doc_vec = [0] * self.num_vocab
for item in gensim_bow_doc:
vocab_idx = item[0]
vovab_counts = item[1]
doc_vec[vocab_idx] = vovab_counts
return doc_vec
def get(self, wordidx):
return self.common_dictionary[wordidx]
def __len__(self):
return self.num_vocab
| 734 | 29.625 | 66 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/ScholarProcessor.py
|
import nltk
from nltk.corpus import stopwords
import os
import re
from .PostprocessorBase import ReaderPostProcessorBase
from transformers import BertTokenizer
def tokenize(text, strip_html=False, lower=True, keep_emails=False, keep_at_mentions=False, keep_numbers=False, keep_alphanum=False, min_length=3, stopwords=None, vocab=None):
text = clean_text(text, strip_html, lower, keep_emails, keep_at_mentions)
tokens = text.split()
if stopwords is not None:
tokens = ['_' if t in stopwords else t for t in tokens]
# remove tokens that contain numbers
if not keep_alphanum and not keep_numbers:
tokens = [t if alpha.match(t) else '_' for t in tokens]
# or just remove tokens that contain a combination of letters and numbers
elif not keep_alphanum:
tokens = [t if alpha_or_num.match(t) else '_' for t in tokens]
# drop short tokens
if min_length > 0:
tokens = [t if len(t) >= min_length else '_' for t in tokens]
counts = Counter()
unigrams = [t for t in tokens if t != '_']
counts.update(unigrams)
if vocab is not None:
tokens = [token for token in unigrams if token in vocab]
else:
tokens = unigrams
return tokens, counts
def clean_text(text, strip_html=False, lower=True, keep_emails=False, keep_at_mentions=False):
# remove html tags
if strip_html:
text = re.sub(r'<[^>]+>', '', text)
else:
# replace angle brackets
text = re.sub(r'<', '(', text)
text = re.sub(r'>', ')', text)
# lower case
if lower:
text = text.lower()
# eliminate email addresses
if not keep_emails:
text = re.sub(r'\S+@\S+', ' ', text)
# eliminate @mentions
if not keep_at_mentions:
text = re.sub(r'\s@\S+', ' ', text)
# replace underscores with spaces
text = re.sub(r'_', ' ', text)
# break off single quotes at the ends of words
text = re.sub(r'\s\'', ' ', text)
text = re.sub(r'\'\s', ' ', text)
# remove periods
text = re.sub(r'\.', '', text)
# replace all other punctuation (except single quotes) with spaces
text = replace.sub(' ', text)
# remove single quotes
text = re.sub(r'\'', '', text)
# replace all whitespace with a single space
text = re.sub(r'\s', ' ', text)
# strip off spaces on either end
text = text.strip()
return text
class ScholarProcessor(ReaderPostProcessorBase):
def __init__(self, x_fields=['Claim', 'Explaination'], y_field='selected_label', **kwargs):
super().__init__(**kwargs)
self.x_fields = x_fields
self.y_field = y_field
self.initProcessor()
def initProcessor(self):
bert_tokenizer_path = os.path.join(self.config['BERT'].get('bert_path'), 'tokenizer')
self.bert_tokenizer = BertTokenizer.from_pretrained(bert_tokenizer_path)
self.tokenizerProcessor = self.bertTokenizer
self.word2idProcessor = self.bertWord2id
if 'TARGET' in self.config:
self.labelsFields = self.config['TARGET'].get('labels')
else:
self.labelsFields = ['PubAuthAction', 'CommSpread', 'GenMedAdv', 'PromActs', 'Consp', 'VirTrans', 'VirOrgn', 'PubPrep', 'Vacc', 'Prot', 'None']
#print(self.labelsFields)
def postProcess(self, sample):
split_x = []
for x_field in self.x_fields:
current_rawx = self._get_sample(sample, x_field)
split_x.append(current_rawx)
current_rawx = ' '.join(split_x)
## Bert toknise for hidden layers. add_special_tokens not added, additional attention will be applied on token level (CLS not used)
if self.embd_ready:
current_x = sample['embd']
else:
current_x = self.x_pipeline(current_rawx, add_special_tokens=self.add_spec_tokens)
## NLTK tokenise and remove stopwords for topic modelling
#current_x_nltk_tokened = self.nltkTokenizer(current_rawx)
#current_x_nltk_tokened = self._remove_stop_words(current_x_nltk_tokened)
current_x_nltk_tokened = tokenize(current_rawx)
if self.dictProcess:
current_x_nltk_tokened = self.dictProcess.doc2countHot(current_x_nltk_tokened)
x=[current_x, current_x_nltk_tokened]
y = sample[self.y_field]
if self.label2id:
y = self.label2ids(y)
if self.remove_single_list:
x = self._removeSingleList(x)
y = self._removeSingleList(y)
return x, y
| 4,509 | 35.370968 | 175 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/__init__.py
|
from .BatchIter import BatchIterBert
from .DictionaryProcess import DictionaryProcess
from .WVPostProcessor import WVPostProcessor
from .ScholarPostProcessor import ScholarPostProcessor
from .modelUltiClassTopic import ModelUltiClass
from .modelUlti import modelUlti as ModelUlti
from .EvaluationManager import EvaluationManager
from .modelUltiUpdateCATopic import ModelUltiUpdateCAtopic
| 388 | 42.222222 | 58 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/modelUlti.py
|
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import os
from pathlib import Path
class modelUlti:
def __init__(self, net=None, gpu=False):
if net:
self.net = net
self.gpu = gpu
if self.gpu and net:
self.net.cuda()
def train(self, trainBatchIter, num_epohs=100, valBatchIter=None, cache_path=None, patience=15, earlyStopping='cls_loss'):
self.cache_path = cache_path
output_dict = {}
output_dict['accuracy'] = 'no val iter'
self.evaluation_history = []
self.optimizer = optim.Adam(self.net.parameters())
self.criterion = nn.CrossEntropyLoss()
if self.gpu:
self.criterion.cuda()
for epoch in range(num_epohs):
all_loss = []
trainIter = self.pred(trainBatchIter, train=True)
for current_prediction in trainIter:
pred = current_prediction['pred']['y_hat']
y = current_prediction['y']
self.optimizer.zero_grad()
loss = self.criterion(pred, y)
loss.backward()
self.optimizer.step()
loss_value = float(loss.data.item())
all_loss.append(loss_value)
print("Finish batch")
if valBatchIter:
output_dict = self.eval(valBatchIter)
avg_loss = sum(all_loss)/len(all_loss)
output_dict['cls_loss'] = -avg_loss
if earlyStopping:
stop_signal = self.earlyStop(output_dict, num_epoch=num_epohs, patience=patience, metric=earlyStopping)
if stop_signal:
print('stop signal received, stop training')
cache_load_path = os.path.join(self.cache_path, 'best_net.model')
print('finish training, load model from ', cache_load_path)
self.loadWeights(cache_load_path)
break
print('epoch ', epoch, 'loss', avg_loss, ' val acc: ', output_dict['accuracy'])
if epoch % 20 == 0:
cache_last_path = os.path.join(self.cache_path, 'last_net.model')
self.saveWeights(cache_last_path)
cache_last_path = os.path.join(self.cache_path, 'last_net.model')
self.saveWeights(cache_last_path)
def earlyStop(self, output_dict, metric='accuracy', patience=40, num_epoch=None):
result = output_dict[metric]
stop_signal = False
self.evaluation_history.append(result)
num_epochs = len(self.evaluation_history)
max_result = max(self.evaluation_history)
max_epoch = self.evaluation_history.index(max_result)
max_passed = num_epochs - max_epoch
if max_passed >= patience:
stop_signal = True
if num_epoch:
#print('num epoch passed: ', len(self.evaluation_history))
#print('max_epoches:', num_epoch)
if len(self.evaluation_history) == num_epoch:
stop_signal = True
if max_passed == 1:
print('caching best ')
cache_path = os.path.join(self.cache_path, 'best_net.model')
self.saveWeights(cache_path)
return stop_signal
def pred(self, batchGen, train=False):
pre_embd = False
if train:
self.net.train()
else:
self.net.eval()
i=0
for x, y in batchGen:
i+=1
print("processing batch", i, end='\r')
if self.gpu:
y = y.type(torch.cuda.LongTensor)
y.cuda()
if batchGen.dataIter.postProcessor.embd_ready:
pre_embd = True
x = x.type(torch.cuda.FloatTensor).squeeze(1)
x.cuda()
else:
x = x.type(torch.cuda.LongTensor)
x.cuda()
pred = self.net(x, pre_embd=pre_embd)
output_dict = {}
output_dict['pred'] = pred
output_dict['y'] = y
yield output_dict
def eval(self, batchGen, get_perp=False):
output_dict = {}
all_prediction = []
all_true_label = []
all_elbo_x = []
all_elbo_xy = []
all_bow_x = []
#print(len(batchGen))
#print(len(batchGen.dataIter))
for current_prediction in self.pred(batchGen):
pred = current_prediction['pred']['y_hat']
y = current_prediction['y']
current_batch_out = F.softmax(pred, dim=-1)
label_prediction = torch.max(current_batch_out, -1)[1]
current_batch_out_list = current_batch_out.to('cpu').detach().numpy()
label_prediction_list = label_prediction.to('cpu').detach().numpy()
y_list = y.to('cpu').detach().numpy()
all_prediction.append(label_prediction_list)
all_true_label.append(y_list)
if get_perp:
elbo_x = current_prediction['pred']['elbo_x'].to('cpu').detach().numpy()
elbo_xy = current_prediction['pred']['elbo_xy'].to('cpu').detach().numpy()
bow_x = current_prediction['x_bow'].to('cpu').detach().numpy()
#print(elbo_xy)
all_elbo_x.append(elbo_x)
all_elbo_xy.append(elbo_xy)
all_bow_x.append(bow_x)
if get_perp:
perplexity, log_perp = self._get_prep(all_elbo_xy, all_bow_x)
output_dict['perplexity'] = perplexity
output_dict['log_perplexity'] = log_perp
perplexity_x_only, log_perp_x_only = self._get_prep(all_elbo_x, all_bow_x)
output_dict['perplexity_x_only'] = perplexity_x_only
output_dict['log_perplexity_x_only'] = log_perp_x_only
all_prediction = np.concatenate(all_prediction)
all_true_label = np.concatenate(all_true_label)
#print(len(all_true_label))
num_correct = (all_prediction == all_true_label).sum()
accuracy = num_correct / len(all_prediction)
output_dict['accuracy'] = accuracy
output_dict['f-measure'] = {}
num_classes = len(batchGen.dataIter.postProcessor.labelsFields)
for class_id in list(range(num_classes)):
f_measure_score = self.fMeasure(all_prediction, all_true_label, class_id)
output_dict['f-measure']['class '+str(class_id)] = f_measure_score
return output_dict
def _get_prep(self, all_elbo_list, all_bow_list):
all_elbo = np.concatenate(all_elbo_list)
all_bow = np.concatenate(all_bow_list)
###############################################
##num_token = all_bow.sum(axis=1)
##print(num_token)
##print(num_token.shape)
#log_perp = np.mean(all_elbo / all_bow.sum(axis=1))
#print(log_perp)
#############################################
num_token = all_bow.sum()
log_perp = all_elbo.sum() / num_token
#############################################
#print(log_perp)
perplexity = np.exp(log_perp)
#print(perplexity)
return perplexity, log_perp
def saveWeights(self, save_path):
torch.save(self.net.state_dict(), save_path)
def loadWeights(self, load_path, cpu=True):
if cpu:
self.net.load_state_dict(torch.load(load_path, map_location=torch.device('cpu')), strict=False)
else:
self.net.load_state_dict(torch.load(load_path), strict=False)
self.net.eval()
def fMeasure(self, all_prediction, true_label, class_id, ignoreid=None):
#print(class_id)
mask = [class_id] * len(all_prediction)
mask_arrary = np.array(mask)
pred_mask = np.argwhere(all_prediction==class_id)
#print(pred_mask)
true_mask = np.argwhere(true_label==class_id)
#print(true_mask)
#print(len(true_mask))
total_pred = 0
total_true = 0
pc = 0
for i in pred_mask:
if all_prediction[i[0]] == true_label[i[0]]:
pc+=1
if true_label[i[0]] != ignoreid:
total_pred += 1
rc = 0
for i in true_mask:
if all_prediction[i[0]] == true_label[i[0]]:
rc+=1
if true_label[i[0]] != ignoreid:
total_true += 1
if total_pred == 0:
precision = 0
else:
precision = float(pc)/total_pred
if total_true == 0:
recall = 0
else:
recall = float(rc)/total_true
if (precision+recall)==0:
f_measure = 0
else:
f_measure = 2*((precision*recall)/(precision+recall))
#print(total_true)
return precision, recall, f_measure, total_pred, total_true, pc, rc
| 8,968 | 35.02008 | 126 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/EvaluationManager.py
|
import sys
import nltk
import math
from GateMIcateLib import BatchIterBert, DictionaryProcess
#from GateMIcateLib import WVPostProcessor as ReaderPostProcessor
from configobj import ConfigObj
import torch
import argparse
import copy
from sklearn.model_selection import KFold
import random
import os
from pathlib import Path
from gensim.corpora.dictionary import Dictionary
from gensim.models import LdaModel
import numpy as np
def get_average_fmeasure_score(results_dict, field):
t=0
score = 0
for class_field in results_dict['f-measure']:
score += sum(results_dict['f-measure'][class_field][field])
t += len(results_dict['f-measure'][class_field][field])
return score/t
def get_micro_fmeasure(results_dict, num_field, de_field):
score = 0
for class_field in results_dict['f-measure']:
numerator = sum(results_dict['f-measure'][class_field][num_field])
denominator = sum(results_dict['f-measure'][class_field][de_field])
if denominator != 0:
score += numerator/denominator
t = len(results_dict['f-measure'])
return score/t
class EvaluationManager:
def __init__(self, trainReaderargs, envargs, testReaderargs=None, valReaderargs=None):
self._initParams(envargs)
self.trainReaderargs = trainReaderargs
self.testReaderargs = testReaderargs
self.valReaderargs = valReaderargs
self.getLibs()
self._get_train_DataIter()
def get_covid_train_json_for_scholar(self):
current_traindataIter=dataIter(*self.trainReaderargs, config=self.config, shuffle=False)
all_json = []
for item in current_traindataIter:
claim = item['Claim']
explaination = item['Explaination']
label = item['selected_label']
sample_id = item['unique_wv_id']
text = claim+' '+explaination
current_dict = {}
current_dict['text'] = text
current_dict['sentiment'] = label
current_dict['id'] = sample_id
all_json.append(current_dict)
return all_json
def outputCorpus4NPMI(self):
all_doc = []
token_count = []
current_traindataIter=dataIter(*self.trainReaderargs, config=self.config, shuffle=False)
for item in current_traindataIter:
alltext=[]
for field in self.x_fields:
current_text = nltk.word_tokenize(item[field])
token_count.append(len(current_text))
alltext.append(' '.join(current_text))
all_doc.append(' '.join(alltext))
if self.testReaderargs:
self.testDataIter = dataIter(*self.testReaderargs, config=self.config, shuffle=False)
for item in current_traindataIter:
alltext=[]
for field in self.x_fields:
current_text = nltk.word_tokenize(item[field])
token_count.append(len(current_text))
alltext.append(' '.join(current_text))
all_doc.append(' '.join(alltext))
print(sum(token_count)/len(token_count))
return all_doc
def _get_train_DataIter(self):
self.postProcessor = ReaderPostProcessor(config=self.config, word2id=True, remove_single_list=False, add_spec_tokens=True, x_fields=self.x_fields, y_field=self.y_field, max_sent_len=self.max_sent_len)
print(*self.trainReaderargs)
self.trainDataIter = dataIter(*self.trainReaderargs, postProcessor=self.postProcessor, config=self.config, shuffle=True)
if self.testReaderargs:
self.testDataIter = dataIter(*self.testReaderargs, postProcessor=self.postProcessor, config=self.config, shuffle=False)
print(self.get_dict)
if self.get_dict:
print('building dict')
self.buildDict()
if self.preEmbd:
print('pre calculating embedding')
net = Model(self.config, vocab_dim=self.vocab_dim)
mUlti = modelUlti(net, gpu=self.gpu)
self.trainDataIter.preCalculateEmbed(mUlti.net.bert_embedding, 0)
if not self.testReaderargs:
self.all_ids = copy.deepcopy(self.trainDataIter.all_ids)
random.shuffle(self.all_ids)
## deep copy train reader to test reader
self.testDataIter = copy.deepcopy(self.trainDataIter)
self.valDataIter = None
def _initParams(self,envargs):
print(envargs)
self.get_perp = False
self.get_dict = False
self.vocab_dim = None
self.have_dict = False
self.config_file = envargs.get('configFile',None)
self.config = ConfigObj(self.config_file)
self.cache_path = envargs.get('cachePath',None)
self.n_fold = envargs.get('nFold',5)
self.randomSeed = envargs.get('randomSeed',None)
self.preEmbd = envargs.get('preEmbd',False)
self.dynamicSampling = envargs.get('dynamicSampling',False)
self.modelType = envargs.get('model', 'clsTopic')
self.corpusType = envargs.get('corpusType', 'wvmisinfo')
self.max_sent_len = envargs.get('max_sent_len', '300')
self.num_epoches = envargs.get('num_epoches', 150)
self.patient = envargs.get('patient', 40)
self.batch_size = envargs.get('batch_size', 32)
self.earlyStopping = envargs.get('earlyStopping', 'cls_loss')
self.x_fields = envargs.get('x_fields', 'Claim,Explaination')
self.x_fields = self.x_fields.split(',')
print(self.x_fields)
self.y_field = envargs.get('y_field', 'selected_label')
self.dict_no_below = envargs.get('dict_no_below', 0)
self.dict_no_above = envargs.get('dict_no_above', 1.0)
self.dict_keep_n = envargs.get('dict_keep_n', 5000)
self.splitValidation = envargs.get('splitValidation',None)
self.inspectTest = envargs.get('inspectTest', True)
self.trainLDA = envargs.get('trainLDA', False)
self.gpu = envargs.get('gpu', True)
self.envargs = envargs
def train_lda(self, cache_path):
print(cache_path)
trainBatchIter = BatchIterBert(self.trainDataIter, filling_last_batch=False, postProcessor=batchPostProcessor, batch_size=1)
bow_list = []
for item in trainBatchIter:
bow = item[1].squeeze().detach().numpy().tolist()
bow_list.append(self.bow_2_gensim(bow))
print(len(bow_list))
#print(self.dictProcess.common_dictionary.id2token)
lda = LdaModel(np.array(bow_list), num_topics=50, passes=200, chunksize=len(bow_list), id2word=self.dictProcess.common_dictionary)
#print(lda.show_topic(1, topn=10))
output_topic_line = ''
for topic_id in range(50):
current_topic_list = []
current_topic = lda.show_topic(topic_id, topn=10)
for topic_tuple in current_topic:
current_topic_list.append(topic_tuple[0])
output_topic_line += ' '.join(current_topic_list)+'\n'
#print(current_topic_list)
topic_file = os.path.join(cache_path, 'ldatopic.txt')
with open(topic_file, 'w') as fo:
fo.write(output_topic_line)
testBatchIter = BatchIterBert(self.testDataIter, filling_last_batch=False, postProcessor=batchPostProcessor, batch_size=1)
test_bow_list = []
word_count = 0
for item in testBatchIter:
bow = item[1].squeeze().detach().numpy().tolist()
word_count += sum(bow)
test_bow_list.append(self.bow_2_gensim(bow))
print(word_count)
ppl = lda.log_perplexity(test_bow_list, len(test_bow_list))
print(ppl)
bound = lda.bound(test_bow_list)
print(bound/word_count)
print(np.exp2(-bound/word_count))
def bow_2_gensim(self, bow):
gensim_format = []
for idx, count in enumerate(bow):
if count > 0:
gensim_format.append((idx,count))
return gensim_format
def train(self, cache_path=None):
if self.inspectTest and (not self.splitValidation):
print('inspecting test, please dont use val acc as early stoping')
self.valDataIter = self.testDataIter
elif self.inspectTest and self.splitValidation:
print('inspectTest and splitValidation can not use same time')
print('deset inspectTest')
self.inspectTest = False
if self.splitValidation:
print('splitting test for validation')
self.valDataIter = copy.deepcopy(self.trainDataIter)
train_val_ids = copy.deepcopy(self.trainDataIter.all_ids)
random.shuffle(train_val_ids)
split_4_train = 1-self.splitValidation
top_n_4_train = math.floor(len(train_val_ids) * split_4_train)
id_4_train = train_val_ids[:top_n_4_train]
id_4_val = train_val_ids[top_n_4_train:]
self.trainDataIter.all_ids = id_4_train
self.valDataIter.all_ids = id_4_val
assert self.inspectTest != self.splitValidation, 'splitValidation will overwrite inspectTest, dont use at the same time'
if self.dynamicSampling:
print('get training data sample weights')
trainDataIter.cal_sample_weights()
self.trainDataIter._reset_iter()
trainBatchIter = BatchIterBert(self.trainDataIter, filling_last_batch=True, postProcessor=batchPostProcessor, batch_size=self.batch_size)
if self.valDataIter:
self.valDataIter._reset_iter()
valBatchIter = BatchIterBert(self.valDataIter, filling_last_batch=False, postProcessor=batchPostProcessor, batch_size=self.batch_size)
else:
valBatchIter = None
print(self.vocab_dim)
net = Model(self.config, vocab_dim=self.vocab_dim)
self.mUlti = modelUlti(net, gpu=self.gpu)
#print(next(trainBatchIter))
self.mUlti.train(trainBatchIter, cache_path=cache_path, num_epohs=self.num_epoches, valBatchIter=valBatchIter, patience=self.patient, earlyStopping=self.earlyStopping)
def train_test_evaluation(self):
path = Path(self.cache_path)
path.mkdir(parents=True, exist_ok=True)
self.train(cache_path=self.cache_path)
testBatchIter = BatchIterBert(self.testDataIter, filling_last_batch=False, postProcessor=batchPostProcessor, batch_size=self.batch_size)
results = self.mUlti.eval(testBatchIter, get_perp=self.get_perp)
print(results)
def train_model_only(self):
path = Path(self.cache_path)
path.mkdir(parents=True, exist_ok=True)
self.train(cache_path=self.cache_path)
def cross_fold_evaluation(self):
kf = KFold(n_splits=self.n_fold)
fold_index = 1
results_dict = {}
results_dict['accuracy'] = []
results_dict['perplexity'] = []
results_dict['log_perplexity'] = []
results_dict['perplexity_x_only'] = []
results_dict['f-measure'] = {}
for each_fold in kf.split(self.all_ids):
train_ids, test_ids = self.reconstruct_ids(each_fold)
self.trainDataIter.all_ids = train_ids
self.testDataIter.all_ids = test_ids
self.testDataIter._reset_iter()
fold_cache_path = os.path.join(self.cache_path, 'fold'+str(fold_index))
path = Path(fold_cache_path)
path.mkdir(parents=True, exist_ok=True)
if self.trainLDA:
self.train_lda(cache_path=fold_cache_path)
else:
self.train(cache_path=fold_cache_path)
testBatchIter = BatchIterBert(self.testDataIter, filling_last_batch=False, postProcessor=batchPostProcessor, batch_size=self.batch_size)
results = self.mUlti.eval(testBatchIter, get_perp=self.get_perp)
print(results)
results_dict['accuracy'].append(results['accuracy'])
if 'perplexity' in results:
results_dict['perplexity'].append(results['perplexity'])
results_dict['log_perplexity'].append(results['log_perplexity'])
results_dict['perplexity_x_only'].append(results['perplexity_x_only'])
for f_measure_class in results['f-measure']:
if f_measure_class not in results_dict['f-measure']:
results_dict['f-measure'][f_measure_class] = {'precision':[], 'recall':[], 'f-measure':[], 'total_pred':[], 'total_true':[], 'matches':[]}
results_dict['f-measure'][f_measure_class]['precision'].append(results['f-measure'][f_measure_class][0])
results_dict['f-measure'][f_measure_class]['recall'].append(results['f-measure'][f_measure_class][1])
results_dict['f-measure'][f_measure_class]['f-measure'].append(results['f-measure'][f_measure_class][2])
results_dict['f-measure'][f_measure_class]['total_pred'].append(results['f-measure'][f_measure_class][3])
results_dict['f-measure'][f_measure_class]['total_true'].append(results['f-measure'][f_measure_class][4])
results_dict['f-measure'][f_measure_class]['matches'].append(results['f-measure'][f_measure_class][5])
fold_index += 1
print(results_dict)
overall_accuracy = sum(results_dict['accuracy'])/len(results_dict['accuracy'])
if len(results_dict['perplexity']) >0:
overall_perplexity = sum(results_dict['perplexity'])/len(results_dict['perplexity'])
print('perplexity: ', overall_perplexity)
overall_log_perplexity = sum(results_dict['log_perplexity'])/len(results_dict['log_perplexity'])
print('log perplexity: ', overall_log_perplexity)
overall_perplexity_x = sum(results_dict['perplexity_x_only'])/len(results_dict['perplexity_x_only'])
print('perplexity_x_only: ', overall_perplexity_x)
macro_precision = get_average_fmeasure_score(results_dict, 'precision')
macro_recall = get_average_fmeasure_score(results_dict, 'recall')
macro_fmeasure = get_average_fmeasure_score(results_dict, 'f-measure')
micro_precision = get_micro_fmeasure(results_dict, 'matches', 'total_pred')
micro_recall = get_micro_fmeasure(results_dict, 'matches', 'total_true')
micro_fmeasure = 2*((micro_precision*micro_recall)/(micro_precision+micro_recall))
print('accuracy: ', overall_accuracy)
print('micro_precision: ', micro_precision)
print('micro_recall: ', micro_recall)
print('micro_f-measure: ', micro_fmeasure)
print('macro_precision: ', macro_precision)
print('macro_recall: ', macro_recall)
print('macro_f-measure: ', macro_fmeasure)
def reconstruct_ids(self, each_fold):
output_ids = [[],[]] #[train_ids, test_ids]
for sp_id in range(len(each_fold)):
current_output_ids = output_ids[sp_id]
current_fold_ids = each_fold[sp_id]
for doc_id in current_fold_ids:
current_output_ids.append(self.all_ids[doc_id])
return output_ids
def buildDict(self):
batchiter = BatchIterBert(self.trainDataIter, filling_last_batch=False, postProcessor=xonlyBatchProcessor, batch_size=1)
common_dictionary = Dictionary(batchiter)
print(len(common_dictionary))
if self.testReaderargs:
print('update vocab from test set')
batchiter = BatchIterBert(self.testDataIter, filling_last_batch=False, postProcessor=xonlyBatchProcessor, batch_size=1)
common_dictionary.add_documents(batchiter)
print(len(common_dictionary))
common_dictionary.filter_extremes(no_below=self.dict_no_below, no_above=self.dict_no_above, keep_n=self.dict_keep_n)
self.dictProcess = DictionaryProcess(common_dictionary)
self.postProcessor.dictProcess = self.dictProcess
self.vocab_dim = len(self.dictProcess)
self.have_dict = True
if 1:
count_list = []
self.trainDataIter._reset_iter()
batchiter = BatchIterBert(self.trainDataIter, filling_last_batch=False, postProcessor=xonlyBatchProcessor, batch_size=1)
for item in batchiter:
current_count = sum(item)
count_list.append(current_count)
#print(current_count)
print(sum(count_list)/len(count_list))
def getModel(self):
self.net = Model(config, vocab_dim=vocab_dim)
def getLibs(self):
print('getting libs')
print(self.modelType)
global modelUlti
global Model
global xonlyBatchProcessor
global batchPostProcessor
global dataIter
global ReaderPostProcessor
if self.modelType == 'clsTopic':
from GateMIcateLib import ModelUltiClass as modelUlti
from GateMIcateLib.models import CLSAW_TopicModel as Model
from GateMIcateLib.batchPostProcessors import xonlyBatchProcessor
from GateMIcateLib.batchPostProcessors import bowBertBatchProcessor as batchPostProcessor
self.get_dict = True
self.get_perp = True
elif self.modelType == 'clsTopicSL':
from GateMIcateLib import ModelUltiClass as modelUlti
from GateMIcateLib.models import CLSAW_TopicModelSL as Model
from GateMIcateLib.batchPostProcessors import xonlyBatchProcessor
from GateMIcateLib.batchPostProcessors import bowBertBatchProcessor as batchPostProcessor
self.get_dict = True
self.get_perp = True
elif self.modelType == 'baselineBert':
from GateMIcateLib import ModelUlti as modelUlti
from GateMIcateLib.models import BERT_Simple as Model
from GateMIcateLib.batchPostProcessors import xyOnlyBertBatchProcessor as batchPostProcessor
elif self.modelType == 'nvdm':
from GateMIcateLib import ModelUltiClass as modelUlti
from GateMIcateLib.models import NVDM as Model
from GateMIcateLib.batchPostProcessors import xonlyBatchProcessor
from GateMIcateLib.batchPostProcessors import bowBertBatchProcessor as batchPostProcessor
self.get_dict = True
self.get_perp = True
elif self.modelType == 'orinvdm':
from GateMIcateLib import ModelUltiClass as modelUlti
from GateMIcateLib.models import ORINVDM as Model
from GateMIcateLib.batchPostProcessors import xonlyBatchProcessor
from GateMIcateLib.batchPostProcessors import bowBertBatchProcessor as batchPostProcessor
self.get_dict = True
self.get_perp = True
elif self.modelType == 'clsTopicBE':
from GateMIcateLib import ModelUltiClass as modelUlti
from GateMIcateLib.models import CLSAW_TopicModel_BERTEN as Model
from GateMIcateLib.batchPostProcessors import xonlyBatchProcessor
from GateMIcateLib.batchPostProcessors import bowBertBatchProcessor as batchPostProcessor
self.get_dict = True
self.get_perp = True
print(self.corpusType)
if self.corpusType == 'wvmisinfo':
from GateMIcateLib.readers import WVmisInfoDataIter as dataIter
from GateMIcateLib import WVPostProcessor as ReaderPostProcessor
self.dict_no_below = 3
self.dict_no_above = 0.7
elif self.corpusType == 'wvmisinfoScholar':
from GateMIcateLib.readers import WVmisInfoDataIter as dataIter
from GateMIcateLib import ScholarPostProcessor as ReaderPostProcessor
self.dict_keep_n = 2000
elif self.corpusType == 'aclIMDB':
from GateMIcateLib.readers import ACLimdbReader as dataIter
from GateMIcateLib import ScholarPostProcessor as ReaderPostProcessor
elif self.corpusType == 'tsvBinary':
from GateMIcateLib.readers import TsvBinaryFolderReader as dataIter
from GateMIcateLib import WVPostProcessor as ReaderPostProcessor
self.dict_no_below = 3
self.dict_no_above = 0.7
| 20,370 | 42.342553 | 208 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/WVPostProcessor.py
|
import nltk
from nltk.corpus import stopwords
import os
import re
from .PostprocessorBase import ReaderPostProcessorBase
from transformers import BertTokenizer
class WVPostProcessor(ReaderPostProcessorBase):
def __init__(self, x_fields=['Claim', 'Explaination'], y_field='category', **kwargs):
super().__init__(**kwargs)
self.x_fields = x_fields
self.y_field = y_field
self.initProcessor()
def initProcessor(self):
bert_tokenizer_path = os.path.join(self.config['BERT'].get('bert_path'), 'tokenizer')
self.bert_tokenizer = BertTokenizer.from_pretrained(bert_tokenizer_path)
self.tokenizerProcessor = self.bertTokenizer
self.word2idProcessor = self.bertWord2id
if 'TARGET' in self.config:
self.labelsFields = self.config['TARGET'].get('labels')
else:
self.labelsFields = ['PubAuthAction', 'CommSpread', 'GenMedAdv', 'PromActs', 'Consp', 'VirTrans', 'VirOrgn', 'PubPrep', 'Vacc', 'Prot', 'None']
#print(self.labelsFields)
def postProcess(self, sample):
split_x = []
for x_field in self.x_fields:
current_rawx = self._get_sample(sample, x_field)
split_x.append(current_rawx)
current_rawx = ' '.join(split_x)
## Bert toknise for hidden layers. add_special_tokens not added, additional attention will be applied on token level (CLS not used)
if self.embd_ready:
current_x = sample['embd']
else:
current_x = self.x_pipeline(current_rawx, add_special_tokens=self.add_spec_tokens)
## NLTK tokenise and remove stopwords for topic modelling
current_x_nltk_tokened = self.nltkTokenizer(current_rawx)
current_x_nltk_tokened = self._remove_stop_words(current_x_nltk_tokened)
if self.dictProcess:
current_x_nltk_tokened = self.dictProcess.doc2countHot(current_x_nltk_tokened)
x=[current_x, current_x_nltk_tokened]
y = sample[self.y_field]
if self.label2id:
y = self.label2ids(y)
if self.remove_single_list:
x = self._removeSingleList(x)
y = self._removeSingleList(y)
return x, y
| 2,216 | 37.894737 | 155 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/models/CLSAW_TopicModel_simple_loss.py
|
import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
import math
from .miscLayer import BERT_Embedding, WVHidden, WVClassifier, Identity, Topics, kld, CLSAW_TopicModel_Base
class CLSAW_TopicModelSL(CLSAW_TopicModel_Base):
def __init__(self, config, vocab_dim=None):
super().__init__(config=config)
default_config = {}
self.bert_embedding = BERT_Embedding(config)
bert_dim = self.bert_embedding.bert_dim
if self.banlance_loss:
self.banlance_lambda = float(math.ceil(vocab_dim/self.n_classes))
else:
self.banlance_lambda = 1
#self.wv_hidden = WVHidden(bert_dim, self.hidden_dim)
self.hidden_dim = bert_dim
##############M1###########################################
self.mu_z1 = nn.Linear(self.hidden_dim, self.z_dim)
self.log_sigma_z1 = nn.Linear(self.hidden_dim, self.z_dim)
self.x_only_topics = Topics(self.z_dim, vocab_dim)
self.xy_classifier = WVClassifier(self.z_dim, self.n_classes)
self.class_criterion = nn.CrossEntropyLoss()
#############M2############################################
self.hidden_y_dim = self.hidden_dim + self.n_classes
self.z_y_dim = self.z_dim + self.n_classes
self.x_y_hidden = WVHidden(self.hidden_y_dim, self.hidden_dim)
self.z_y_hidden = WVHidden(self.z_y_dim, self.ntopics)
self.mu_z2 = nn.Linear(self.hidden_dim, self.z_dim)
self.log_sigma_z2 = nn.Linear(self.hidden_dim, self.z_dim)
self.xy_topics = Topics(self.ntopics, vocab_dim)
self.z2y_classifier = WVClassifier(self.ntopics, self.n_classes)
############################################################
self.h_to_z = Identity()
self.class_topics = Topics(self.n_classes, vocab_dim)
self.reset_parameters()
def forward(self,x, mask=None, n_samples=1, bow=None, train=False, true_y=None, pre_embd=False, true_y_ids=None):
#print(true_y.shape)
if pre_embd:
bert_rep = x
else:
bert_rep = self.bert_embedding(x, mask)
bert_rep = bert_rep[0]
atted = bert_rep[:,0]
#hidden = self.wv_hidden(atted)
hidden = atted
mu_z1 = self.mu_z1(hidden)
log_sigma_z1 = self.log_sigma_z1(hidden)
kldz1 = kld(mu_z1, log_sigma_z1)
rec_loss_z1 = 0
classifier_loss = 0
kldz2 = 0
rec_loss_z2 = 0
log_y_hat_rec_loss = 0
class_topic_rec_loss = 0
if not train:
### for discriminator, we only use mean
z1 = mu_z1
y_hat_logis = self.xy_classifier(z1)
log_probz_1 = self.x_only_topics(z1)
y_hat = torch.softmax(y_hat_logis, dim=-1)
log_prob_class_topic = self.class_topics(y_hat)
#y = y_hat_logis
for i in range(n_samples):
if train:
z1 = torch.zeros_like(mu_z1).normal_() * torch.exp(log_sigma_z1) + mu_z1
z1 = self.h_to_z(z1)
log_probz_1 = self.x_only_topics(z1)
y_hat_logis = self.xy_classifier(z1)
y_hat = torch.softmax(y_hat_logis, dim=-1)
log_prob_class_topic = self.class_topics(y_hat)
classifier_loss += self.class_criterion(y_hat_logis, true_y_ids)
y_hat_h = torch.cat((hidden, y_hat), dim=-1)
x_y_hidden = self.x_y_hidden(y_hat_h)
mu_z2 = self.mu_z2(x_y_hidden)
log_sigma_z2 = self.log_sigma_z2(x_y_hidden)
z2 = torch.zeros_like(mu_z2).normal_() * torch.exp(log_sigma_z2) + mu_z2
topic = z2
log_prob_z2 = self.xy_topics(topic)
#y_hat_rec = self.z2y_classifier(topic)
#log_y_hat_rec = torch.log_softmax(y_hat_rec, dim=-1)
rec_loss_z1 = rec_loss_z1-(log_probz_1 * bow).sum(dim=-1)
kldz2 += kld(mu_z2, log_sigma_z2)
rec_loss_z2 = rec_loss_z2 - (log_prob_z2 * bow).sum(dim=-1)
#log_y_hat_rec_loss = log_y_hat_rec_loss - (log_y_hat_rec*true_y).sum(dim=-1)
#log_y_hat_rec_loss = log_y_hat_rec_loss - (log_y_hat_rec*y_hat).sum(dim=-1)
class_topic_rec_loss = class_topic_rec_loss - (log_prob_class_topic*bow).sum(dim=-1)
rec_loss_z1 = rec_loss_z1/n_samples
#print(rec_loss_z1.shape)
classifier_loss = classifier_loss/n_samples
kldz2 = kldz2/n_samples
rec_loss_z2 = rec_loss_z2/n_samples
log_y_hat_rec_loss = log_y_hat_rec_loss/n_samples
class_topic_rec_loss = class_topic_rec_loss/n_samples
elbo_z1 = kldz1 + rec_loss_z1
#print(elbo_z1.shape)
#elbo_z1 = elbo_z1.sum()
elbo_z2 = kldz2 + rec_loss_z2# + log_y_hat_rec_loss
#print(elbo_z2)
#elbo_z2 = elbo_z2.sum()
#class_topic_rec_loss = class_topic_rec_loss.sum()
classifier_loss = classifier_loss
total_loss = elbo_z1.sum() + elbo_z2.sum() + class_topic_rec_loss.sum() + classifier_loss*self.banlance_lambda*self.classification_loss_lambda
y = {
'loss': total_loss,
'elbo_xy': elbo_z2,
'rec_loss': rec_loss_z2,
'kld': kldz2,
'cls_loss': classifier_loss,
'class_topic_loss': class_topic_rec_loss,
'y_hat': y_hat_logis,
'elbo_x': elbo_z1
}
####################################################################################################################################################
# else:
# z1 = mu_z1
# y_hat_logis = self.xy_classifier(z1)
# y_hat = torch.softmax(y_hat_logis, dim=-1)
# y = y_hat_logis
#
#
# y_hat_h = torch.cat((hidden, y_hat), dim=-1)
# x_y_hidden = self.x_y_hidden(y_hat_h)
# mu_z2 = self.mu_z2(x_y_hidden)
# log_sigma_z2 = self.log_sigma_z2(x_y_hidden)
# z2 = torch.zeros_like(mu_z2).normal_() * torch.exp(log_sigma_z2) + mu_z2
#
# kldz2 = kld(mu_z2, log_sigma_z2)
# log_prob_z2 = self.xy_topics(z2)
# y_hat_rec = self.z2y_classifier(z2)
# log_y_hat_rec = torch.log_softmax(y_hat_rec, dim=-1)
#
#
return y, None
def reset_parameters(self):
init.zeros_(self.log_sigma_z1.weight)
init.zeros_(self.log_sigma_z1.bias)
init.zeros_(self.log_sigma_z2.weight)
init.zeros_(self.log_sigma_z2.bias)
def get_topics(self):
return self.xy_topics.get_topics()
def get_class_topics(self):
return self.class_topics.get_topics()
def get_x_only_topics(self):
return self.x_only_topics.get_topics()
| 6,776 | 35.435484 | 150 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/models/CLSAW_TopicModel.py
|
import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
import math
from .miscLayer import BERT_Embedding, WVHidden, WVClassifier, Identity, Topics, kld, CLSAW_TopicModel_Base
class CLSAW_TopicModel(CLSAW_TopicModel_Base):
def __init__(self, config, vocab_dim=None):
super().__init__(config=config)
default_config = {}
self.bert_embedding = BERT_Embedding(config)
bert_dim = self.bert_embedding.bert_dim
if self.banlance_loss:
self.banlance_lambda = float(math.ceil(vocab_dim/self.n_classes))
else:
self.banlance_lambda = 1
#self.wv_hidden = WVHidden(bert_dim, self.hidden_dim)
self.hidden_dim = bert_dim
##############M1###########################################
self.mu_z1 = nn.Linear(self.hidden_dim, self.z_dim)
self.log_sigma_z1 = nn.Linear(self.hidden_dim, self.z_dim)
self.x_only_topics = Topics(self.z_dim, vocab_dim)
self.xy_classifier = WVClassifier(self.z_dim, self.n_classes)
self.class_criterion = nn.CrossEntropyLoss()
#############M2############################################
self.hidden_y_dim = self.hidden_dim + self.n_classes
self.z_y_dim = self.z_dim + self.n_classes
self.x_y_hidden = WVHidden(self.hidden_y_dim, self.hidden_dim)
self.z_y_hidden = WVHidden(self.z_y_dim, self.ntopics)
self.mu_z2 = nn.Linear(self.hidden_dim, self.z_dim)
self.log_sigma_z2 = nn.Linear(self.hidden_dim, self.z_dim)
self.xy_topics = Topics(self.ntopics, vocab_dim)
self.z2y_classifier = WVClassifier(self.ntopics, self.n_classes)
############################################################
self.h_to_z = Identity()
self.class_topics = Topics(self.n_classes, vocab_dim)
self.reset_parameters()
def forward(self,x, mask=None, n_samples=1, bow=None, train=False, true_y=None, pre_embd=False, true_y_ids=None, update_catopic=False):
#print(true_y.shape)
if pre_embd:
bert_rep = x
else:
bert_rep = self.bert_embedding(x, mask)
bert_rep = bert_rep[0]
atted = bert_rep[:,0]
#hidden = self.wv_hidden(atted)
hidden = atted
mu_z1 = self.mu_z1(hidden)
log_sigma_z1 = self.log_sigma_z1(hidden)
kldz1 = kld(mu_z1, log_sigma_z1)
rec_loss_z1 = 0
classifier_loss = 0
kldz2 = 0
rec_loss_z2 = 0
log_y_hat_rec_loss = 0
class_topic_rec_loss = 0
#if not train:
# ### for discriminator, we only use mean
# z1 = mu_z1
# y_hat_logis = self.xy_classifier(z1)
# log_probz_1 = self.x_only_topics(z1)
# y_hat = torch.softmax(y_hat_logis, dim=-1)
# log_prob_class_topic = self.class_topics(y_hat)
# #y = y_hat_logis
for i in range(n_samples):
z1 = torch.zeros_like(mu_z1).normal_() * torch.exp(log_sigma_z1) + mu_z1
z1 = self.h_to_z(z1)
log_probz_1 = self.x_only_topics(z1)
#if train or update_catopic:
# z1 = torch.zeros_like(mu_z1).normal_() * torch.exp(log_sigma_z1) + mu_z1
# z1 = self.h_to_z(z1)
# log_probz_1 = self.x_only_topics(z1)
# y_hat_logis = self.xy_classifier(z1)
# y_hat = torch.softmax(y_hat_logis, dim=-1)
# log_prob_class_topic = self.class_topics(y_hat)
if train or update_catopic:
y_hat_logis = self.xy_classifier(z1)
y_hat = torch.softmax(y_hat_logis, dim=-1)
#print(y_hat.shape)
else:
y_hat_logis = self.xy_classifier(mu_z1)
y_hat = torch.softmax(y_hat_logis, dim=-1)
if train:
classifier_loss += self.class_criterion(y_hat_logis, true_y_ids)
log_prob_class_topic = self.class_topics(y_hat)
y_hat_h = torch.cat((hidden, y_hat), dim=-1)
x_y_hidden = self.x_y_hidden(y_hat_h)
mu_z2 = self.mu_z2(x_y_hidden)
log_sigma_z2 = self.log_sigma_z2(x_y_hidden)
z2 = torch.zeros_like(mu_z2).normal_() * torch.exp(log_sigma_z2) + mu_z2
y_hat_z = torch.cat((z2, y_hat), dim=-1)
topic = self.z_y_hidden(y_hat_z)
log_prob_z2 = self.xy_topics(topic)
y_hat_rec = self.z2y_classifier(topic)
log_y_hat_rec = torch.log_softmax(y_hat_rec, dim=-1)
rec_loss_z1 = rec_loss_z1-(log_probz_1 * bow).sum(dim=-1)
kldz2 += kld(mu_z2, log_sigma_z2)
rec_loss_z2 = rec_loss_z2 - (log_prob_z2 * bow).sum(dim=-1)
#log_y_hat_rec_loss = log_y_hat_rec_loss - (log_y_hat_rec*true_y).sum(dim=-1)
log_y_hat_rec_loss = log_y_hat_rec_loss - (log_y_hat_rec*y_hat).sum(dim=-1)
class_topic_rec_loss = class_topic_rec_loss - (log_prob_class_topic*bow).sum(dim=-1)
rec_loss_z1 = rec_loss_z1/n_samples
#print(rec_loss_z1.shape)
classifier_loss = classifier_loss/n_samples
kldz2 = kldz2/n_samples
rec_loss_z2 = rec_loss_z2/n_samples
log_y_hat_rec_loss = log_y_hat_rec_loss/n_samples
class_topic_rec_loss = class_topic_rec_loss/n_samples
elbo_z1 = kldz1 + rec_loss_z1
#print(elbo_z1.shape)
#elbo_z1 = elbo_z1.sum()
elbo_z2 = kldz2 + rec_loss_z2 + log_y_hat_rec_loss
#print(elbo_z2)
#elbo_z2 = elbo_z2.sum()
#class_topic_rec_loss = class_topic_rec_loss.sum()
classifier_loss = classifier_loss
total_loss = elbo_z1.sum() + elbo_z2.sum() + class_topic_rec_loss.sum() + classifier_loss*self.banlance_lambda*self.classification_loss_lambda
if update_catopic:
total_loss = elbo_z2.sum()
y = {
'loss': total_loss,
'elbo_xy': elbo_z2,
'rec_loss': rec_loss_z2,
'kld': kldz2,
'cls_loss': classifier_loss,
'class_topic_loss': class_topic_rec_loss,
'y_hat': y_hat_logis,
'elbo_x': elbo_z1
}
####################################################################################################################################################
# else:
# z1 = mu_z1
# y_hat_logis = self.xy_classifier(z1)
# y_hat = torch.softmax(y_hat_logis, dim=-1)
# y = y_hat_logis
#
#
# y_hat_h = torch.cat((hidden, y_hat), dim=-1)
# x_y_hidden = self.x_y_hidden(y_hat_h)
# mu_z2 = self.mu_z2(x_y_hidden)
# log_sigma_z2 = self.log_sigma_z2(x_y_hidden)
# z2 = torch.zeros_like(mu_z2).normal_() * torch.exp(log_sigma_z2) + mu_z2
#
# kldz2 = kld(mu_z2, log_sigma_z2)
# log_prob_z2 = self.xy_topics(z2)
# y_hat_rec = self.z2y_classifier(z2)
# log_y_hat_rec = torch.log_softmax(y_hat_rec, dim=-1)
#
#
return y, None
def reset_parameters(self):
init.zeros_(self.log_sigma_z1.weight)
init.zeros_(self.log_sigma_z1.bias)
init.zeros_(self.log_sigma_z2.weight)
init.zeros_(self.log_sigma_z2.bias)
def get_topics(self):
return self.xy_topics.get_topics()
def get_class_topics(self):
return self.class_topics.get_topics()
def get_x_only_topics(self):
return self.x_only_topics.get_topics()
| 7,541 | 35.434783 | 150 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/models/CLSAW_TopicModelBertEnrich.py
|
import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
import math
from .miscLayer import BERT_Embedding, WVHidden, WVClassifier, Identity, Topics, kld, CLSAW_TopicModel_Base
class CLSAW_TopicModel_BERTEN(CLSAW_TopicModel_Base):
def __init__(self, config, vocab_dim=None):
super().__init__(config=config)
default_config = {}
self.bert_embedding = BERT_Embedding(config)
bert_dim = self.bert_embedding.bert_dim
if self.banlance_loss:
self.banlance_lambda = float(math.ceil(vocab_dim/self.n_classes))
else:
self.banlance_lambda = 1
self.hidden_dim = 500
self.bow_hidden = WVHidden(vocab_dim, 500)
self.mix_bert = WVHidden(500+ bert_dim, self.hidden_dim)
##############M1###########################################
self.mu_z1 = nn.Linear(self.hidden_dim, self.z_dim)
self.log_sigma_z1 = nn.Linear(self.hidden_dim, self.z_dim)
self.x_only_topics = Topics(self.z_dim, vocab_dim)
self.xy_classifier = WVClassifier(self.z_dim, self.n_classes)
self.class_criterion = nn.CrossEntropyLoss()
#############M2############################################
self.hidden_y_dim = self.hidden_dim + self.n_classes
self.z_y_dim = self.z_dim + self.n_classes
self.x_y_hidden = WVHidden(self.hidden_y_dim, self.hidden_dim)
self.z_y_hidden = WVHidden(self.z_y_dim, self.ntopics)
self.mu_z2 = nn.Linear(self.hidden_dim, self.z_dim)
self.log_sigma_z2 = nn.Linear(self.hidden_dim, self.z_dim)
self.xy_topics = Topics(self.ntopics, vocab_dim)
self.z2y_classifier = WVClassifier(self.ntopics, self.n_classes)
############################################################
self.h_to_z = Identity()
self.class_topics = Topics(self.n_classes, vocab_dim)
self.reset_parameters()
def forward(self,x, mask=None, n_samples=1, bow=None, train=False, true_y=None, pre_embd=False, true_y_ids=None):
#print(true_y.shape)
if pre_embd:
bert_rep = x
else:
bert_rep = self.bert_embedding(x, mask)
bert_rep = bert_rep[0]
bow_hidden = self.bow_hidden(bow)
atted = bert_rep[:,0]
bert_bow = torch.cat((atted, bow_hidden), dim=-1)
hidden = self.mix_bert(bert_bow)
#hidden = atted
mu_z1 = self.mu_z1(hidden)
log_sigma_z1 = self.log_sigma_z1(hidden)
kldz1 = kld(mu_z1, log_sigma_z1)
rec_loss_z1 = 0
classifier_loss = 0
kldz2 = 0
rec_loss_z2 = 0
log_y_hat_rec_loss = 0
class_topic_rec_loss = 0
if not train:
### for discriminator, we only use mean
z1 = mu_z1
y_hat_logis = self.xy_classifier(z1)
log_probz_1 = self.x_only_topics(z1)
y_hat = torch.softmax(y_hat_logis, dim=-1)
log_prob_class_topic = self.class_topics(y_hat)
#y = y_hat_logis
for i in range(n_samples):
if train:
z1 = torch.zeros_like(mu_z1).normal_() * torch.exp(log_sigma_z1) + mu_z1
z1 = self.h_to_z(z1)
log_probz_1 = self.x_only_topics(z1)
y_hat_logis = self.xy_classifier(z1)
y_hat = torch.softmax(y_hat_logis, dim=-1)
log_prob_class_topic = self.class_topics(y_hat)
classifier_loss += self.class_criterion(y_hat_logis, true_y_ids)
y_hat_h = torch.cat((hidden, y_hat), dim=-1)
x_y_hidden = self.x_y_hidden(y_hat_h)
mu_z2 = self.mu_z2(x_y_hidden)
log_sigma_z2 = self.log_sigma_z2(x_y_hidden)
z2 = torch.zeros_like(mu_z2).normal_() * torch.exp(log_sigma_z2) + mu_z2
y_hat_z = torch.cat((z2, y_hat), dim=-1)
topic = self.z_y_hidden(y_hat_z)
log_prob_z2 = self.xy_topics(topic)
y_hat_rec = self.z2y_classifier(topic)
log_y_hat_rec = torch.log_softmax(y_hat_rec, dim=-1)
rec_loss_z1 = rec_loss_z1-(log_probz_1 * bow).sum(dim=-1)
kldz2 += kld(mu_z2, log_sigma_z2)
rec_loss_z2 = rec_loss_z2 - (log_prob_z2 * bow).sum(dim=-1)
#log_y_hat_rec_loss = log_y_hat_rec_loss - (log_y_hat_rec*true_y).sum(dim=-1)
log_y_hat_rec_loss = log_y_hat_rec_loss - (log_y_hat_rec*y_hat).sum(dim=-1)
class_topic_rec_loss = class_topic_rec_loss - (log_prob_class_topic*bow).sum(dim=-1)
rec_loss_z1 = rec_loss_z1/n_samples
#print(rec_loss_z1.shape)
classifier_loss = classifier_loss/n_samples
kldz2 = kldz2/n_samples
rec_loss_z2 = rec_loss_z2/n_samples
log_y_hat_rec_loss = log_y_hat_rec_loss/n_samples
class_topic_rec_loss = class_topic_rec_loss/n_samples
elbo_z1 = kldz1 + rec_loss_z1
#print(elbo_z1.shape)
#elbo_z1 = elbo_z1.sum()
elbo_z2 = kldz2 + rec_loss_z2 + log_y_hat_rec_loss
#print(elbo_z2)
#elbo_z2 = elbo_z2.sum()
#class_topic_rec_loss = class_topic_rec_loss.sum()
classifier_loss = classifier_loss
total_loss = elbo_z1.sum() + elbo_z2.sum() + class_topic_rec_loss.sum() + classifier_loss*self.banlance_lambda*self.classification_loss_lambda
y = {
'loss': total_loss,
'elbo_xy': elbo_z2,
'rec_loss': rec_loss_z2,
'kld': kldz2,
'cls_loss': classifier_loss,
'class_topic_loss': class_topic_rec_loss,
'y_hat': y_hat_logis,
'elbo_x': elbo_z1
}
####################################################################################################################################################
# else:
# z1 = mu_z1
# y_hat_logis = self.xy_classifier(z1)
# y_hat = torch.softmax(y_hat_logis, dim=-1)
# y = y_hat_logis
#
#
# y_hat_h = torch.cat((hidden, y_hat), dim=-1)
# x_y_hidden = self.x_y_hidden(y_hat_h)
# mu_z2 = self.mu_z2(x_y_hidden)
# log_sigma_z2 = self.log_sigma_z2(x_y_hidden)
# z2 = torch.zeros_like(mu_z2).normal_() * torch.exp(log_sigma_z2) + mu_z2
#
# kldz2 = kld(mu_z2, log_sigma_z2)
# log_prob_z2 = self.xy_topics(z2)
# y_hat_rec = self.z2y_classifier(z2)
# log_y_hat_rec = torch.log_softmax(y_hat_rec, dim=-1)
#
#
return y, None
def reset_parameters(self):
init.zeros_(self.log_sigma_z1.weight)
init.zeros_(self.log_sigma_z1.bias)
init.zeros_(self.log_sigma_z2.weight)
init.zeros_(self.log_sigma_z2.bias)
def get_topics(self):
return self.xy_topics.get_topics()
def get_class_topics(self):
return self.class_topics.get_topics()
def get_x_only_topics(self):
return self.x_only_topics.get_topics()
| 7,008 | 34.760204 | 150 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/models/miscLayer.py
|
from transformers import BertModel
import math
import os
import torch.nn.functional as F
import torch
import torch.nn as nn
class SingleHeadAttention(nn.Module):
def __init__(self, d_model, d_output, dropout = 0.1):
super().__init__()
self.q = nn.Parameter(torch.randn([d_output, 1]).float())
self.v_linear = nn.Linear(d_model, d_output)
self.dropout_v = nn.Dropout(dropout)
self.k_linear = nn.Linear(d_model, d_output)
self.dropout_k = nn.Dropout(dropout)
self.softmax_simi = nn.Softmax(dim=1)
self.dropout = nn.Dropout(dropout)
#self.out = nn.Linear(d_output, d_output)
def forward(self, x, mask=None):
k = self.k_linear(x)
k = F.relu(k)
k = self.dropout_k(k)
v = self.v_linear(x)
v = F.relu(v)
v = self.dropout_v(v)
dotProducSimi = k.matmul(self.q)
normedSimi = self.softmax_simi(dotProducSimi)
attVector = v.mul(normedSimi)
weightedSum = torch.sum(attVector, dim=1)
#output = self.out(weightedSum)
return weightedSum
class Norm(nn.Module):
def __init__(self, d_model, eps = 1e-6):
super().__init__()
self.size = d_model
# create two learnable parameters to calibrate normalisation
self.alpha = nn.Parameter(torch.ones(self.size))
self.bias = nn.Parameter(torch.zeros(self.size))
self.eps = eps
def forward(self, x):
norm = self.alpha * (x - x.mean(dim=-1, keepdim=True)) \
/ (x.std(dim=-1, keepdim=True) + self.eps) + self.bias
return norm
def attention(q, k, v, d_k, mask=None, dropout=None):
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(d_k)
if mask is not None:
mask = mask.unsqueeze(1)
scores = scores.masked_fill(mask == 0, -1e9)
scores = F.softmax(scores, dim=-1)
if dropout is not None:
scores = dropout(scores)
output = torch.matmul(scores, v)
return output
class EncoderLayer(nn.Module):
def __init__(self, d_model, heads, dropout=0.1):
super().__init__()
self.norm_1 = Norm(d_model)
self.norm_2 = Norm(d_model)
self.attn = MultiHeadAttention(heads, d_model, dropout=dropout)
self.ff = FeedForward(d_model, dropout=dropout)
self.dropout_1 = nn.Dropout(dropout)
self.dropout_2 = nn.Dropout(dropout)
def forward(self, x, mask):
x2 = self.norm_1(x)
x = x + self.dropout_1(self.attn(x2,x2,x2,mask))
x2 = self.norm_2(x)
x = x + self.dropout_2(self.ff(x2))
return x
class MultiHeadAttention(nn.Module):
def __init__(self, heads, d_model, dropout = 0.1):
super().__init__()
self.d_model = d_model
self.d_k = d_model // heads
self.h = heads
self.q_linear = nn.Linear(d_model, d_model)
self.v_linear = nn.Linear(d_model, d_model)
self.k_linear = nn.Linear(d_model, d_model)
self.dropout = nn.Dropout(dropout)
self.out = nn.Linear(d_model, d_model)
def forward(self, q, k, v, mask=None):
bs = q.size(0)
# perform linear operation and split into N heads
# bs, sl, d_model --> bs, sl, heads, sub_d_model
# d_model = heads * sub_d_model
k = self.k_linear(k).view(bs, -1, self.h, self.d_k)
q = self.q_linear(q).view(bs, -1, self.h, self.d_k)
v = self.v_linear(v).view(bs, -1, self.h, self.d_k)
# transpose to get dimensions bs * N * sl * d_model
k = k.transpose(1,2)
q = q.transpose(1,2)
v = v.transpose(1,2)
# calculate attention using function we will define next
scores = attention(q, k, v, self.d_k, mask, self.dropout)
# concatenate heads and put through final linear layer
concat = scores.transpose(1,2).contiguous()\
.view(bs, -1, self.d_model)
output = self.out(concat)
return output
class FeedForward(nn.Module):
def __init__(self, d_model, d_ff=1024, dropout = 0.1):
super().__init__()
# We set d_ff as a default to 2048
self.linear_1 = nn.Linear(d_model, d_ff)
self.dropout = nn.Dropout(dropout)
self.linear_2 = nn.Linear(d_ff, d_model)
def forward(self, x):
x = self.dropout(F.relu(self.linear_1(x)))
x = self.linear_2(x)
return x
class BERT_Embedding(nn.Module):
def __init__(self, config):
super().__init__()
bert_model_path = os.path.join(config['BERT'].get('bert_path'), 'model')
self.bert_dim = int(config['BERT'].get('bert_dim'))
self.trainable_layers = config['BERT'].get('trainable_layers')
self.bert = BertModel.from_pretrained(bert_model_path)
if self.trainable_layers:
#print(self.trainable_layers)
#self.bert = BertModel.from_pretrained(bert_model_path)
for name, param in self.bert.named_parameters():
if name in self.trainable_layers:
param.requires_grad = True
#print(name, param)
else:
param.requires_grad = False
else:
for p in self.bert.parameters():
p.requires_grad = False
def forward(self, x, mask=None):
if mask == None:
mask = x != 0
mask.type(x.type())
bert_rep = self.bert(x, attention_mask=mask)
return bert_rep
class Dense(nn.Module):
def __init__(self, input_dim, out_dim, non_linear=None):
super().__init__()
self.dense = nn.Linear(input_dim, out_dim)
self.non_linear = non_linear
def forward(self, x):
output = self.dense(x)
if self.non_linear:
output = self.non_linear(output)
return output
class Topics(nn.Module):
def __init__(self, k, vocab_size, bias=True):
super(Topics, self).__init__()
self.k = k
self.vocab_size = vocab_size
self.topic = nn.Linear(k, vocab_size, bias=bias)
def forward(self, logit):
# return the log_prob of vocab distribution
return torch.log_softmax(self.topic(logit), dim=-1)
def get_topics(self):
#print('hey')
#print(self.topic.weight)
return torch.softmax(self.topic.weight.data.transpose(0, 1), dim=-1)
def get_topic_word_logit(self):
"""topic x V.
Return the logits instead of probability distribution
"""
return self.topic.weight.transpose(0, 1)
class Identity(nn.Module):
def __init__(self):
super(Identity, self).__init__()
def forward(self, *input):
if len(input) == 1:
return input[0]
return input
def kld(mu, log_sigma):
"""log q(z) || log p(z).
mu: batch_size x dim
log_sigma: batch_size x dim
"""
return -0.5 * (1 - mu ** 2 + 2 * log_sigma - torch.exp(2 * log_sigma)).sum(dim=-1)
class BERT_Mapping_mapping(nn.Module):
def __init__(self, bert_dim):
super().__init__()
self.att = SingleHeadAttention(bert_dim, bert_dim)
def forward(self,x):
atted = self.att(x)
return atted
class WVHidden(nn.Module):
def __init__(self, input_dim, hidden_dim):
super().__init__()
self.hidden1 = nn.Linear(input_dim, hidden_dim)
def forward(self, x):
hidden = F.leaky_relu(self.hidden1(x))
return hidden
class WVClassifier(nn.Module):
def __init__(self, n_hidden, n_classes):
super().__init__()
self.layer_output = torch.nn.Linear(n_hidden, n_classes)
def forward(self, x):
out = self.layer_output(x)
return out
class CLSAW_TopicModel_Base(nn.Module):
def __init__(self, config=None):
super().__init__()
self._init_params()
if config:
self._read_config(config)
def _init_params(self):
self.hidden_dim = 300
self.z_dim = 100
self.ntopics = 50
self.class_topic_loss_lambda = 1
self.classification_loss_lambda = 1
self.banlance_loss = False
def _read_config(self, config):
self.n_classes = len(config['TARGET'].get('labels'))
if 'MODEL' in config:
if 'hidden_dim' in config['MODEL']:
self.hidden_dim = int(config['MODEL'].get('hidden_dim'))
if 'z_dim' in config['MODEL']:
self.z_dim = int(config['MODEL'].get('z_dim'))
if 'ntopics' in config['MODEL']:
self.ntopics = int(config['MODEL'].get('ntopics'))
if 'class_topic_loss_lambda' in config['MODEL']:
self.class_topic_loss_lambda = float(config['MODEL'].get('class_topic_loss_lambda'))
if 'classification_loss_lambda' in config['MODEL']:
self.class_topic_loss_lambda = float(config['MODEL'].get('classification_loss_lambda'))
if 'banlance_loss' in config['MODEL']:
self.banlance_loss = config['MODEL'].as_bool('banlance_loss')
self.n_class_topics = self.z_dim+self.n_classes
| 9,182 | 29.407285 | 103 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/models/CLSAW_TopicModel_linear.py
|
import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
import math
from .miscLayer import BERT_Embedding, WVHidden, WVClassifier, Identity, Topics, kld, CLSAW_TopicModel_Base
class CLSAW_TopicModel(CLSAW_TopicModel_Base):
def __init__(self, config, vocab_dim=None):
super().__init__(config=config)
default_config = {}
self.bert_embedding = BERT_Embedding(config)
bert_dim = self.bert_embedding.bert_dim
if self.banlance_loss:
self.banlance_lambda = float(math.ceil(vocab_dim/self.n_classes))
else:
self.banlance_lambda = 1
#self.wv_hidden = WVHidden(bert_dim, self.hidden_dim)
self.hidden_dim = bert_dim
##############M1###########################################
self.mu_z1 = nn.Linear(self.hidden_dim, self.z_dim)
self.log_sigma_z1 = nn.Linear(self.hidden_dim, self.z_dim)
self.x_only_topics = Topics(self.z_dim, vocab_dim)
self.xy_classifier = WVClassifier(self.z_dim, self.n_classes)
self.class_criterion = nn.CrossEntropyLoss()
#############M2############################################
self.hidden_y_dim = self.hidden_dim + self.n_classes
self.z_y_dim = self.z_dim + self.n_classes
self.x_y_hidden = WVHidden(self.hidden_y_dim, self.hidden_dim)
self.z_y_hidden = WVHidden(self.z_y_dim, self.ntopics)
self.mu_z2 = nn.Linear(self.hidden_dim, self.z_dim)
self.log_sigma_z2 = nn.Linear(self.hidden_dim, self.z_dim)
self.xy_topics = Topics(self.ntopics, vocab_dim)
self.z2y_classifier = WVClassifier(self.ntopics, self.n_classes)
############################################################
self.h_to_z = Identity()
self.class_topics = Topics(self.n_classes, vocab_dim)
self.reset_parameters()
def forward(self,x, mask=None, n_samples=1, bow=None, train=False, true_y=None, pre_embd=False, true_y_ids=None):
#print(true_y.shape)
if pre_embd:
bert_rep = x
else:
bert_rep = self.bert_embedding(x, mask)
bert_rep = bert_rep[0]
atted = bert_rep[:,0]
#hidden = self.wv_hidden(atted)
hidden = atted
mu_z1 = self.mu_z1(hidden)
log_sigma_z1 = self.log_sigma_z1(hidden)
kldz1 = kld(mu_z1, log_sigma_z1)
rec_loss_z1 = 0
classifier_loss = 0
kldz2 = 0
rec_loss_z2 = 0
log_y_hat_rec_loss = 0
class_topic_rec_loss = 0
if not train:
### for discriminator, we only use mean
z1 = mu_z1
y_hat_logis = self.xy_classifier(z1)
log_probz_1 = self.x_only_topics(z1)
y_hat = torch.softmax(y_hat_logis, dim=-1)
log_prob_class_topic = self.class_topics(y_hat)
#y = y_hat_logis
for i in range(n_samples):
if train:
z1 = torch.zeros_like(mu_z1).normal_() * torch.exp(log_sigma_z1) + mu_z1
z1 = self.h_to_z(z1)
log_probz_1 = self.x_only_topics(z1)
y_hat_logis = self.xy_classifier(z1)
y_hat = torch.softmax(y_hat_logis, dim=-1)
log_prob_class_topic = self.class_topics(y_hat)
classifier_loss += self.class_criterion(y_hat_logis, true_y_ids)
y_hat_h = torch.cat((hidden, y_hat), dim=-1)
x_y_hidden = self.x_y_hidden(y_hat_h)
mu_z2 = self.mu_z2(x_y_hidden)
log_sigma_z2 = self.log_sigma_z2(x_y_hidden)
z2 = torch.zeros_like(mu_z2).normal_() * torch.exp(log_sigma_z2) + mu_z2
y_hat_z = torch.cat((z2, y_hat), dim=-1)
topic = self.z_y_hidden(y_hat_z)
log_prob_z2 = self.xy_topics(topic)
y_hat_rec = self.z2y_classifier(topic)
log_y_hat_rec = torch.log_softmax(y_hat_rec, dim=-1)
rec_loss_z1 = rec_loss_z1-(log_probz_1 * bow).sum(dim=-1)
kldz2 += kld(mu_z2, log_sigma_z2)
rec_loss_z2 = rec_loss_z2 - (log_prob_z2 * bow).sum(dim=-1)
#log_y_hat_rec_loss = log_y_hat_rec_loss - (log_y_hat_rec*true_y).sum(dim=-1)
log_y_hat_rec_loss = log_y_hat_rec_loss - (log_y_hat_rec*y_hat).sum(dim=-1)
class_topic_rec_loss = class_topic_rec_loss - (log_prob_class_topic*bow).sum(dim=-1)
rec_loss_z1 = rec_loss_z1/n_samples
#print(rec_loss_z1.shape)
classifier_loss = classifier_loss/n_samples
kldz2 = kldz2/n_samples
rec_loss_z2 = rec_loss_z2/n_samples
log_y_hat_rec_loss = log_y_hat_rec_loss/n_samples
class_topic_rec_loss = class_topic_rec_loss/n_samples
elbo_z1 = kldz1 + rec_loss_z1
#print(elbo_z1.shape)
#elbo_z1 = elbo_z1.sum()
elbo_z2 = kldz2 + rec_loss_z2 + log_y_hat_rec_loss
#print(elbo_z2)
#elbo_z2 = elbo_z2.sum()
#class_topic_rec_loss = class_topic_rec_loss.sum()
classifier_loss = classifier_loss
total_loss = elbo_z1.sum() + elbo_z2.sum() + class_topic_rec_loss.sum() + classifier_loss*self.banlance_lambda*self.classification_loss_lambda
y = {
'loss': total_loss,
'elbo_xy': elbo_z2,
'rec_loss': rec_loss_z2,
'kld': kldz2,
'cls_loss': classifier_loss,
'class_topic_loss': class_topic_rec_loss,
'y_hat': y_hat_logis,
'elbo_x': elbo_z1
}
####################################################################################################################################################
# else:
# z1 = mu_z1
# y_hat_logis = self.xy_classifier(z1)
# y_hat = torch.softmax(y_hat_logis, dim=-1)
# y = y_hat_logis
#
#
# y_hat_h = torch.cat((hidden, y_hat), dim=-1)
# x_y_hidden = self.x_y_hidden(y_hat_h)
# mu_z2 = self.mu_z2(x_y_hidden)
# log_sigma_z2 = self.log_sigma_z2(x_y_hidden)
# z2 = torch.zeros_like(mu_z2).normal_() * torch.exp(log_sigma_z2) + mu_z2
#
# kldz2 = kld(mu_z2, log_sigma_z2)
# log_prob_z2 = self.xy_topics(z2)
# y_hat_rec = self.z2y_classifier(z2)
# log_y_hat_rec = torch.log_softmax(y_hat_rec, dim=-1)
#
#
return y, None
def reset_parameters(self):
init.zeros_(self.log_sigma_z1.weight)
init.zeros_(self.log_sigma_z1.bias)
init.zeros_(self.log_sigma_z2.weight)
init.zeros_(self.log_sigma_z2.bias)
def get_topics(self):
return self.xy_topics.get_topics()
def get_class_topics(self):
return self.class_topics.get_topics()
def get_x_only_topics(self):
return self.x_only_topics.get_topics()
| 6,843 | 35.795699 | 150 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/models/bertSimple.py
|
from transformers import BertModel
from .miscLayer import BERT_Embedding, CLSAW_TopicModel_Base, WVHidden
import os
import torch.nn.functional as F
import torch
import torch.nn as nn
class BERT_Simple(CLSAW_TopicModel_Base):
def __init__(self, config, **kwargs):
super().__init__(config=config)
self.bert_embedding = BERT_Embedding(config)
bert_dim = self.bert_embedding.bert_dim
self.hidden_dim = bert_dim
self.hidden2 = WVHidden(self.hidden_dim, self.z_dim)
self.layer_output = torch.nn.Linear(self.z_dim, self.n_classes)
#self.layer_output = torch.nn.Linear(bert_dim, self.n_classes)
def forward(self, x, mask=None, pre_embd=False):
if pre_embd:
bert_rep = x
else:
bert_rep = self.bert_embedding(x, mask)
bert_rep = bert_rep[0]
bert_rep = bert_rep[:,0]
#hidden = self.hidden1(bert_rep)
hidden = bert_rep
hidden = self.hidden2(hidden)
out = self.layer_output(hidden)
y = {
'y_hat':out
}
return y
| 1,100 | 25.853659 | 71 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/models/bertPure.py
|
from transformers import BertModel
from .miscLayer import BERT_Embedding, CLSAW_TopicModel_Base, WVHidden
import os
import torch.nn.functional as F
import torch
import torch.nn as nn
class BERT_Simple(CLSAW_TopicModel_Base):
def __init__(self, config, **kwargs):
super().__init__(config=config)
self.bert_embedding = BERT_Embedding(config)
bert_dim = self.bert_embedding.bert_dim
self.hidden_dim = bert_dim
#self.hidden2 = WVHidden(self.hidden_dim, self.z_dim)
#self.layer_output = torch.nn.Linear(self.z_dim, self.n_classes)
self.layer_output = torch.nn.Linear(bert_dim, self.n_classes)
def forward(self, x, mask=None, pre_embd=False):
if pre_embd:
bert_rep = x
else:
bert_rep = self.bert_embedding(x, mask)
bert_rep = bert_rep[0]
bert_rep = bert_rep[:,0]
#hidden = self.hidden1(bert_rep)
hidden = bert_rep
#hidden = self.hidden2(hidden)
out = self.layer_output(hidden)
y = {
'y_hat':out
}
return y
| 1,102 | 25.902439 | 72 |
py
|
CANTM
|
CANTM-main/GateMIcateLib/models/NVDM.py
|
import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
import math
from .miscLayer import BERT_Embedding, WVHidden, WVClassifier, Identity, Topics, kld, CLSAW_TopicModel_Base
class NVDM(CLSAW_TopicModel_Base):
def __init__(self, config, vocab_dim=None):
super().__init__(config=config)
default_config = {}
self.bert_embedding = BERT_Embedding(config)
bert_dim = self.bert_embedding.bert_dim
if self.banlance_loss:
self.banlance_lambda = float(math.ceil(vocab_dim/self.n_classes))
else:
self.banlance_lambda = 1
#self.wv_hidden = WVHidden(bert_dim, self.hidden_dim)
self.hidden_dim = bert_dim
##############M1###########################################
self.mu_z1 = nn.Linear(self.hidden_dim, self.z_dim)
self.log_sigma_z1 = nn.Linear(self.hidden_dim, self.z_dim)
self.x_only_topics = Topics(self.z_dim, vocab_dim)
#self.xy_classifier = WVClassifier(self.z_dim, self.n_classes)
#self.class_criterion = nn.CrossEntropyLoss()
#############M2############################################
#self.hidden_y_dim = self.hidden_dim + self.n_classes
#self.z_y_dim = self.z_dim + self.n_classes
#self.x_y_hidden = WVHidden(self.hidden_y_dim, self.hidden_dim)
#self.z_y_hidden = WVHidden(self.z_y_dim, self.ntopics)
#self.mu_z2 = nn.Linear(self.hidden_dim, self.z_dim)
#self.log_sigma_z2 = nn.Linear(self.hidden_dim, self.z_dim)
#self.xy_topics = Topics(self.ntopics, vocab_dim)
#self.z2y_classifier = WVClassifier(self.ntopics, self.n_classes)
############################################################
self.h_to_z = Identity()
#self.class_topics = Topics(self.n_classes, vocab_dim)
self.reset_parameters()
def forward(self,x, mask=None, n_samples=1, bow=None, train=False, true_y=None, pre_embd=False, true_y_ids=None):
#print(true_y.shape)
if pre_embd:
bert_rep = x
else:
bert_rep = self.bert_embedding(x, mask)
bert_rep = bert_rep[0]
atted = bert_rep[:,0]
#hidden = self.wv_hidden(atted)
hidden = atted
mu_z1 = self.mu_z1(hidden)
log_sigma_z1 = self.log_sigma_z1(hidden)
kldz1 = kld(mu_z1, log_sigma_z1)
rec_loss_z1 = 0
classifier_loss = 0
kldz2 = 0
rec_loss_z2 = 0
log_y_hat_rec_loss = 0
class_topic_rec_loss = 0
for i in range(n_samples):
z1 = torch.zeros_like(mu_z1).normal_() * torch.exp(log_sigma_z1) + mu_z1
z1 = self.h_to_z(z1)
log_probz_1 = self.x_only_topics(z1)
rec_loss_z1 = rec_loss_z1-(log_probz_1 * bow).sum(dim=-1)
rec_loss_z1 = rec_loss_z1/n_samples
elbo_z1 = kldz1 + rec_loss_z1
total_loss = elbo_z1.sum()
y_hat_logis = torch.zeros(x.shape[0], self.n_classes)
elbo_z2 = torch.zeros_like(elbo_z1)
classifier_loss = torch.tensor(0)
y = {
'loss': total_loss,
'elbo_xy': elbo_z2,
'rec_loss': rec_loss_z2,
'kld': kldz2,
'cls_loss': classifier_loss,
'class_topic_loss': class_topic_rec_loss,
'y_hat': y_hat_logis,
'elbo_x': elbo_z1
}
return y, None
def reset_parameters(self):
init.zeros_(self.log_sigma_z1.weight)
init.zeros_(self.log_sigma_z1.bias)
def get_topics(self):
return self.x_only_topics.get_topics()
def get_class_topics(self):
return self.x_only_topics.get_topics()
def get_x_only_topics(self):
return self.x_only_topics.get_topics()
| 3,804 | 31.801724 | 117 |
py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.