def _test_write_dx(counts=100, ndim=3, nptype="float32", dxtype="float"): h, edges = np.histogramdd(np.random.random((counts, ndim)), bins=10) g = Grid(h, edges) # hack the grid to be a different dtype g.grid = g.grid.astype(nptype) assert_equal(g.grid.sum(), counts) with tempdir.in_tempdir(): outfile = "grid.dx" g.export(outfile) g2 = Grid(outfile) # check that dxtype was written dx = gridData.OpenDX.field(0) dx.read(outfile) data = dx.components['data'] out_dxtype = data.type assert_almost_equal(g.grid, g2.grid, err_msg="written grid does not match original") assert_almost_equal( g.delta, g2.delta, decimal=6, err_msg="deltas of written grid do not match original") assert_equal(out_dxtype, dxtype)
def test_write_dx(tmpdir, nptype, dxtype, outfile, counts=100, ndim=3): # conversion from numpy array to DX file h, edges = np.histogramdd(np.random.random((counts, ndim)), bins=10) g = Grid(h, edges) # hack the grid to be a different dtype g.grid = g.grid.astype(nptype) assert_equal(g.grid.sum(), counts) with tmpdir.as_cwd(): g.export(outfile) g2 = Grid(outfile) # check that dxtype was written dx = gridData.OpenDX.field(0) dx.read(outfile) data = dx.components['data'] out_dxtype = data.type assert_almost_equal(g.grid, g2.grid, err_msg="written grid does not match original") assert_almost_equal(g.delta, g2.delta, decimal=6, err_msg="deltas of written grid do not match original") assert_equal(out_dxtype, dxtype)
def write_dx_input(self, param_charge, param_diel): ''' Generate the dielectric constant and charge grid for APBS calculations. ``generate_charge`` and ``generate_diel`` are used to generate the profile of the charge and dielectric constant on the one-dimensional z-axis which is then broadcast to cover the whole 3D space. The generated files are named as ``dielx.dx``, ``diely.dx``, ``dielz.dx`` and ``charge.dx``. Parameters ---------- **kwargs : dict ``generate_charge`` uses the arguments from kwargs['charge'] and ``generate_diel`` uses the arguments from kwargs['diel']. ''' # generate the one dimensional z axis z_list = np.linspace(0 * pq.angstrom, self.dim[-1], self.grid[-1]) charge = self.generate_charge(z_list, param_charge) diel = self.generate_diel(z_list, param_diel) # expand to 3D diel = np.ones((self.grid[0], self.grid[1], 1)) * diel.reshape( (1, 1, self.grid[2])) charge = np.ones((self.grid[0], self.grid[1], 1)) * charge.reshape( (1, 1, self.grid[2])) origin = self.dim / 2 * -1 origin = origin.rescale(pq.angstrom) delta = self.delta.rescale(pq.angstrom) # Write diel # write x origin_x = origin.copy() origin_x[0] += self.delta[0] / 2 g = Grid(diel, origin=origin_x.magnitude, delta=delta.magnitude) g.export('dielx.dx', typequote='') # write y origin_y = origin.copy() origin_y[1] += self.delta[1] / 2 g = Grid(diel, origin=origin_y.magnitude, delta=delta.magnitude) g.export('diely.dx', typequote='') # write z origin_z = origin.copy() origin_z[2] += self.delta[2] / 2 g = Grid(diel, origin=origin_z.magnitude, delta=delta.magnitude) g.export('dielz.dx', typequote='') # Write charge charge = charge.rescale(pq.e / pq.angstrom**3) g = Grid(charge.magnitude, origin=origin.magnitude, delta=delta.magnitude) g.export('charge.dx', typequote='')
def test_ccp4(): g = Grid(datafiles.CCP4) POINTS = 192 assert_equal(g.grid.flat, np.arange(1, POINTS+1)) assert_equal(g.grid.size, POINTS) assert_almost_equal(g.delta, [3./4, .5, 2./3]) assert_equal(g.origin, np.zeros(3))
def analyze_dx(_f): """analyzes dx _file Args: _f (string): filename with extension of the dx file that we want to analyze Returns: pandas: pandas dataframe columns=['coord_phi','phiz'] """ g = Grid(_f) nx, ny, nz = g.grid.shape Lx = g.edges[0][0] Ly = g.edges[1][0] Lzl = g.edges[2][0] Lzr = g.edges[2][-1] g_all = np.zeros(nz) count = 0 for i in range(nx): for j in range(ny): g_all += g.grid[i][j] count += 1 r_array = np.linspace(Lzl, Lzr, nz) yy = g_all / count A = np.vstack([r_array, yy]) df = pd.DataFrame(A.T, columns=['coord_phi', 'phiz']) return df
def test_read_dx(): g = Grid('gridData/tests/test.dx') POINTS = 8 assert_array_equal(g.grid.flat, np.ones(POINTS)) assert_equal(g.grid.size, POINTS) assert_array_equal(g.delta, np.ones(3)) assert_array_equal(g.origin, np.zeros(3))
def test_ccp4(): g = Grid('gridData/tests/test.ccp4') POINTS = 192 assert_equal(g.grid.flat, np.arange(1, POINTS + 1)) assert_equal(g.grid.size, POINTS) assert_almost_equal(g.delta, [3. / 4, .5, 2. / 3]) assert_equal(g.origin, np.zeros(3))
def analyze_dx(f): """analyzes dx file""" g = Grid(f + ".dx") nx, ny, nz = g.grid.shape Lx = g.edges[0][0] Ly = g.edges[1][0] Lzl = g.edges[2][0] Lzr = g.edges[2][-1] # g_all = g.grid[nx//2][ny//2] # g_vmd = g_all # L = 100. g_all = np.zeros(nz) count = 0 for i in range(nx): for j in range(ny): g_all += g.grid[i][j] count += 1 # vmd_unit = 25*ureg.mV # vmd_unit = 1. # units = nu.e/(25*nu.mV) # print units yy = g_all[2:-2]/count r_array = np.linspace(Lzl, Lzr, len(yy)) print len(r_array), len(yy) return r_array, yy
def __init__(self, fileName): try: from gridData import Grid except ModuleNotFoundError: raise ModuleNotFoundError("The dependency 'GridDataFormats' is required for this functionality!") self.grid = Grid(fileName) # stores the grid data
def extractISOPdb(input, output, iso): g = Grid(input) # JD: this is clunky but i'm not sure what's a better way data = np.array(OpenDX.array(3, g.grid).array.flat) data = data.reshape((len(data) / 3, 3)) x, y, z = 0, 0, 0 counter = 1 lines = [] for point in data: for pos in point: if (iso < 0 and pos < iso) or (iso > 0 and pos > iso): line = 'ATOM %5d C PTH 1 %8.3f%8.3f%8.3f%6.2f%6.2f\n' % ( counter, g.origin[0] + float(x) * g.delta[0, 0], g.origin[1] + float(y) * g.delta[1, 1], g.origin[2] + float(z) * g.delta[2, 2], 0.0, 0.0) lines.append(line) counter += 1 z += 1 if z >= g.grid.shape[2]: z = 0 y += 1 if y >= g.grid.shape[1]: y = 0 x += 1 with open(output, "w") as f: f.writelines(lines) return g
def data(): d = dict( griddata=np.arange(1, 28).reshape(3, 3, 3), origin=np.zeros(3), delta=np.ones(3)) d['grid'] = Grid(d['griddata'], origin=d['origin'], delta=d['delta']) return d
def read_APBS(self): ''' Read the APBS output. Returns ------- charge : array The three-dimensional array of the charge density. diel : array The three-dimensional array of the dielectric constant in the x direction. lipid : array The three-dimensional array of the ESP. ''' charge = Grid('charge_check.dx').grid diel = Grid('dielx_check.dx').grid lipid = Grid('lipid.dx').grid return charge, diel, lipid
def mask_generator(maskfile, referencefile=None, distance=5): if os.path.splitext(maskfile)[1] == ".pdb": mask = GridUtil.gen_distance_grid(referencefile, maskfile) else: mask = Grid(maskfile) mask.grid = mask.grid < distance return mask
def test_write_dx(counts=100, ndim=3): h, edges = np.histogramdd(np.random.random((counts, ndim)), bins=10) g = Grid(h, edges) assert_equal(g.grid.sum(), counts) with tempdir.in_tempdir(): outfile = "grid.dx" g.export(outfile) g2 = Grid(outfile) assert_array_almost_equal(g.grid, g2.grid, err_msg="written grid does not match original") assert_array_almost_equal( g.delta, g2.delta, err_msg="deltas of written grid do not match original")
def test_init_pickle_pathobjects(self, data, tmpdir): g = data['grid'] fn = tmpdir.mkdir('grid').join('grid.pickle') g.save(fn) h = Grid(fn) assert h == g
def test_centers(self, data): # this only checks the edges. If you know an alternative # algorithm that isn't an exact duplicate of the one in # g.centers to test this please implement it. g = Grid(data['griddata'], origin=np.ones(3), delta=data['delta']) centers = np.array(list(g.centers())) assert_array_equal(centers[0], g.origin) assert_array_equal(centers[-1] - g.origin, (np.array(g.grid.shape) - 1) * data['delta'])
def test_load_pickle(self, data, tmpdir): g = data['grid'] fn = str(tmpdir.mkdir('grid').join('grid.pkl')) g.save(fn) h = Grid() h.load(fn) assert h == g
def test_read_dx(infile): g = Grid(infile) POINTS = 8 ref = np.ones(POINTS) ref[4] = 1e-6 ref[5] = -1e+6 assert_equal(g.grid.flat, ref) assert_equal(g.grid.size, POINTS) assert_equal(g.delta, np.ones(3)) assert_equal(g.origin, np.array([20.1, 3., -10.]))
def read(self): DX = Path(self.fname).glob("*.dx") files = [p for p in DX if p.is_file()] if not files: raise Exception("No .dx files found") for dx in files: name = dx.stem.split('.') if (name[0].endswith("_"+self.suffix[0])): self.grids[self.suffix[0]+name[1]] = Grid(self.fname + "/" + dx.stem + ".dx") self.delta = np.prod(self.grids[self.suffix[0]+name[1]].delta) elif (name[0].endswith("_"+self.suffix[1])): self.grids[self.suffix[1]+name[1]] = Grid(self.fname + "/" + dx.stem + ".dx") elif (name[0].endswith("_"+self.suffix[2])): self.grids[self.suffix[2]+name[1]] = Grid(self.fname + "/" + dx.stem + ".dx") elif (name[0].endswith("_"+self.suffix[3])): self.grids[self.suffix[3]+name[1]] = Grid(self.fname + "/" + dx.stem + ".dx") if not self.grids: raise Exception("No tagged .dx files found")
def test_write_dx_ValueError(tmpdir, nptype, outfile, counts=100, ndim=3): h, edges = np.histogramdd(np.random.random((counts, ndim)), bins=10) g = Grid(h, edges) # hack the grid to be a different dtype g.grid = g.grid.astype(nptype) with pytest.raises(ValueError): with tmpdir.as_cwd(): g.export(outfile)
def get_density(lipid_xyz, ul_max, x): xbin, ybin, zbin = int(ul_max[0]*x), int(ul_max[1]*x), int(ul_max[2]*x) system_h, system_e = coordinate_histogram(lipid_xyz, xbin, ybin, zbin) histogram, edges = system_h, system_e grid = Grid(histogram, edges=[e * 10 for e in edges]) return grid
def _conclude(self): # concatenate lists into arrays all_coords = np.concatenate(self.coord_list, axis=0) # compute histogram self.data, self.edges = np.histogramdd( all_coords, [self.xedges, self.yedges, self.zedges]) # normalize to occupancy per frame self.data = self.data / self.frame_count # place into a grid object for writing to .dx self.gridobj = Grid(self.data, edges=self.edges)
def test_anyarray(data): ma = np.ma.MaskedArray(data['griddata']) mg = Grid(ma, origin=data['origin'], delta=data['delta']) assert isinstance(mg.grid, ma.__class__) result = f_arithmetic(mg) ref = f_arithmetic(data['grid']) assert_almost_equal(result.grid, ref.grid)
def read_central_ESP(self): ''' Read the one-dimensional ESP along the Z-axis at the center of the x-y plane. Returns ------- out_ESP : array The one-dimensional ESP. ''' lipid = Grid('lipid.dx').grid out_ESP = lipid[int(np.rint(self.grid[0] / 2)), int(np.rint(self.grid[1] / 2)), :] return out_ESP
def density_data(self, dens, quantiles=np.arange(0, 1.05, 0.05)): g = Grid(dens) g_max = np.max(g.grid.flat) g_min = np.min(g.grid.flat) g_mean = np.median(g.grid.flat) g_std = np.std(g.grid.flat) filtered = g.grid[g.grid > 0.001] g_q = np.quantile(filtered.flat, q=quantiles) print(f'Mean: {g_mean}\nSt. dev: {g_std}\nMax: {g_max}\nMin: {g_min}') return (quantiles, g_q, g.grid, g_mean, g_std, g_max, filtered)
def test_gOpenMol(): g = Grid(datafiles.gOpenMol) POINTS = 192 assert g.grid.size == 165048 assert_almost_equal(g.delta, [1.0, 1.0, 1.0]) assert_equal(g.grid.shape, (46, 46, 78)) assert_almost_equal(g.origin, [0.5995016, 0.5995016, 0.5919984]) assert_almost_equal( g.grid[::20, ::20, ::30], np.array([[[1.02196848, 0., 0.88893718], [0.99051529, 0., 0.95906246], [0.96112466, 0., 0.88996845]], [[0.97247058, 0., 0.91574967], [1.00237465, 1.34423399, 0.87810922], [0.97917157, 0., 0.84717268]], [[0.99103099, 0., 0.86521846], [0.96421844, 0., 0.], [0.98432779, 0., 0.8817184]]])) assert_almost_equal(g.grid.mean(), 0.5403224581733577)
def Grid(self, delta, **kwargs): """Package the PMF as a :class:`gridData.Grid` object. *delta* should be the original spacing of the points in angstroem. With a *resample_factor*, the data are interpolated on a new grid with *resample_factor* times as many bins as in the original histogram (See :meth:`gridData.Grid.resample_factor`). *interpolation_order* sets the interpolation order for the resampling procedure. .. Warning:: Interpolating can lead to artifacts in the 3D PMF. If in doubt, **do not resample**. """ from gridData import Grid resample_factor = kwargs.pop('resample_factor', None) kwargs.setdefault('interpolation_spline_order', 3) g = Grid(*self.histogramdd(delta), **kwargs) if not resample_factor: return g return g.resample_factor(resample_factor)
def grid_to_dx(self, save_dir, grid, bin_size, use_channel_names=False): #origin = np.array([7.473, 4.334, 7.701]) - 5.0 if grid.shape[0] % 2 != 0: raise ValueError('Number of channels must be even (%i)' % grid.shape[0]) ch_per_mol = grid.shape[0] / 2 for shift, prefix in [(0, 'rec'), (ch_per_mol, 'lig')]: for ch in range(ch_per_mol): ch += shift if use_channel_names: names = self.prop_table.columns[1:] names *= 2 channel_name = names[ch] else: channel_name = str(ch) g = Grid(grid[ch], origin=np.array([7.473, 4.334, 7.701]) - 5.0, delta=bin_size) g.export(Path(save_dir).joinpath(channel_name + '.dx'), 'DX')
import numpy as np from gridData import Grid import sys import argparse # one PMEpot unit (kT/e) of electrostatic potential is equivalent to 0.0258 Volts. (or 25.8 mV) # Parse inputs parser = argparse.ArgumentParser() parser.add_argument("-f",dest="infile",action="store") parser.add_argument("-e",dest="eField",type=float,action="store") parser.add_argument("-o",dest="outname",action="store") args = parser.parse_args() # Open the .dx from PMEPot, and calculate grid-demensions PMEPotIN = Grid(args.infile) lenx, leny, lenz = PMEPotIN.grid.shape # loop through the z-axis of the reaction potential and add the applied linear-potential for z in range(lenz): for x in range(lenx): for y in range(leny): PMEPotIN.grid[x][y][z] = PMEPotIN.grid[x][y][z] + (z*args.eField) # writeout new potential grid PMEPotIN.export(args.outname+'.dx')
def test_equality(self, data): assert data['grid'] == data['grid'] assert data['grid'] != 'foo' g = Grid(data['griddata'], origin=data['origin'] + 1, delta=data['delta']) assert data['grid'] != g