Commit d7f785ec by Jigyasa Watwani

working extend code

parent b4081442
...@@ -5,15 +5,15 @@ ...@@ -5,15 +5,15 @@
"viscosity": 1, "viscosity": 1,
"zero_rho_boundary": true, "zero_rho_boundary": true,
"friction": 1.0, "friction": 1.0,
"lamda": -0.1, "lamda": 1,
"diffusion_rho": 0.1, "diffusion_rho": 0.1,
"turnover_rho": 10.0, "turnover_rho": 1,
"active_death": false, "active_death": false,
"active_stress_setpoint": 1, "active_stress_setpoint": 3,
"average_rho": 1.0, "average_rho": 1.0,
"saturation_rho": 1.0, "saturation_rho": 1.0,
"noise_level": 0.0, "noise_level": 0.0,
"timestep": 0.001, "timestep": 0.01,
"savetime": 0.1, "savetime": 0.1,
"maxtime": 70.0 "maxtime": 1.0
} }
\ No newline at end of file
...@@ -10,8 +10,7 @@ import numpy as np ...@@ -10,8 +10,7 @@ import numpy as np
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('-j','--jsonfile', help='data file', parser.add_argument('-j','--jsonfile', help='data file',
default='parameters.json') default='parameters.json')
parser.add_argument('-t','--time', help='time to run', type=float, parser.add_argument('-t','--time', help='time to run', type=float)
default=100)
args = parser.parse_args() args = parser.parse_args()
assert os.path.isfile(args.jsonfile), '%s file not found' % args.jsonfile assert os.path.isfile(args.jsonfile), '%s file not found' % args.jsonfile
...@@ -19,68 +18,61 @@ with open(args.jsonfile) as jsonFile: ...@@ -19,68 +18,61 @@ with open(args.jsonfile) as jsonFile:
parameters = json.load(jsonFile) parameters = json.load(jsonFile)
if args.jsonfile=='parameters.json': if args.jsonfile=='parameters.json':
extend=False extend = False
print('Fresh run...') print('Fresh run...')
timestamp = datetime.datetime.now().strftime("%d%m%y-%H%M%S") timestamp = datetime.datetime.now().strftime("%d%m%y-%H%M%S")
parameters['timestamp'] = timestamp parameters['timestamp'] = timestamp
parametersFile = timestamp+'_parameters.json' parametersFile = timestamp + '_parameters.json'
initu=None initu = None
initrho=None initrho = None
oldMaxTime=0.0 initTime = 0.0
mesh = None
else: else:
# extend=True extend = True
# print('Extending run %s...' % parameters['timestamp']) print('Extending run %s...' % parameters['timestamp'])
# parametersFile = args.jsonfile parametersFile = args.jsonfile
# # read geometry from h5 file savesteps = int(parameters['maxtime']/parameters['savetime'])
# var = 'density'
# h5 = h5py.File( '%s_%s.h5' % (parameters['timestamp'], var))
# # should be in the loop if remeshing mesh = df.IntervalMesh(parameters['resolution'],
# savesteps = int(parameters['maxtime']/parameters['savetime']) - parameters['system_size']/2,
parameters['system_size']/2)
# geometry = np.array(h5['%s/%s_%d/mesh/geometry'%(var,var,savesteps)]) print('Before reading geometry the mesh:', mesh.coordinates()[:,0])
# # print(geometry[:,0])
# # geometry, zeros= np.dsplit(geometry, 2)
# mesh = df.IntervalMesh(parameters['resolution'],
# - parameters['system_size']/2,
# parameters['system_size']/2)
# print(mesh.coordinates())
# # Read data # read geometry from h5 file
var = 'density'
# uFile = df.XDMFFile( h5 = h5py.File( '%s_%s.h5' % (parameters['timestamp'], var,), 'a')
# '%s_displacement.xdmf' % parameters['timestamp']) # print("Name of the file: ", h5.filename)
# rhoFile = df.XDMFFile( # print('Details of the h5 file:', [(i,j) for i,j in h5.attrs.items()])
# '%s_density.xdmf' % parameters['timestamp']) print(f'var {var}, savesteps {savesteps}')
geometry = np.array(h5['%s/%s_%d/mesh/geometry'%(var,var, savesteps)])
mesh.coordinates()[:,0] = geometry[:,0]
print('After reading geometry the mesh:',mesh.coordinates()[:,0])
# # Reading data # Read data
# print('Reading data...') SFS = df.FunctionSpace(mesh, 'P', 1)
# mesh.coordinates()[:,0] = geometry[:,0] VFS = df.VectorFunctionSpace(mesh, 'P', 1)
# print(mesh.coordinates()) initu, initrho = df.Function(VFS), df.Function(SFS)
# SFS = df.FunctionSpace(mesh, 'P', 1) uFile = df.XDMFFile('%s_displacement.xdmf' % parameters['timestamp'])
# VFS = df.VectorFunctionSpace(mesh, 'P', 1) rhoFile = df.XDMFFile('%s_density.xdmf' % parameters['timestamp'])
# initu, initrho = df.Function(VFS), df.Function(SFS) uFile.read_checkpoint(initu, 'displacement', savesteps)
rhoFile.read_checkpoint(initrho, 'density', savesteps)
# uFile.read_checkpoint(initu, 'displacement', savesteps) uFile.close()
# rhoFile.read_checkpoint(initrho, 'density', savesteps) rhoFile.close()
# uFile.close() initTime = parameters['maxtime']
# rhoFile.close() print('old max time=', initTime)
parameters['maxtime'] = args.time
tissue = Tissue(parameters, mesh)
# oldMaxTime = parameters['maxtime'] tissue.solve(initu, initrho, initTime, extend)
tissue = Tissue(parameters)
tissue.solve(initu, initrho, oldMaxTime)
if extend: if extend:
parameters['maxtime'] = oldMaxTime + parameters['maxtime'] parameters['maxtime'] = initTime + parameters['maxtime']
with open(parametersFile, "w") as jsonFile: with open(parametersFile, "w") as jsonFile:
json.dump(parameters, jsonFile, indent=4, sort_keys=True) json.dump(parameters, jsonFile, indent=4, sort_keys=True)
from viz_tissue import visualize # from viz_tissue import visualize
visualize(parameters, DIR='') # visualize(parameters, DIR='')
\ No newline at end of file \ No newline at end of file
import numpy as np import numpy as np
import dolfin as df import dolfin as df
import progressbar import progressbar
import os
import h5py
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from tempfile import TemporaryDirectory
import vedo as vd
from matplotlib.animation import FuncAnimation
from mpl_toolkits.axes_grid1 import make_axes_locatable
df.set_log_level(df.LogLevel.ERROR) df.set_log_level(df.LogLevel.ERROR)
df.parameters['form_compiler']['optimize'] = True df.parameters['form_compiler']['optimize'] = True
class Tissue(object): class Tissue(object):
def __init__(self, parameters): def __init__(self, parameters, mesh=None):
# read in parameters # read in parameters
for key in parameters: for key in parameters:
setattr(self, key, parameters[key]) setattr(self, key, parameters[key])
self.mesh = df.Mesh() # if no mesh is given
self.mesh = df.IntervalMesh(self.resolution, if mesh is None:
self.mesh = df.IntervalMesh(self.resolution,
-self.system_size/2, -self.system_size/2,
self.system_size/2) self.system_size/2)
else:
self.mesh = mesh
print('Mesh passed as initial condition:', self.mesh.coordinates()[:,0])
scalar_element = df.FiniteElement('P', self.mesh.ufl_cell(), 1) scalar_element = df.FiniteElement('P', self.mesh.ufl_cell(), 1)
vector_element = df.VectorElement('P', self.mesh.ufl_cell(), 1) vector_element = df.VectorElement('P', self.mesh.ufl_cell(), 1)
...@@ -71,10 +67,9 @@ class Tissue(object): ...@@ -71,10 +67,9 @@ class Tissue(object):
return (self.passive_stress(u, v) + self.active_stress(rho)) return (self.passive_stress(u, v) + self.active_stress(rho))
def diffusion_reaction_rho(self, rho, trho): def diffusion_reaction_rho(self, rho, trho):
# NOTE: implement a step-function of density in the reaction
return (self.diffusion_rho * df.inner(df.nabla_grad(rho), return (self.diffusion_rho * df.inner(df.nabla_grad(rho),
df.nabla_grad(trho)) df.nabla_grad(trho))
- self.turnover_rho * df.inner(rho*(1 - rho/self.average_rho), # logistic growth, no need to implement step function - self.turnover_rho * df.inner(rho*(1 - rho/self.average_rho),
trho) trho)
) )
...@@ -91,7 +86,6 @@ class Tissue(object): ...@@ -91,7 +86,6 @@ class Tissue(object):
base_rho = 0.0 base_rho = 0.0
else: else:
base_rho = self.average_rho base_rho = self.average_rho
# rho0 = df.interpolate(df.Constant(self.average_rho),self.function_space.sub(2).collapse())
rho0 = df.interpolate(df.Expression( rho0 = df.interpolate(df.Expression(
'base_rho + 0.1 * cos(PI*x[0]/L)*cos(PI*x[0]/L)', 'base_rho + 0.1 * cos(PI*x[0]/L)*cos(PI*x[0]/L)',
L=self.system_size, L=self.system_size,
...@@ -138,7 +132,7 @@ class Tissue(object): ...@@ -138,7 +132,7 @@ class Tissue(object):
self.form = (uform + vform + rhoform) * df.dx self.form = (uform + vform + rhoform) * df.dx
def solve(self, initu=None, initrho=None, inittime=None): def solve(self, initu=None, initrho=None, initTime=0, extend=False):
self.uFile = df.XDMFFile( self.uFile = df.XDMFFile(
'%s_displacement.xdmf' % self.timestamp) '%s_displacement.xdmf' % self.timestamp)
self.vFile = df.XDMFFile( self.vFile = df.XDMFFile(
...@@ -150,31 +144,43 @@ class Tissue(object): ...@@ -150,31 +144,43 @@ class Tissue(object):
self.setup_weak_forms() self.setup_weak_forms()
# time-variables # time-variables
self.time = inittime self.time = initTime
savesteps = int(self.savetime/self.timestep) savesteps = int(self.savetime/self.timestep)
maxsteps = int(self.maxtime/self.timestep) maxsteps = int(self.maxtime/self.timestep)
u, v, rho = self.function0.split(deepcopy=True)
self.uFile.write_checkpoint(u, 'displacement', self.time) # if this is a fresh run, write the initial condition
self.vFile.write_checkpoint(v, 'velocity', self.time) if not extend:
self.rhoFile.write_checkpoint(rho, 'density', self.time) u, v, rho = self.function0.split(deepcopy=True)
self.uFile.write_checkpoint(u, 'displacement', self.time)
self.vFile.write_checkpoint(v, 'velocity', self.time)
self.rhoFile.write_checkpoint(rho, 'density', self.time)
for steps in progressbar.progressbar(range(1, maxsteps + 1)): for steps in progressbar.progressbar(range(1, maxsteps + 1)):
print(self.time)
df.solve(self.form == 0, self.function, self.bc) df.solve(self.form == 0, self.function, self.bc)
self.function0.assign(self.function) self.function0.assign(self.function)
self.time += self.timestep self.time += self.timestep
u, v, rho = self.function0.split(deepcopy=True) u, v, rho = self.function0.split(deepcopy=True)
if steps % savesteps == 0: if steps % savesteps == 0:
# if not extend:
self.uFile.write_checkpoint(u, 'displacement', self.uFile.write_checkpoint(u, 'displacement',
self.time, append=True) self.time, append=True)
self.vFile.write_checkpoint(v, 'velocity', self.vFile.write_checkpoint(v, 'velocity',
self.time, append=True) self.time, append=True)
self.rhoFile.write_checkpoint(rho, 'density', self.rhoFile.write_checkpoint(rho, 'density',
self.time, append=True) self.time, append=True)
# move mesh # move mesh
dr = df.project(v*self.timestep, self.function_space.sub(0).collapse()) dr = df.project(v*self.timestep, self.function_space.sub(0).collapse())
df.ALE.move(self.mesh, dr) df.ALE.move(self.mesh, dr)
print('After solving till new maxtime, the mesh coordinates:',self.mesh.coordinates()[:,0])
self.uFile.close() self.uFile = None
self.vFile.close() self.vFile = None
self.rhoFile.close() self.rhoFile = None
# self.uFile.closed
# self.vFile.closed
# self.rhoFile.closed
import dolfin as df import dolfin as df
import numpy as np import numpy as np
import vedo as vd
import os import os
import h5py import h5py
from matplotlib.widgets import Slider from matplotlib.widgets import Slider
...@@ -10,28 +9,34 @@ from tempfile import TemporaryDirectory ...@@ -10,28 +9,34 @@ from tempfile import TemporaryDirectory
def visualize(params, DIR=''): def visualize(params, DIR=''):
savesteps = int(params['maxtime']/params['savetime']) savesteps = int(params['maxtime']/params['savetime'])
times = np.arange(savesteps+1) * params['savetime'] times = np.arange(savesteps+1) * params['savetime']
print(times)
# Read mesh geometry from h5 file # Read mesh geometry from h5 file
var = 'density' var = 'density'
h5 = h5py.File(os.path.join(DIR, h5 = h5py.File(os.path.join(DIR,
'%s_%s.h5' % (params['timestamp'], var)), "r") '%s_%s.h5' % (params['timestamp'], var)), "r")
# should be in the loop if remeshing # should be in the loop if remeshing
topology = np.array(h5['%s/%s_0/mesh/topology'%(var,var)]) topology = np.array(h5['%s/%s_0/mesh/topology'%(var,var)])
geometry = [] geometry = []
for i in range(len(times)): for i in progressbar.progressbar(range(len(times))):
print(times[i])
geometry.append(np.array(h5['%s/%s_%d/mesh/geometry'%(var,var,i)])) geometry.append(np.array(h5['%s/%s_%d/mesh/geometry'%(var,var,i)]))
h5.close() h5.close()
geometry = np.array(geometry) geometry = np.array(geometry)
geometry, zeros= np.dsplit(geometry, 2) geometry, zeros = np.dsplit(geometry, 2)
mesh = df.IntervalMesh(params['resolution'], mesh = df.IntervalMesh(params['resolution'],
- params['system_size']/2, - params['system_size']/2,
params['system_size']/2) params['system_size']/2)
# Read data # Read data
u = np.zeros((len(times), mesh.num_vertices(), 1)) u = np.zeros((len(times), mesh.num_vertices(), 1))
v = np.zeros_like(u) v = np.zeros_like(u)
rho = np.zeros((len(times), mesh.num_vertices())) rho = np.zeros((len(times), mesh.num_vertices()))
elastic_stress = np.zeros((len(times), mesh.num_vertices()))
viscous_stress = np.zeros_like(elastic_stress)
active_stress = np.zeros_like(elastic_stress)
uFile = df.XDMFFile(os.path.join(DIR, uFile = df.XDMFFile(os.path.join(DIR,
'%s_displacement.xdmf' % params['timestamp'])) '%s_displacement.xdmf' % params['timestamp']))
...@@ -51,27 +56,47 @@ def visualize(params, DIR=''): ...@@ -51,27 +56,47 @@ def visualize(params, DIR=''):
uFile.read_checkpoint(ui, 'displacement', steps) uFile.read_checkpoint(ui, 'displacement', steps)
vFile.read_checkpoint(vi, 'velocity', steps) vFile.read_checkpoint(vi, 'velocity', steps)
rhoFile.read_checkpoint(rhoi, 'density', steps) rhoFile.read_checkpoint(rhoi, 'density', steps)
u_vec = ui.compute_vertex_values(mesh) u_vec = ui.compute_vertex_values(mesh)
u[steps] = u_vec.reshape(1, int(u_vec.shape[0])).T u[steps] = u_vec.reshape(1, int(u_vec.shape[0])).T
v_vec = vi.compute_vertex_values(mesh) v_vec = vi.compute_vertex_values(mesh)
v[steps] = v_vec.reshape(1, int(v_vec.shape[0])).T v[steps] = v_vec.reshape(1, int(v_vec.shape[0])).T
rho[steps] = rhoi.compute_vertex_values(mesh) rho[steps] = rhoi.compute_vertex_values(mesh)
e_stress = params['elasticity'] * ui.dx(0)
e_stress = df.project(e_stress, VFS)
elastic_stress[steps] = e_stress.compute_vertex_values(mesh)
v_stress = params['viscosity'] * vi.dx(0)
v_stress = df.project(v_stress, VFS)
viscous_stress[steps] = v_stress.compute_vertex_values(mesh)
a_stress = -params['lamda'] * rhoi/(rhoi + params['saturation_rho'])
a_stress = df.project(a_stress, SFS)
active_stress[steps] = a_stress.compute_vertex_values(mesh)
uFile.close() uFile.close()
vFile.close() vFile.close()
rhoFile.close() rhoFile.close()
# interactive plot # interactive plot
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(8,8)) plt.rcParams.update({'font.size': 15})
fig, axes = plt.subplots(3, 1, sharex=True, figsize=(8,8))
axes[-1].set_xlabel(r'$x$') axes[-1].set_xlabel(r'$x$')
axes[0].set_ylabel(r'$\rho/\rho_0$') axes[0].set_ylabel(r'$\rho/\rho_0$')
axes[1].set_ylabel(r'$v/v_0$') axes[1].set_ylabel(r'$v/v_0$')
plt.rc('font', size=14) axes[2].set_ylabel(r'$u/u_0$')
axes[0].set_xlim(np.min(geometry), np.max(geometry)) axes[0].set_xlim(np.min(geometry), np.max(geometry))
axes[0].set_ylim(np.min(rho), np.max(rho)) axes[0].set_ylim(np.min(rho)-0.1, np.max(rho)+0.1)
axes[1].set_ylim(np.min(v), np.max(v)) axes[1].set_ylim(np.min(v)-0.1, np.max(v)+0.1)
axes[2].set_ylim(np.min(u)-0.1, np.max(u)+0.1)
rhoplot, = axes[0].plot(geometry[0], rho[0], 'g-', ms=3) rhoplot, = axes[0].plot(geometry[0], rho[0], 'g-', ms=3)
velplot, = axes[1].plot(geometry[0], v[0], 'r-', ms=3) velplot, = axes[1].plot(geometry[0], v[0], 'r-', ms=3)
uplot, = axes[2].plot(geometry[0], u[0], 'b-', ms=3)
def update(value): def update(value):
ti = np.abs(times-value).argmin() ti = np.abs(times-value).argmin()
...@@ -79,6 +104,8 @@ def visualize(params, DIR=''): ...@@ -79,6 +104,8 @@ def visualize(params, DIR=''):
rhoplot.set_xdata(geometry[ti]) rhoplot.set_xdata(geometry[ti])
velplot.set_ydata(v[ti]) velplot.set_ydata(v[ti])
velplot.set_xdata(geometry[ti]) velplot.set_xdata(geometry[ti])
uplot.set_ydata(u[ti])
uplot.set_xdata(geometry[ti])
plt.draw() plt.draw()
sax = plt.axes([0.1, 0.92, 0.7, 0.02]) sax = plt.axes([0.1, 0.92, 0.7, 0.02])
...@@ -88,11 +115,63 @@ def visualize(params, DIR=''): ...@@ -88,11 +115,63 @@ def visualize(params, DIR=''):
slider.drawon = False slider.drawon = False
slider.on_changed(update) slider.on_changed(update)
# plt.show() # plt.show()
print('Saving movie-...')
FPS = 50
movFile = os.path.join(DIR, '%s_fields.mov' % params['timestamp'])
fps = float(FPS)
command = "ffmpeg -y -r"
options = "-b:v 3600k -qscale:v 4 -vcodec mpeg4"
tmp_dir = TemporaryDirectory()
get_filename = lambda x: os.path.join(tmp_dir.name, x)
for tt in progressbar.progressbar(range(len(times))):
slider.set_val(times[tt])
fr = get_filename("%03d.png" % tt)
fig.savefig(fr, facecolor=fig.get_facecolor(), dpi=100)
os.system(command + " " + str(fps)
+ " -i " + tmp_dir.name + os.sep
+ "%03d.png " + options + " " + movFile)
tmp_dir.cleanup()
# plotting the stresses
fig2, axes1 = plt.subplots(3, 1, sharex=True, figsize=(8,8))
axes1[-1].set_xlabel(r'$x$')
axes1[2].set_ylabel('Elastic stress')
axes1[1].set_ylabel('Viscous stress')
axes1[0].set_ylabel('Active stress')
axes1[0].set_xlim(np.min(geometry), np.max(geometry))
axes1[2].set_ylim(np.min(elastic_stress)-0.1, np.max(elastic_stress)+0.1)
axes1[1].set_ylim(np.min(viscous_stress)-0.1, np.max(viscous_stress)+0.1)
axes1[0].set_ylim(np.min(active_stress)-0.1, np.max(active_stress)+0.1)
e_stress_plot, = axes1[2].plot(geometry[0], elastic_stress[0], 'g-', ms=3)
v_stress_plot, = axes1[1].plot(geometry[0], viscous_stress[0], 'r-', ms=3)
a_stress_plot, = axes1[0].plot(geometry[0], -active_stress[0], 'b-', ms=3)
def update2(value):
ti = np.abs(times-value).argmin()
e_stress_plot.set_ydata(elastic_stress[ti])
e_stress_plot.set_xdata(geometry[ti])
v_stress_plot.set_ydata(viscous_stress[ti])
v_stress_plot.set_xdata(geometry[ti])
a_stress_plot.set_ydata(active_stress[ti])
a_stress_plot.set_xdata(geometry[ti])
plt.draw()
sax = plt.axes([0.1, 0.92, 0.7, 0.02])
slider = Slider(sax, r'$t/\tau$', min(times), max(times),
valinit=min(times), valfmt='%3.1f',
fc='#999999')
slider.drawon = False
slider.on_changed(update2)
# plt.show()
# make movie # make movie
print('Saving movie-...') print('Saving movie-...')
FPS = 50 FPS = 50
movFile = os.path.join(DIR, '%s.mov' % params['timestamp']) movFile = os.path.join(DIR, '%s_stresses.mov' % params['timestamp'])
fps = float(FPS) fps = float(FPS)
command = "ffmpeg -y -r" command = "ffmpeg -y -r"
options = "-b:v 3600k -qscale:v 4 -vcodec mpeg4" options = "-b:v 3600k -qscale:v 4 -vcodec mpeg4"
...@@ -101,7 +180,7 @@ def visualize(params, DIR=''): ...@@ -101,7 +180,7 @@ def visualize(params, DIR=''):
for tt in progressbar.progressbar(range(len(times))): for tt in progressbar.progressbar(range(len(times))):
slider.set_val(times[tt]) slider.set_val(times[tt])
fr = get_filename("%03d.png" % tt) fr = get_filename("%03d.png" % tt)
fig.savefig(fr, facecolor=fig.get_facecolor(), dpi=100) fig2.savefig(fr, facecolor=fig2.get_facecolor(), dpi=100)
os.system(command + " " + str(fps) os.system(command + " " + str(fps)
+ " -i " + tmp_dir.name + os.sep + " -i " + tmp_dir.name + os.sep
+ "%03d.png " + options + " " + movFile) + "%03d.png " + options + " " + movFile)
...@@ -119,6 +198,15 @@ def visualize(params, DIR=''): ...@@ -119,6 +198,15 @@ def visualize(params, DIR=''):
# plt.show() # plt.show()
np.save('%s_length.npy' %params['timestamp'], length) np.save('%s_length.npy' %params['timestamp'], length)
fig2, ax2 = plt.subplots(1, 1, figsize=(8, 8))
ax2.set_xlabel('$t$')
ax2.set_ylabel('$L(t)$')
# ax2.set_xlim(np.min(times), np.max(times))
# ax2.set_ylim(np.min(length), np.max(length)+1)
ax2.loglog(times, length)
plt.savefig("%s_loglog.png" %params['timestamp'])
# plt.show()
if __name__ == '__main__': if __name__ == '__main__':
import argparse, json import argparse, json
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment