Пример #1
0
def main():
	"""Analyses the vorticity given a case."""
	# parse the command-line
	args = read_inputs()

	folder = args.folder	# path of the case

	# read parameters of the simulation
	nt, start_step, nsave, dt = readSimulationParameters(folder)

	# read and generate the computational mesh
	nx, ny, dx, dy, _, yu, xv, _ = readGridData(folder)
	
	# number of saved points
	save_points = int( (nt-start_step)/nsave )

	T = 10.0	# total time of the simulation
	h = dx[0]	# uniform cell-width

	# initialization
	total_vorticity = np.empty(save_points, dtype=float)
	circulation = np.empty(save_points, dtype=float)
	time = np.empty(save_points, dtype=float)

	# time-loop
	ite = start_step + nsave
	idx = 0
	while ite < nt+1:
		time[idx] = ite*dt
		# read the vorticity
		vort_file = '%s/%07d/vorticity' % (folder, ite)
		with open(vort_file, 'r') as infile:
			vorticity = np.loadtxt(infile, dtype=float, usecols=(2,))
		# calculate the total vorticity
		total_vorticity[idx] = h**2*vorticity.sum()
		# calculate the theoretical circulation
		circulation[idx] = -math.sin(math.pi*time[idx]/T)
		idx += 1
		ite += nsave

	# plot the total vorticity and theretical circulation
	plt.figure()
	plt.grid(True)
	plt.xlabel('Time', fontsize=16)
	plt.ylabel('Total circulation', fontsize=16)
	plt.plot(time, total_vorticity, label='Total vorticity',
			 color='r', ls='.', marker='o', markersize=10)
	plt.plot(time, circulation, label='Theoretical circulation',
			 color='b', ls='-', lw=2)
	plt.xlim(0, 80)
	plt.ylim(-1.5, 1.5)
	plt.title('Comparison of Total Vorticity and Theoretical Circulation '
			  'at Re=10,000')
	plt.legend(loc='best', prop={'size': 16})
	plt.savefig('%s/total_vorticity.png' % folder)
	if args.show:
		plt.show()
Пример #2
0
def main():
    """Plots the contour of vorticity at every time saved."""
    # parse the command-line
    args = read_inputs()

    folder = args.folder  # name of the folder

    # read the parameters of the simulation
    nt, start_step, nsave, dt = readSimulationParameters(folder)

    # calculate the mesh characteristics
    nx, ny, dx, dy, _, yu, xv, _ = readGridData(folder)

    # calculate appropriate array boundaries
    i_start = np.where(xv >= args.xmin)[0][0]
    i_end = np.where(xv <= args.xmax)[0][-1]
    j_start = np.where(yu >= args.ymin)[0][0]
    j_end = np.where(yu <= args.ymax)[0][-1]

    y = np.zeros(j_end - j_start)
    x = np.zeros(i_end - i_start)
    x[:] = 0.5 * (xv[i_start:i_end] + xv[i_start + 1:i_end + 1])
    y[:] = 0.5 * (yu[j_start:j_end] + yu[j_start + 1:j_end + 1])
    X, Y = np.meshgrid(x, y)

    Omg = np.zeros((j_end - j_start, i_end - i_start))

    # time-loop
    for ite in xrange(start_step + nsave, nt + 1, nsave):
        # read the velocity data at the given time-step
        u, v = readVelocityData(folder, ite, nx, ny, dx, dy)
        if u is None or v is None:
            break

        # calculate the vorticity
        for j in xrange(j_start, j_end):
            Dy = 0.5 * (dy[j] + dy[j + 1])
            for i in xrange(i_start, i_end):
                Dx = 0.5 * (dx[i] + dx[i + 1])
                Omg[j-j_start, i-i_start] = (v[j*nx+i+1] - v[j*nx+i]) / Dx \
                   - (u[(j+1)*(nx-1)+i] - u[j*(nx-1)+i]) / Dy

        CS = plt.contourf(X,
                          Y,
                          Omg,
                          levels=np.linspace(-args.vortlim, args.vortlim,
                                             args.numlevels))
        plt.title("Vorticity @ time = {0}".format(ite * dt))
        plt.colorbar(CS)
        plt.axis([xv[i_start], xv[i_end], yu[j_start], yu[j_end]])
        plt.gca().set_aspect('equal', adjustable='box')
        plt.savefig('%s/o%07d.png' % (folder, ite / nsave))
        plt.clf()
        print "Saved figure {0}".format(ite)

    print 'DONE!'
Пример #3
0
def main():
	"""Plots the contour of velocity (u and v) at every time saved."""
	# parse the command-line
	args = read_inputs()

	folder = args.folder	# name of the folder

	# read the parameters of the simulation
	nt, start_step, nsave, _ = readSimulationParameters(folder)

	# calculate the mesh characteristics
	nx, ny, dx, dy, xu, yu, xv, yv = readGridData(folder)

	# calculate appropriate array boundaries
	i_start = np.where(xu >= args.xmin)[0][0]
	i_end = np.where(xu <= args.xmax)[0][-1]
	j_start = np.where(yu >= args.ymin)[0][0]
	j_end = np.where(yu <= args.ymax)[0][-1]

	x_start = xu[i_start] - dx[i_start]
	x_end   = xu[i_end] + dx[i_end+1]
	y_start = yu[j_start] - dy[j_start]/2.
	y_end   = yu[j_end] + dy[j_end]/2.

	# generate a mesh grid for u- and v- velocities
	Xu, Yu = np.meshgrid(xu, yu)
	Xv, Yv = np.meshgrid(xv, yv)

	for ite in xrange(start_step+nsave, nt+1, nsave):
		print 'iteration %d' % ite
		# read the velocity data at the given time-step
		u, v = readVelocityData(folder, ite, nx, ny, dx, dy)
		if u == None or v == None:
			break

		# plot u-velocity contour
		plt.contour(Xu, Yu, u.reshape((ny, nx-1)),
					levels=np.linspace(-args.u_lim, args.u_lim, 21))
		plt.axis('equal')
		plt.axis([x_start, x_end, y_start, y_end])
		plt.colorbar()
		plt.savefig('%s/u%07d.png' % (folder, ite))
		plt.clf()
	
		# plot v-velocity contour
		plt.contour(Xv, Yv, v.reshape((ny-1, nx)), 
					levels=np.linspace(-args.v_lim, args.v_lim, 21))
		plt.axis('equal')
		plt.axis([x_start, x_end, y_start, y_end])
		plt.colorbar()
		plt.savefig('%s/v%07d.png' % (folder, ite))
		plt.clf()
Пример #4
0
def main():
	"""Plots the contour of vorticity at every time saved."""
	# parse the command-line
	args = read_inputs()

	folder = args.folder	# name of the folder

	# read the parameters of the simulation
	nt, start_step, nsave, _ = readSimulationParameters(folder)

	# calculate the mesh characteristics
	nx, ny, dx, dy, _, yu, xv, _ = readGridData(folder)

	# calculate appropriate array boundaries
	i_start = np.where(xv >= args.xmin)[0][0]
	i_end = np.where(xv <= args.xmax)[0][-1]
	j_start = np.where(yu >= args.ymin)[0][0]
	j_end = np.where(yu <= args.ymax)[0][-1]

	y = np.zeros(j_end-j_start)
	x = np.zeros(i_end-i_start)
	x[:] = 0.5*(xv[i_start:i_end] + xv[i_start+1:i_end+1])
	y[:] = 0.5*(yu[j_start:j_end] + yu[j_start+1:j_end+1])
	X, Y = np.meshgrid(x, y)

	Omg = np.zeros((j_end-j_start, i_end-i_start))

	# time-loop
	for ite in xrange(start_step+nsave, nt+1, nsave):
		# read the velocity data at the given time-step
		u, v = readVelocityData(folder, ite, nx, ny, dx, dy)
		if u == None or v == None:
			break

		# calculate the vorticity
		for j in xrange(j_start, j_end):
			Dy = 0.5 * (dy[j] + dy[j+1])
			for i in xrange(i_start, i_end):
				Dx = 0.5 * (dx[i] + dx[i+1])
				Omg[j-j_start, i-i_start] = (v[j*nx+i+1] - v[j*nx+i]) / Dx \
					  - (u[(j+1)*(nx-1)+i] - u[j*(nx-1)+i]) / Dy

		CS = plt.contour(X, Y, Omg, levels=np.linspace(-args.vortlim, args.vortlim, args.numlevels))
		plt.title("Vorticity")
		plt.colorbar(CS)
		plt.axis([xv[i_start], xv[i_end], yu[j_start], yu[j_end]])
		plt.gca().set_aspect('equal', adjustable='box')
		plt.savefig('{}/o{:0>7}.png'.format(folder,ite))
		plt.clf()
		print "Saved figure {}/O{:0>7}.png".format(folder,ite)
	
	print 'DONE!'
Пример #5
0
def main():
    """Plots the contour of vorticity at every time saved."""
    # parse the command-line
    args = read_inputs()

    folder = args.folder  # name of the folder

    # read the parameters of the simulation
    nt, start_step, nsave, _ = readSimulationParameters(folder)

    # calculate the mesh characteristics
    nx, ny, dx, dy, _, yu, xv, _ = readGridData(folder)

    # calculate appropriate array boundaries
    i_start = np.where(xv >= args.xmin)[0][0]
    i_end = np.where(xv <= args.xmax)[0][-1]
    j_start = np.where(yu >= args.ymin)[0][0]
    j_end = np.where(yu <= args.ymax)[0][-1]

    x = np.zeros(i_end + 1 - i_start)
    y = np.zeros(j_end + 1 - j_start)
    x[:] = xv[i_start:i_end + 1]
    y[:] = yu[j_start:j_end + 1]
    X, Y = np.meshgrid(x, y)

    P = np.zeros((j_end + 1 - j_start, i_end + 1 - i_start))

    # time-loop
    for ite in xrange(start_step + nsave, nt + 1, nsave):
        # read the velocity data at the given time-step
        p = readPressureData(folder, ite, nx, ny)
        p = p.reshape((ny, nx))

        # calculate and write the vorticity
        for j in xrange(j_start, j_end + 1):
            P[j - j_start, :] = p[j, i_start:i_end + 1]

        CS = plt.contourf(X,
                          Y,
                          P,
                          levels=np.linspace(args.plimlow, args.plim,
                                             args.numlevels))
        plt.title("Pressure")
        plt.colorbar(CS)
        plt.axis([xv[i_start], xv[i_end], yu[j_start], yu[j_end]])
        plt.gca().set_aspect('equal', adjustable='box')
        plt.savefig('{0} {1}.png'.format(folder, ite))
        plt.clf()
        print "Saved figure {0} {1}.png".format(folder, ite)

    print 'DONE!'
Пример #6
0
def main():
	"""Plots the contour of vorticity at every time saved."""
	# parse the command-line
	args = read_inputs()

	folder = args.folder	# name of the folder

	# read the parameters of the simulation
	nt, start_step, nsave, _ = readSimulationParameters(folder)

	# calculate the mesh characteristics
	nx, ny, dx, dy, _, yu, xv, _ = readGridData(folder)

	# calculate appropriate array boundaries
	i_start = np.where(xv >= args.xmin)[0][0]
	i_end = np.where(xv <= args.xmax)[0][-1]
	j_start = np.where(yu >= args.ymin)[0][0]
	j_end = np.where(yu <= args.ymax)[0][-1]

	x = np.zeros(i_end+1-i_start)
	y = np.zeros(j_end+1-j_start)
	x[:] = xv[i_start:i_end+1]
	y[:] = yu[j_start:j_end+1]
	X, Y = np.meshgrid(x, y)

	P = np.zeros((j_end+1-j_start, i_end+1-i_start))

	# time-loop
	for ite in xrange(start_step+nsave, nt+1, nsave):
		try:
			# read the velocity data at the given time-step
			p = readPressureData(folder, ite, nx, ny)
			p = p.reshape((ny, nx))

			# calculate and write the vorticity
			for j in xrange(j_start, j_end+1):
				P[j-j_start, :] = p[j, i_start:i_end+1]

			CS = plt.contourf(X, Y, P, levels=np.linspace(args.plimlow, args.plim, args.numlevels))
			plt.title("Pressure")
			plt.colorbar(CS)
			plt.axis([xv[i_start], xv[i_end], yu[j_start], yu[j_end]])
			plt.gca().set_aspect('equal', adjustable='box')
			plt.savefig('{0}p{1:0=5d}.png'.format(folder,ite))
			plt.clf()
			print "Saved figure {0} {1}.png".format(folder,ite)
		except:
			print 'data not found at timestep: ' + str(ite)
	
	print 'DONE!'
