#!/usr/bin/env python3 import sys sys.path.append("/home/lequieu/Work/tools/lib/") import iotools as io import pdb import viztools as viz import numpy as np from domaintools import DomainAnalyzer if __name__ == "__main__": infile = "density.bin" #ndim, Nx, orthorhombic, M, nfields, AllCoords, AllFields = io.ReadBinFile(infile) AllCoords, AllFields = io.ReadBinFile(infile) np.save("coords.npy", AllCoords) np.save("densityfields.npy", AllFields) infile = "fields.bin" #ndim, Nx, orthorhombic, M, nfields, AllCoords, AllFields = io.ReadBinFile(infile) AllCoords, AllFields = io.ReadBinFile(infile) #np.save("coords.npy", AllCoords) np.save("wfields.npy", AllFields)
type=str, help='Input fields file from PolyFTS. Can be binary or dat') parser.add_argument('--output', default='epsilon.h5', type=str, help='Output h5 file to be read by MPB code') # Parse the command-line arguments args = parser.parse_args() # setup and parse input file name # use iotools to load density.bin to get coords and fields if args.input != '': infile = args.input suffix = infile.split('.')[-1] if suffix == 'bin': coords, fields = io.ReadBinFile(infile) fields_have_imag = True elif suffix == 'dat': coords, fields = io.ReadDatFile(infile) fields_have_imag = False else: raise RuntimeError(f"invalid suffix of args.input: {suffix}") else: # args.input not specified, try density.bin and density.dat if os.path.isfile('density.bin'): coords, fields = io.ReadBinFile('density.bin') fields_have_imag = True elif os.path.isfile('density.dat'): coords, fields = io.ReadDatFile('density.dat') fields_have_imag = False else:
for iblock in range(nblocks): if resumeflag and os.path.exists("stats{}.dat".format(iblock)): # if skipblock, then just load the stats file print(f"Skipping frames {infiles_in_block[iblock][0]} to {infiles_in_block[iblock][-1]}, --resume flag is set and stats{iblock}.dat exists.") skipblock = True else: skipblock = False if saveflag and not skipblock: print(f"Block{iblock}, averaging frames ",end='',flush=True) first = True for infile in infiles_in_block[iblock]: print("{}, ".format(infile),end='',flush=True), coords, fields = io.ReadBinFile(infile) if first: sumcoords = np.copy(coords) sumfields = np.copy(fields) first = False else: sumcoords = sumcoords + coords sumfields = sumfields + fields print("...done") nfiles_in_block = len(infiles_in_block[iblock]) sumcoords /= nfiles_in_block sumfields /= nfiles_in_block # now all the fields in this block have been averaged
if args.verbose: logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) else: logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.WARNING) orthorhombic = True # Check whether the input file exits, and whether it is a binary PolyFTS file or a formatted on. # Dispatch reading to relevant function. # Open as binary first print("Reading input file {}".format(infile)) if iotools.TestBinFile(infile): #ndim, Nx, orthorhombic, M, nfields, AllCoords, AllFields = iotools.ReadBinFile(infile) AllCoords, AllFields = iotools.ReadBinFile(infile) else: #ndim, Nx, orthorhombic, M, nfields, AllCoords, AllFields = iotools.ReadDatFile(infile) AllCoords, AllFields = iotools.ReadDatFile(infile) logging.info("Orthorhombic cell? {}".format(orthorhombic)) print("Outputting to Legacy VTK formatted file {}".format(outfile)) #viztools.writeVTK(outfile, Nx, orthorhombic, M, AllCoords, AllFields) ndim = AllCoords.shape[-1] if ndim == 1: AllCoords = AllCoords[::args.stride, :] AllFields = AllFields[::args.stride, :] elif ndim == 2: AllCoords = AllCoords[::args.stride, ::args.stride, :] AllFields = AllFields[::args.stride, ::args.stride, :]
def plot_density(infile): #infile="density.bin" restart = False if restart: com = np.load('com.npy') coords2d = np.load('coords2d.npy') fields2d = np.load('fields2d.npy') coords = np.load('coords.npy') fields = np.load('fields.npy') else: coords, fields = io.ReadBinFile(infile) __ndim = len(coords.shape) - 1 __Nx = coords.shape[:__ndim] #__hvoxel = np.array([coords[1,0],coords[0,1]]) __hvoxel = np.array([coords[1, 0, 0], coords[0, 1, 0], coords[0, 0, 1]]) __hcell = __hvoxel * __Nx #nreplicates = (2,2) #repcoords,repfields = fieldtools.replicate_fields(coords,fields,nreplicates) zslice = 0.5 * __hcell[2, 2] zslice_index = int(0.5 * __Nx[2]) # use domain analyzer to get com and contours if not restart: domainanalyzer = DomainAnalyzer(coords, fields) domainanalyzer.setDensityThreshold(0.5) ndomains, com, area, vol, IQ = domainanalyzer.getDomainStats( plotMesh=False, add_periodic_domains=True) ##verts,faces,normals,values = domainanalyzer.meshAllDomains(plotfile='tmp.png') coords2d = coords[:, :, zslice_index, 0:2] fields2d = fields[:, :, zslice_index, :] np.save('com.npy', com) np.save('coords2d.npy', coords2d) np.save('fields2d.npy', fields2d) np.save('coords.npy', coords) np.save('fields.npy', fields) domainanalyzer2d = DomainAnalyzer(coords2d, fields2d) contours = domainanalyzer2d.meshAllDomains() # add extra cells in -/+ x and -/+ y so that voronoi cells are in correct locations com = np.vstack([ com, com + [-1, 0, 0] * np.mat(__hcell), com + [0, -1, 0] * np.mat(__hcell), com + [1, 0, 0] * np.mat(__hcell), com + [0, 1, 0] * np.mat(__hcell) ]) # using COM get voronoi cells using scipy vor = scipy.spatial.Voronoi(com) # now plot fig = plt.figure() ax = fig.add_subplot(111) ax.set_xticks([]) ax.set_yticks([]) ax.set_axis_off() # turn axes off ax.set_aspect(1) ymax = np.max(coords2d[:, :, 1]) ymin = np.min(coords2d[:, :, 1]) ax.set_ylim(ymin, ymax) # reduce 3d voronoi cells to a 2d slice com2d = [] points2d = [] for i in range(com.shape[0]): if np.isclose(com[i, 2], zslice): com2d.append([com[i, 0], com[i, 1]]) points2d.append(i) #ax.text(com[i,0],com[i,1],f'{i}') com2d = np.array(com2d) #plot com2d #ax.plot(com2d[:,0],com2d[:,1], color='red',marker='x',ls='') for ridge_pair in vor.ridge_points: #if ridge_pair[0] in points2d or ridge_pair[1] in points2d: if True: myridge_verticies = vor.ridge_dict[tuple(ridge_pair)] #myverticies = np.array([vor.vertices[i] for i in myridge_verticies if i != -1 and np.all(np.abs(vor.vertices[i]) <100) ]) myverticies = np.array( [vor.vertices[i] for i in myridge_verticies if i != -1]) zmin = np.min(myverticies[:, 2]) zmax = np.max(myverticies[:, 2]) #print(ridge_pair,zmin,zmax) tol = 1e-2 if np.isclose(zmax, zmin) or ((zmin + tol) < zslice and (zmax - tol) > zslice): #ax.plot(myverticies[:,0],myverticies[:,1],color='k',ls='',marker='o') #ax.plot(myverticies[:,0],myverticies[:,1],color='k') ax.plot(myverticies[:, 0], myverticies[:, 1], ls='-', color='k') ax.plot([myverticies[-1, 0], myverticies[0, 0]], [myverticies[-1, 1], myverticies[0, 1]], ls='-', color='k') #ax.legend() # plot contours for contour in contours: ax.plot(contour[:, 0], contour[:, 1], linewidth=2, color='k', ls='--') # plot density fields X = coords2d[:, :, 0] Y = coords2d[:, :, 1] z = fields2d[:, :, 0] ax.imshow(z.T, cmap=plt.cm.coolwarm, vmin=0.0, vmax=1.0, extent=[X.min(), X.max(), Y.min(), Y.max()], interpolation='bicubic', origin='lower') #im=ax.pcolormesh(xx,yy,repfields[:,:,0].T,cmap=mpl.cm.coolwarm,vmin=0,vmax=1) plt.tight_layout() plt.savefig('fig_domain_shape_SIGMA.png') plt.savefig('fig_domain_shape_SIGMA.pdf') plt.show()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 22 23:24:21 2020 @author: tquah """ import os import sys #sys.path.append("/home/lequieu/Work/tools/lib") mypath = os.path.realpath(sys.argv[0]) #the absolute path to this script libpath = '/'.join(mypath.split( '/')[0:-2]) + '/lib' # remove script name and domain_analysis directory sys.path.append(libpath) import numpy as np import logging import pdb import viztools import iotools import argparse import re, glob import matplotlib.pyplot as plt from copy import deepcopy #from scipy.interpolate import #writePolyFTSDatFile(outfilename, griddim, hcell, complexdata, kspacedata, fielddata, fielddataimpart=[]) import_path = '/home/tquah/TestDIR/readwrite_different_resolutions/GYR_fields.in' export_path = '/home/tquah/TestDIR/readwrite_different_resolutions/fields.out' field = iotools.ReadBinFile(import_path)
# Method 2 take average of two fields one DIS one LAM infilelist = [ '/home/tquah/Projects/CL_SEEDS/averagedis.bin', '/home/tquah/Projects/CL_SEEDS/LAM_field.bin' ] outfile = '/home/tquah/Projects/CL_SEEDS/avglamwithavgdis.dat' weight = [30, 1] # x:1 # coords, fields = io.ReadBinFile(infile) fields = [] coords = [] for i in range(len(infilelist)): coord_local, fields_local = io.ReadBinFile(infilelist[i]) fields.append(fields_local * weight[i]) coords.append(coord_local) newfield = np.stack(fields) avgfield = np.sum(fields, axis=0) / np.sum(weight) #get real fields fieldout = avgfield[:, :, :, [0, 2]] io.WriteDatFile(outfile, coord_local, fieldout, iskspace=False, iscomplex=False) # Method 3 lets take an average of 100 random fields then average it with
args.tolerance = float(args.tolerance) #the default tolerance in platon is 0.5 angstroms (radii of gyration) #in order to change this expand the box by a factor, so the relative #tolerance is tighter box_multiplier = 0.5 / args.tolerance # if not os.path.isfile('structure.cif') and not args.overwrite: # make_domains(args.filename) # else: # print('Found an existing structure.cif skipping domain calculation, disable this feature with -o') #====================================================================== #this section finds the domains, using domaintools with meshing enabled #====================================================================== filetype = re.split('\.', args.filename)[-1] if filetype == 'bin': AllCoords, AllFields = io.ReadBinFile(args.filename) elif filetype == 'dat': AllCoords, AllFields = io.ReadDatFile(args.filename) else: raise NotImplementedError('This only supports .bin and .dat files') #normalize by box length #extra AllCoords[1,1,1] is because boxes are mesured by lower left corner box_length = AllCoords[-1, -1, -1] + AllCoords[1, 1, 1] AllCoords = AllCoords / (box_length) domainanalyzer = DomainAnalyzer(AllCoords, AllFields) ndomains, com, area, vol, IQ = domainanalyzer.getDomainStats( plotMesh=False, add_periodic_domains=True) domainanalyzer.meshAllDomains(plotfile="mesh_all.png") stats = np.vstack((com.T, area, vol, IQ)).T np.savetxt("stats_mesh.dat", stats, header="comx comy comz area vol IQ")