Пример #7
0
def main():
	
	#view available fonts
	#for font in font_manager.findSystemFonts():
	#	print font

	try:
		fontpath = '/usr/share/fonts/truetype/msttcorefonts/Georgia.ttf'

		prop = font_manager.FontProperties(fname=fontpath)
		matplotlib.rcParams['font.family'] = prop.get_name()
	except:
		pass
	# Command line options
	parser = argparse.ArgumentParser(description="Calculates the order of convergence.", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
	parser.add_argument("-folder", dest="caseDir", help="folder in which the cases for different mesh sizes are present", default=os.path.expandvars("${CUIBM_DIR}/cases/convergence/cavityRe100/NavierStokes/20x20"))
	parser.add_argument("-tolerance", dest="tolerance", help="folder in which the cases for different mesh sizes are present", default="")
	parser.add_argument("-interpolation_type", dest="interpolation_type", help="the type of interpolation used in the direct forcing method", default="")
	parser.add_argument("-device", dest="device", help="CUDA device number", default="")
	parser.add_argument("-run", dest="runSimulations", help="run the cases if this flag is used", action='store_true', default=False)
	parser.add_argument("-remove_mask", dest="removeMask", help="use values from the entire domain", action='store_true', default=False)
	args = parser.parse_args()

	commandOptions = []
	if args.tolerance:
		commandOptions.extend(["-velocityTol", "{}".format(args.tolerance), "-poissonTol", "{}".format(args.tolerance)])
	if args.interpolation_type:
		commandOptions.extend(["-interpolationType", "{}".format(args.interpolation_type)])
	if args.device:
		commandOptions.extend(["-deviceNumber", "{}".format(args.device)])

	# list of folders from which velocity data is to be obtained
	folders = sorted(os.walk(args.caseDir).next()[1], key=int)
	numFolders = len(folders)

	# run the cases in each of the folders
	if args.runSimulations:
		for folder in folders:
			runCommand = [os.path.expandvars("${CUIBM_DIR}/bin/cuIBM"),
							'-caseFolder', "{}/{}".format(args.caseDir, folder)]
			runCommand.extend(commandOptions)
			print " ".join(runCommand)
			subprocess.call(runCommand)

	# create arrays to store the required values
	U = []
	V = []
	Q = []
	errL2NormU  = np.zeros(numFolders-1)
	errL2NormV  = np.zeros(numFolders-1)
	errL2NormQ  = np.zeros(numFolders-1)
	errLInfNormU  = np.zeros(numFolders-1)
	errLInfNormV  = np.zeros(numFolders-1)
	meshSize = np.zeros(numFolders-1, dtype=int)

	line()
	print "Case directory: {}".format(args.caseDir)
	print "Folders: ",

	stride = 1
	for fIdx, folder in enumerate(folders):
		# path to folder
		folderPath = os.path.expandvars("{}/{}".format(args.caseDir, folder));
		# read simulation information
		nt, _, _, _ = readSimulationParameters(folderPath)

		# read the grid data
		# nx and ny are the number of cells
		# dx and dy are the cell widths
		# xu and yu are the coordinates of the locations where U is calculated
		nx, ny, dx, dy, xu, yu, xv, yv = readGridData(folderPath)
		
		if fIdx==0:
			initialMeshSpacing = dx[0]
		else:
			meshSize[fIdx-1] = nx

		# read velocity data
		u, v = readVelocityData(folderPath, nt, nx, ny, dx, dy)

		if not args.removeMask:
			# read mask
			try:
				mask_u, mask_v = readMask(folderPath, nx, ny)
				u[:] = u[:]*mask_u[:]
				v[:] = v[:]*mask_v[:]
			except:
				pass

		U.append(np.reshape(u, (ny, nx-1))[stride/2::stride,stride-1::stride])
		V.append(np.reshape(v, (ny-1, nx))[stride-1::stride,stride/2::stride])
		Q.append(np.concatenate([U[fIdx].flatten(),V[fIdx].flatten()]))
		
		print '{},'.format(folder),
		stride = stride*3

	for idx in range(numFolders-1):
		errL2NormU[idx] = la.norm(U[idx+1]-U[idx])
		errL2NormV[idx] = la.norm(V[idx+1]-V[idx])
		errL2NormQ[idx] = la.norm(Q[idx+1]-Q[idx])

		errLInfNormU[idx] = la.norm(U[idx+1]-U[idx], np.inf)
		errLInfNormV[idx] = la.norm(V[idx+1]-V[idx], np.inf)
		
		if idx==0:
			plt.ioff()
			h = initialMeshSpacing
			# u diffs
			x = np.arange(0., 1.+h/2., h)
			y = np.arange(h/2., 1., h)
			X, Y = np.meshgrid(x,y)
			fig = plt.figure()
			ax = fig.add_subplot(111)
			ax.set_xlim([0,1])
			ax.set_ylim([0,1])
			diffV = np.abs(V[idx+1]-V[idx])
			ax.tick_params(labelsize=16)
			CS = ax.pcolormesh(X, Y, diffV, norm=LogNorm(vmin=1e-10, vmax=1))
			fig.gca().set_aspect('equal', adjustable='box')
			cbar = fig.colorbar(CS)
			cbar.ax.tick_params(labelsize=16) 
			if args.removeMask:
				fig.savefig("{}/diffV_nomask.pdf".format(args.caseDir))
			else:
				fig.savefig("{}/diffV.pdf".format(args.caseDir))
			# v diffs
			x = np.arange(h/2., 1., h)
			y = np.arange(0., 1.+h/2., h)
			X, Y = np.meshgrid(x,y)
			fig = plt.figure()
			ax = fig.add_subplot(111)
			ax.set_xlim([0,1])
			ax.set_ylim([0,1])
			diffU = np.abs(U[idx+1]-U[idx])
			ax.tick_params(labelsize=16)
			CS = ax.pcolormesh(X, Y, diffU, norm=LogNorm(vmin=1e-10, vmax=1))
			fig.gca().set_aspect('equal', adjustable='box')
			cbar = fig.colorbar(CS)
			cbar.ax.tick_params(labelsize=16) 
			if args.removeMask:
				fig.savefig("{}/diffU_nomask.pdf".format(args.caseDir))
			else:
				fig.savefig("{}/diffU.pdf".format(args.caseDir))

	L2OrderOfConvergenceU = -np.polyfit(np.log10(meshSize), np.log10(errL2NormU), 1)[0]
	L2OrderOfConvergenceV = -np.polyfit(np.log10(meshSize), np.log10(errL2NormV), 1)[0]
	L2OrderOfConvergenceQ = -np.polyfit(np.log10(meshSize), np.log10(errL2NormQ), 1)[0]

	LInfOrderOfConvergenceU = -np.polyfit(np.log10(meshSize), np.log10(errLInfNormU), 1)[0]
	LInfOrderOfConvergenceV = -np.polyfit(np.log10(meshSize), np.log10(errLInfNormV), 1)[0]
	
	print " "
	line()
	
	print "U:",
	#print "errL2Norms: {}".format(errL2NormU)
	print "Convergence rates:",
	for i in range(len(errL2NormU)-1):
		print "{:.3f}, ".format(np.log(errL2NormU[i]/errL2NormU[i+1])/np.log(3)),
	print "Linear fit convergence rate: {:.3f}".format(L2OrderOfConvergenceU)

	print "V:",
	#print "errL2Norms: {}".format(errL2NormV)
	print "Convergence rates:",
	for i in range(len(errL2NormV)-1):
		print "{:.3f}, ".format(np.log(errL2NormV[i]/errL2NormV[i+1])/np.log(3)),
	print "Linear fit convergence rate: {:.3f}".format(L2OrderOfConvergenceV)

	'''
	print "Q:",
	#print "errL2Norms: {}".format(errL2NormQ)
	print "Convergence rates:",
	for i in range(len(errL2NormQ)-1):
		print "{:.3f}, ".format(np.log(errL2NormQ[i]/errL2NormQ[i+1])/np.log(3)),
	print "Linear fit convergence rate: {:.3f}".format(L2OrderOfConvergenceQ)
	'''
	
	line()

	plt.clf()
	plt.loglog(meshSize, errL2NormU, 's-k', label="$u$".format(L2OrderOfConvergenceU))
	plt.loglog(meshSize, errL2NormV, 'o-k', label="$v$".format(L2OrderOfConvergenceV))
	plt.axis([1, 1e4, 1e-4, 10])
	x  = np.linspace(1, 1e4, 2)
	x1 = 1/x
	x2 = 1/x**2
	plt.loglog(x, x1, '--k', label="First-order convergence")
	plt.loglog(x, x2, ':k', label="Second-order convergence")
	plt.legend(prop={'size':15})
	ax = plt.axes()
	ax.set_xlabel("Mesh size", fontsize=18)
	ax.set_ylabel("$L^2$-norm of differences", fontsize=18)
	ax.tick_params(labelsize=18)
	plt.savefig("{}/L2Convergence.pdf".format(args.caseDir))

	'''
Пример #8
0
def main():
    """Plots the contour of vorticity at every time saved."""
    # parse the command-line
    args = read_inputs()

    folder = args.folder  # name of the folder

    # read the parameters of the simulation
    nt, start_step, nsave, _ = readSimulationParameters(folder)

    if not args.plot_only:
        # calculate the mesh characteristics
        nx, ny, dx, dy, _, yu, xv, _ = readGridData(folder)

        # calculate appropriate array boundaries
        i_start = np.where(xv >= args.bl_x)[0][0]
        i_end = np.where(xv <= args.tr_x)[0][-1]
        j_start = np.where(yu >= args.bl_y)[0][0]
        j_end = np.where(yu <= args.tr_y)[0][-1]

        # time-loop
        for ite in xrange(start_step + nsave, nt + 1, nsave):
            # read the velocity data at the given time-step
            u, v = readVelocityData(folder, ite, nx, ny, dx, dy)
            if u is None or v is None:
                break

            # calculate and write the vorticity
            vort_file = '%s/%07d/vorticity' % (folder, ite)
            print vort_file
            with open(vort_file, 'w') as outfile:
                for j in xrange(j_start, j_end):
                    y = 0.5 * (yu[j] + yu[j + 1])
                    Dy = 0.5 * (dy[j] + dy[j + 1])
                    for i in xrange(i_start, i_end):
                        x = 0.5 * (xv[i] + xv[i + 1])
                        Dx = 0.5 * (dx[i] + dx[i + 1])
                        vort = (v[j*nx+i+1] - v[j*nx+i]) / Dx \
                          - (u[(j+1)*(nx-1)+i] - u[j*(nx-1)+i]) / Dy
                        outfile.write('%f\t%f\t%f\n' % (x, y, vort))
                    outfile.write('\n')

    # create the gnuplot file
    print 'Creating gnuplot file...'
    gnuplot_file = '%s/vorticity.plt' % folder
    with open(gnuplot_file, 'w') as outfile:
        outfile.write('reset;\n')
        outfile.write('set terminal pngcairo enhanced '
                      'font "Times, 15" size 900,600;\n')

        for ite in xrange(start_step + nsave, nt + 1, nsave):
            # image file name
            outfile.write('\nset output "%s/vort%07d.png"\n' % (folder, ite))
            outfile.write('set multiplot;\n')
            # vorticity
            outfile.write('reset;\n')
            outfile.write('set view map; set size ratio -1; unset key;\n')
            outfile.write('set pm3d map;\n')
            outfile.write('set palette defined (-2 "dark-blue", '
                          '-1 "light-blue", '
                          '0 "white", '
                          '1 "light-red", '
                          '2 "dark-red");\n')
            outfile.write('set cbrange [%f:%f];\n' %
                          (-args.vort_lim, args.vort_lim))
            outfile.write(
                'splot [%f:%f] [%f:%f] "%s/%07d/vorticity";\n' %
                (xv[i_start], xv[i_end], yu[j_start], yu[j_end], folder, ite))
            # bodies
            #outfile.write('reset;\n')
            #outfile.write('set view map; set size ratio -1; unset key;\n')
            #outfile.write('splot [%f:%f] [%f:%f] "%s/%07d/bodies" '
            #			  'u 1:2:(0) wl lw 2 lc "black";\n'
            #			  % (args.bl_x, args.tr_x, args.bl_y, args.tr_y,
            #			  	 folder, ite))
            outfile.write('unset multiplot;\n')

    print 'DONE!'

    # run the plotting script
    print 'Generating PNGs...'
    os.system('gnuplot %s' % gnuplot_file)

    print 'DONE!'
Пример #9
0
    sys.exit()

validationData = '/cavity-GGS82.txt'
caseFolder = cuibmFolder + '/validation/lidDrivenCavity/Re' + Re
validationData = cuibmFolder + '/validation-data' + validationData
execPath = cuibmFolder + '/bin/cuIBM'

print "\n" + "-" * 120
print "Running the validation case for flow in a lid-driven cavity at Reynolds number %s" % Re
print "-" * 120 + "\n"

runCommand = "%s -caseFolder %s" % (execPath, caseFolder)
print runCommand + "\n"
os.system(runCommand)

nt, _, _, _ = rd.readSimulationParameters(caseFolder)
nx, ny, dx, dy, _, yu, xv, _ = rd.readGridData(caseFolder)
u, v = rd.readVelocityData(caseFolder, nt, nx, ny, dx, dy)

f = open(caseFolder + "/u.txt", 'w')
f.write("%f\t%f\n" % (0, 0))
for j in range(len(yu)):
    f.write("%f\t%f\n" % (yu[j], u[j * (nx - 1) + nx / 2 - 1]))
f.write("%f\t%f\n" % (1, 1))
f.close()

f = open(caseFolder + "/v.txt", 'w')
f.write("%f\t%f\n" % (0, 0))
for i in range(len(xv)):
    f.write("%f\t%f\n" % (xv[i], v[(ny / 2 - 1) * nx + i]))
f.write("%f\t%f\n" % (1, 0))
Пример #10
0
def main():
	"""Plots the contour of vorticity at every time saved."""
	# parse the command-line
	args = read_inputs()

	folder = args.folder	# name of the folder

	# read the parameters of the simulation
	nt, start_step, nsave, _ = readSimulationParameters(folder)

	if not args.plot_only:
		# calculate the mesh characteristics
		nx, ny, dx, dy, _, yu, xv, _ = readGridData(folder)

		# calculate appropriate array boundaries
		i_start = np.where(xv >= args.bl_x)[0][0]
		i_end = np.where(xv <= args.tr_x)[0][-1]
		j_start = np.where(yu >= args.bl_y)[0][0]
		j_end = np.where(yu <= args.tr_y)[0][-1]

		# time-loop
		for ite in xrange(start_step+nsave, nt+1, nsave):
			# read the velocity data at the given time-step
			u, v = readVelocityData(folder, ite, nx, ny, dx, dy)
			if u == None or v == None:
				break

			# calculate and write the vorticity
			vort_file = '%s/%07d/vorticity' % (folder, ite)
			print vort_file
			with open(vort_file, 'w') as outfile:
				for j in xrange(j_start, j_end):
					y = 0.5 * (yu[j] + yu[j+1])
					Dy = 0.5 * (dy[j] + dy[j+1])
					for i in xrange(i_start, i_end):
						x = 0.5 * (xv[i] + xv[i+1])
						Dx = 0.5 * (dx[i] + dx[i+1])
						vort = (v[j*nx+i+1] - v[j*nx+i]) / Dx \
							 - (u[(j+1)*(nx-1)+i] - u[j*(nx-1)+i]) / Dy
						outfile.write('%f\t%f\t%f\n' % (x, y, vort))
					outfile.write('\n')

	# create the gnuplot file
	print 'Creating gnuplot file...'
	gnuplot_file = '%s/vorticity.plt' % folder
	with open(gnuplot_file, 'w') as outfile:
		outfile.write('reset;\n')
		outfile.write('set terminal pngcairo enhanced '
					  'font "Times, 15" size 900,600;\n')

		for ite in xrange(start_step+nsave, nt+1, nsave):
			# image file name
			outfile.write('\nset output "%s/vort%07d.png"\n' % (folder, ite))
			outfile.write('set multiplot;\n')
			# vorticity
			outfile.write('reset;\n')
			outfile.write('set view map; set size ratio -1; unset key;\n')
			outfile.write('set pm3d map;\n')
			outfile.write('set palette defined (-2 "dark-blue", '
											   '-1 "light-blue", '
											   '0 "white", '
											   '1 "light-red", '
											   '2 "dark-red");\n')
			outfile.write('set cbrange [%f:%f];\n' 
						  % (-args.vort_lim, args.vort_lim))
			outfile.write('splot [%f:%f] [%f:%f] "%s/%07d/vorticity";\n'
						  % (xv[i_start], xv[i_end], yu[j_start], yu[j_end], folder, ite))
			# bodies
			#outfile.write('reset;\n')
			#outfile.write('set view map; set size ratio -1; unset key;\n')
			#outfile.write('splot [%f:%f] [%f:%f] "%s/%07d/bodies" '
			#			  'u 1:2:(0) wl lw 2 lc "black";\n'
			#			  % (args.bl_x, args.tr_x, args.bl_y, args.tr_y, 
			#			  	 folder, ite))
			outfile.write('unset multiplot;\n')
	
	print 'DONE!'

	# run the plotting script
	print 'Generating PNGs...'
	os.system('gnuplot %s' % gnuplot_file)
	
	print 'DONE!'
Пример #11
0
def main():

	#view available fonts
	#for font in font_manager.findSystemFonts():
	#	print font

	try:
		fontpath = '/usr/share/fonts/truetype/msttcorefonts/Georgia.ttf'

		prop = font_manager.FontProperties(fname=fontpath)
		matplotlib.rcParams['font.family'] = prop.get_name()
	except:
		pass

	"""Plots the contour of velocity (u and v) at every time saved."""
	# parse the command-line
	args = read_inputs()

	folder = args.folder	# name of the folder

	# read the parameters of the simulation
	print folder
	nt, start_step, nsave, dt = readSimulationParameters(folder)

	# calculate the mesh characteristics
	nx, ny, dx, dy, xu, yu, xv, yv = readGridData(folder)

	# calculate appropriate array boundaries
	i_start = np.where(xu >= args.xmin)[0][0]
	i_end = np.where(xu <= args.xmax)[0][-1]
	j_start = np.where(yu >= args.ymin)[0][0]
	j_end = np.where(yu <= args.ymax)[0][-1]

	x_start = xu[i_start] - dx[i_start]
	x_end   = xu[i_end] + dx[i_end]
	y_start = yu[j_start] - dy[j_start]/2.
	y_end   = yu[j_end] + dy[j_end]/2.

	# generate a mesh grid for u- and v- velocities
	Xu, Yu = np.meshgrid(xu, yu)
	Xv, Yv = np.meshgrid(xv, yv)
	
	for ite in xrange(start_step+nsave, nt+1, nsave):
		print 'iteration %d' % ite
		# read the velocity data at the given time-step
		u, v = readVelocityData(folder, ite, nx, ny, dx, dy)
		if u is None or v is None:
			break

		# plot u-velocity contourf
		CS = plt.contourf(Xu, Yu, u.reshape((ny, nx-1)), levels=np.linspace(-args.u_lim, args.u_lim, 21))
		plt.title("U-Velocity @ time = {0}".format(ite*dt))
		plt.xlabel('x')
		plt.ylabel('y')
		plt.colorbar(CS)
		plt.gca().set_aspect('equal',adjustable='box')
		plt.xlim([x_start,x_end])
		plt.ylim([y_start,y_end])
		plt.savefig('%s/u%07d.png' % (folder, ite/nsave))
		plt.clf()
		
	
		# plot v-velocity contourf
		CS = plt.contourf(Xv, Yv, v.reshape((ny-1, nx)), 
					levels=np.linspace(-args.v_lim, args.v_lim, 21))
		plt.title("V-Velocity @ time = {0}".format(ite*dt))
		plt.xlabel('x')
		plt.ylabel('y')
		plt.colorbar(CS)
		plt.gca().set_aspect('equal',adjustable='box')
		plt.xlim([x_start,x_end])
		plt.ylim([y_start,y_end])
		plt.savefig('%s/v%07d.png' % (folder, ite/nsave))
		plt.clf()
Пример #12
0
def main():
	# Command line options
	parser = argparse.ArgumentParser(description="Calculates the order of convergence.", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
	parser.add_argument("-folder", dest="caseDir", help="folder in which the cases for different mesh sizes are present", default=os.path.expandvars("${CUIBM_DIR}/cases/convergence/cavityRe100/NavierStokes/20x20"))
	parser.add_argument("-tolerance", dest="tolerance", help="folder in which the cases for different mesh sizes are present", default="")
	parser.add_argument("-interpolation_type", dest="interpolation_type", help="the type of interpolation used in the direct forcing method", default="")
	parser.add_argument("-run_simulations", dest="runSimulations", help="run the cases if this flag is used", action='store_true', default=False)
	parser.add_argument("-remove_mask", dest="removeMask", help="use values from the entire domain", action='store_true', default=False)
	args = parser.parse_args()

	commandOptions = []
	if args.tolerance:
		commandOptions.extend(["-velocityTol", "{}".format(args.tolerance), "-poissonTol", "{}".format(args.tolerance)])
	if args.interpolation_type:
		commandOptions.extend(["-interpolationType", "{}".format(args.interpolation_type)])

	# list of folders from which velocity data is to be obtained
	folders = sorted(os.walk(args.caseDir).next()[1], key=int)
	numFolders = len(folders)

	# run the cases in each of the folders
	if args.runSimulations:
		for folder in folders:
			runCommand = [os.path.expandvars("${CUIBM_DIR}/bin/cuIBM"),
							'-caseFolder', "{}/{}".format(args.caseDir, folder)]
			runCommand.extend(commandOptions)
			print " ".join(runCommand)
			subprocess.call(runCommand)

	# create arrays to store the required values
	U = []
	V = []
	errL2NormU  = np.zeros(numFolders-1)
	errL2NormV  = np.zeros(numFolders-1)
	errLInfNormU  = np.zeros(numFolders-1)
	errLInfNormV  = np.zeros(numFolders-1)
	meshSize = np.zeros(numFolders-1, dtype=int)

	line()

	stride = 1
	for fIdx, folder in enumerate(folders):
		# path to folder
		folderPath = os.path.expandvars("{}/{}".format(args.caseDir, folder));
		# read simulation information
		nt, _, _, _ = readSimulationParameters(folderPath)

		# read the grid data
		# nx and ny are the number of cells
		# dx and dy are the cell widths
		# xu and yu are the coordinates of the locations where U is calculated
		nx, ny, dx, dy, xu, yu, xv, yv = readGridData(folderPath)
		
		if fIdx==0:
			initialMeshSpacing = dx[0]
		else:
			meshSize[fIdx-1] = nx

		# read velocity data
		u, v = readVelocityData(folderPath, nt, nx, ny, dx, dy)

		if not args.removeMask:
			# read mask
			mask_u, mask_v = readMask(folderPath, nx, ny)
			u[:] = u[:]*mask_u[:]
			v[:] = v[:]*mask_v[:]

		U.append(np.reshape(u, (ny, nx-1))[stride/2::stride,stride-1::stride])
		V.append(np.reshape(v, (ny-1, nx))[stride-1::stride,stride/2::stride])
		
		print 'Completed folder {}. u:{}, v:{}'.format(folder, U[fIdx].shape, V[fIdx].shape)
		stride = stride*3

	for idx in range(numFolders-1):
		errL2NormU[idx] = la.norm(U[idx+1]-U[idx])
		errL2NormV[idx] = la.norm(V[idx+1]-V[idx])

		errLInfNormU[idx] = la.norm(U[idx+1]-U[idx], np.inf)
		errLInfNormV[idx] = la.norm(V[idx+1]-V[idx], np.inf)
		
		if idx==0:
			h = initialMeshSpacing
			x = np.arange(h/2., 1., h)
			y = np.arange(h, 1., h)
			X, Y = np.meshgrid(x,y)
			plt.ioff()
			fig = plt.figure()
			ax = fig.add_subplot(111)
			diffV = np.abs(V[idx+1]-V[idx] )
			CS = ax.pcolor(X, Y, diffV, norm=LogNorm(vmin=1e-10, vmax=1))
			fig.gca().set_aspect('equal', adjustable='box')
			fig.colorbar(CS)
			if args.removeMask:
				fig.savefig("{}/diff_nomask.png".format(args.caseDir))
			else:
				fig.savefig("{}/diff.png".format(args.caseDir))
	
	L2OrderOfConvergenceU = -np.polyfit(np.log10(meshSize), np.log10(errL2NormU), 1)[0]
	L2OrderOfConvergenceV = -np.polyfit(np.log10(meshSize), np.log10(errL2NormV), 1)[0]

	LInfOrderOfConvergenceU = -np.polyfit(np.log10(meshSize), np.log10(errLInfNormU), 1)[0]
	LInfOrderOfConvergenceV = -np.polyfit(np.log10(meshSize), np.log10(errLInfNormV), 1)[0]
	
	line()
	print "Mesh sizes: {}".format(meshSize)
	line()
	print "U:"
	print "errL2Norms: {}".format(errL2NormU)
	print "Convergence rates: {:.3f}, {:.3f}".format(np.log(errL2NormU[0]/errL2NormU[1])/np.log(3), np.log(errL2NormU[1]/errL2NormU[2])/np.log(3))
	print "Linear fit convergence rate: {:.3f}".format(L2OrderOfConvergenceU)

	print "\nV:"
	print "errL2Norms: {}".format(errL2NormV)
	print "Convergence rates: {:.3f}, {:.3f}".format(np.log(errL2NormV[0]/errL2NormV[1])/np.log(3), np.log(errL2NormV[1]/errL2NormV[2])/np.log(3))
	print "Linear fit convergence rate: {:.3f}".format(L2OrderOfConvergenceV)
	
	plt.clf()
	plt.loglog(meshSize, errL2NormU, 'o-b', label="L-2 norm of difference in $u$\nOrder of convergence={:.3f}".format(L2OrderOfConvergenceU))
	plt.loglog(meshSize, errL2NormV, 'o-r', label="L-2 norm of difference in $v$\nOrder of convergence={:.3f}".format(L2OrderOfConvergenceV))
	plt.axis([1, 1e4, 1e-4, 100])
	x  = np.linspace(1, 1e4, 2)
	x1 = 1/x
	x2 = 1/x**2
	plt.loglog(x, x1, '--k', label="First-order convergence")
	plt.loglog(x, x2, ':k', label="Second-order convergence")
	plt.legend()
	ax = plt.axes()
	ax.set_xlabel("Mesh size")
	ax.set_ylabel("L-2 Norm of difference between solutions on consecutive grids")
	plt.savefig("{}/L2Convergence.png".format(args.caseDir))

	line()
	print "U:"
	print "errLInfNorms: {}".format(errLInfNormU)
	print "Convergence rates: {:.3f}, {:.3f}".format(np.log(errLInfNormU[0]/errLInfNormU[1])/np.log(3), np.log(errLInfNormU[1]/errLInfNormU[2])/np.log(3))
	print "Linear fit convergence rate: {:.3f}".format(LInfOrderOfConvergenceU)

	print "\nV:"
	print "errLInfNorms: {}".format(errLInfNormV)
	print "Convergence rates: {:.3f}, {:.3f}".format(np.log(errLInfNormV[0]/errLInfNormV[1])/np.log(3), np.log(errLInfNormV[1]/errLInfNormV[2])/np.log(3))
	print "Linear fit convergence rate: {:.3f}".format(LInfOrderOfConvergenceV)
	line()

	plt.clf()
	plt.loglog(meshSize, errLInfNormU, 'o-b', label="L-Inf norm of difference in $u$\nOrder of convergence={:.3f}".format(LInfOrderOfConvergenceU))
	plt.loglog(meshSize, errLInfNormV, 'o-r', label="L-Inf norm of difference in $v$\nOrder of convergence={:.3f}".format(LInfOrderOfConvergenceV))
	plt.axis([1, 1e4, 1e-4, 100])
	x  = np.linspace(1, 1e4, 2)
	x1 = 1/x
	x2 = 1/x**2
	plt.loglog(x, x1, '--k', label="First-order convergence")
	plt.loglog(x, x2, ':k', label="Second-order convergence")
	plt.legend()
	ax = plt.axes()
	ax.set_xlabel("Mesh size")
	ax.set_ylabel("L-Inf Norm of difference between solutions on consecutive grids")
	plt.savefig("{}/LInfConvergence.png".format(args.caseDir))
elif Re=='5000':
	uCol           = '3'
	vCol           = '8' 
elif Re=='10000':
	uCol           = '4'
	vCol           = '9'
else:
	print "Unavailable option for Reynolds number. Choose 100, 1000 or 10000."
	sys.exit()

validationData = '/cavity-GGS82.txt'
caseFolder     = cuibmFolder + '/validation/lidDrivenCavity/Re' + Re
validationData = cuibmFolder + '/validation-data' + validationData
execPath       = cuibmFolder + '/bin/cuIBM'

nt, _, _, _ = rd.readSimulationParameters(caseFolder)
nx, ny, dx, dy, _, yu, xv, _ = rd.readGridData(caseFolder)
u, v = rd.readVelocityData(caseFolder, nt, nx, ny, dx, dy)

u2=[]
x2=[]
v2=[]
y2=[]

x2.append(0)
u2.append(0)
for j in range(len(yu)):
	u2.append(u[j*(nx-1)+nx/2-1])
	x2.append(yu[j])
x2.append(1)
u2.append(1)
Пример #14
0
def main():

	#view available fonts
	#for font in font_manager.findSystemFonts():
	#	print font

	try:
		fontpath = '/usr/share/fonts/truetype/msttcorefonts/Georgia.ttf'

		prop = font_manager.FontProperties(fname=fontpath)
		matplotlib.rcParams['font.family'] = prop.get_name()
	except:
		pass

	"""Plots the contour of velocity (u and v) at every time saved."""
	# parse the command-line
	args = read_inputs()

	folder = args.folder	# name of the folder

	# read the parameters of the simulation
	print folder
	nt, start_step, nsave, dt = readSimulationParameters(folder)

	# calculate the mesh characteristics
	nx, ny, dx, dy, xu, yu, xv, yv = readGridData(folder)

	# calculate appropriate array boundaries
	i_start = np.where(xu >= args.xmin)[0][0]
	i_end = np.where(xu <= args.xmax)[0][-1]
	j_start = np.where(yu >= args.ymin)[0][0]
	j_end = np.where(yu <= args.ymax)[0][-1]

	x_start = xu[i_start] - dx[i_start]
	x_end   = xu[i_end] + dx[i_end]
	y_start = yu[j_start] - dy[j_start]/2.
	y_end   = yu[j_end] + dy[j_end]/2.

	# generate a mesh grid for u- and v- velocities
	Xu, Yu = np.meshgrid(xu, yu)
	Xv, Yv = np.meshgrid(xv, yv)
	
	for ite in xrange(start_step+nsave, nt+1, nsave):
		print 'iteration %d' % ite
		# read the velocity data at the given time-step
		try:
			u, v = readVelocityData(folder, ite, nx, ny, dx, dy)
			if u is None or v is None:
				break
		
			# plot u-velocity contourf
			CS = plt.contourf(Xu, Yu, u.reshape((ny, nx-1)), levels=np.linspace(-args.u_lim, args.u_lim, 21))
			plt.title("U-Velocity @ time = {0}".format(ite*dt))
			plt.xlabel('x')
			plt.ylabel('y')
			plt.colorbar(CS)
			plt.gca().set_aspect('equal',adjustable='box')
			plt.xlim([x_start,x_end])
			plt.ylim([y_start,y_end])
			plt.savefig('%s/u%07d.png' % (folder, ite/nsave))
			plt.clf()
		
			"""
			# plot v-velocity contourf
			CS = plt.contourf(Xv, Yv, v.reshape((ny-1, nx)), 
						levels=np.linspace(-args.v_lim, args.v_lim, 21))
			plt.title("V-Velocity @ time = {0}".format(ite*dt))
			plt.xlabel('x')
			plt.ylabel('y')
			plt.colorbar(CS)
			plt.gca().set_aspect('equal',adjustable='box')
			plt.xlim([x_start,x_end])
			plt.ylim([y_start,y_end])
			plt.savefig('%s/v%07d.png' % (folder, ite/nsave))
			plt.clf()
			"""
		except:
			print '\tno data found for timestep: ' + str(ite)
Пример #15
0
def main():
    """Analyses the vorticity given a case."""
    # parse the command-line
    args = read_inputs()

    folder = args.folder  # path of the case

    # read parameters of the simulation
    nt, start_step, nsave, dt = readSimulationParameters(folder)

    # read and generate the computational mesh
    nx, ny, dx, dy, _, yu, xv, _ = readGridData(folder)

    # number of saved points
    save_points = int((nt - start_step) / nsave)

    T = 10.0  # total time of the simulation
    h = dx[0]  # uniform cell-width

    # initialization
    total_vorticity = np.empty(save_points, dtype=float)
    circulation = np.empty(save_points, dtype=float)
    time = np.empty(save_points, dtype=float)

    # time-loop
    ite = start_step + nsave
    idx = 0
    while ite < nt + 1:
        time[idx] = ite * dt
        # read the vorticity
        vort_file = '%s/%07d/vorticity' % (folder, ite)
        with open(vort_file, 'r') as infile:
            vorticity = np.loadtxt(infile, dtype=float, usecols=(2, ))
        # calculate the total vorticity
        total_vorticity[idx] = h**2 * vorticity.sum()
        # calculate the theoretical circulation
        circulation[idx] = -math.sin(math.pi * time[idx] / T)
        idx += 1
        ite += nsave

    # plot the total vorticity and theretical circulation
    plt.figure()
    plt.grid(True)
    plt.xlabel('Time', fontsize=16)
    plt.ylabel('Total circulation', fontsize=16)
    plt.plot(time,
             total_vorticity,
             label='Total vorticity',
             color='r',
             ls='.',
             marker='o',
             markersize=10)
    plt.plot(time,
             circulation,
             label='Theoretical circulation',
             color='b',
             ls='-',
             lw=2)
    plt.xlim(0, 80)
    plt.ylim(-1.5, 1.5)
    plt.title('Comparison of Total Vorticity and Theoretical Circulation '
              'at Re=10,000')
    plt.legend(loc='best', prop={'size': 16})
    plt.savefig('%s/total_vorticity.png' % folder)
    if args.show:
        plt.show()