def writetxt(fn, arr, axis=-1, maxdim=TXT_MAXDIM, header=True): """Write 1d, 2d or 3d arrays to txt file. If 3d, write as 2d chunks. Take the 2d chunks along `axis`. Write a commented out ini-style header in the file with infos needed by readtxt() to restore the right shape. Parameters ---------- fn : filename arr : nd array axis : axis along which 2d chunks are written maxdim : highest number of dims that `arr` is allowed to have header : bool Write ini style header. Can be used by readtxt(). """ verbose("[writetxt] writing: %s" %fn) common.assert_cond(arr.ndim <= maxdim, 'no rank > %i arrays supported' %maxdim) fh = open(fn, 'wb+') if header: c = ConfigParser() sec = 'array' c.add_section(sec) c.set(sec, 'shape', common.seq2str(arr.shape)) c.set(sec, 'axis', str(axis)) _write_header_config(fh, c) # 1d and 2d case if arr.ndim < maxdim: np.savetxt(fh, arr) # 3d else: # TODO get rid of loop? # write 2d arrays, one by one sl = [slice(None)]*arr.ndim for ind in range(arr.shape[axis]): sl[axis] = ind np.savetxt(fh, arr[sl]) fh.close()
def writetxt(fn, arr, axis=-1, maxdim=TXT_MAXDIM, header=True): """Write 1d, 2d or 3d arrays to txt file. If 3d, write as 2d chunks. Take the 2d chunks along `axis`. Write a commented out ini-style header in the file with infos needed by readtxt() to restore the right shape. Parameters ---------- fn : filename arr : nd array axis : axis along which 2d chunks are written maxdim : highest number of dims that `arr` is allowed to have header : bool Write ini style header. Can be used by readtxt(). """ verbose("[writetxt] writing: %s" %fn) common.assert_cond(arr.ndim <= maxdim, 'no rank > %i arrays supported' %maxdim) fh = open(fn, 'w+') if header: c = PydosConfigParser() sec = 'array' c.add_section(sec) c.set(sec, 'shape', common.seq2str(arr.shape)) c.set(sec, 'axis', axis) _write_header_config(fh, c) # 1d and 2d case if arr.ndim < maxdim: np.savetxt(fh, arr) # 3d else: # TODO get rid of loop? # write 2d arrays, one by one sl = [slice(None)]*arr.ndim for ind in range(arr.shape[axis]): sl[axis] = ind np.savetxt(fh, arr[sl]) fh.close()
def plot_dis(path_norm, freqs, special_points_path=None, show_coords=None, dos=None, ax=None, ylim=None, **kwargs): """Plot dispersion. See ``bin/plot_dispersion.py`` for a usage example. This lives here (and not in :mod:`~pwtools.pwscf`) b/c it is not PWscf-specific. It can be used for any dispersion data (band structure). See :func:`~pwtools.pwscf.read_matdyn_freq` for how to get `freqs` in the case of phonon dispersions. This function is a convenience function, which can even plot the DOS as well. We do not expose many matplotlib parameters here. If you want to tweak your plot much, then operate on the returned `fig`, `ax` (dispersion) and `axdos` (dos), or copy and hack the function, which might be actually the easiest way. Parameters ---------- path_norm : array (nks,) x-axis with cumulative norms of points along the k-path, see :func:`get_path_norm` freqs : array (nks, nbnd) `nbnd` frequencies for each band at each k-point special_points_path : optional, :class:`SpecialPointsPath` instance used for pretty-printing the x-axis (set special point labels) show_coords : 'cart', 'frac', None Show the cartesian or fractional coordinates of special points in the x-axis label, on neither if None. dos : array (N,2) or None array with phonon dos to plot: ``dos[:,0]=freq``, ``dos[:,1]=phdos`` ax : matplotlib AxesSubplot (e.g. from ``fig,ax=pwtools.mpl.fig_ax()``) automatically created if None ylim : tuple (2,) frequency axis limits **kwargs : keywords passed to plot() Returns ------- fig, ax, axdos fig : matplotlib Figure to ax ax : matplotlib AxesSubplot with dispersion axdos : matplotlib AxesSubplot with dos, or None if `dos=None` Examples -------- >>> spp = kpath.SpecialPointsPath(ks=np.array([[0,0,0], [1.5,0,0], [2.3,0,0]]), symbols=['A', 'B', 'C']) >>> path_norm = np.linspace(0,2.5,100) >>> freqs = np.random.rand(100,5)*500 >>> # create fig,ax inside, returned axdos=None >>> fig,ax,axdos = kpath.plot_dis(path_norm, freqs, spp) >>> # pass ax from outside, returns fig,ax but we don't use that b/c ax >>> # is in-place modified >>> fig,ax = mpl.fig_ax() >>> kpath.plot_dis(path_norm, freqs, spp, ax=ax) >>> # plot also DOS >>> dos = np.empty((30,2)); dos[:,0]=np.linspace(0,500,30); dos[:,1]=rand(30) >>> fig,ax,axdos = kpath.plot_dis(path_norm, freqs, spp, dos=dos) See Also -------- :func:`get_path_norm` :func:`pwtools.pwscf.read_matdyn_freq` :ref:`dispersion_example` """ if ax is None: fig, ax = mpl.fig_ax() else: fig = ax.get_figure() # Plot columns of `freq` against q points (path_norm) ax.plot(path_norm, freqs, **kwargs) if special_points_path is not None: ylim = ax.get_ylim() if ylim is None else ylim ks, ks_frac, nrm, symbols = \ special_points_path.ks, \ special_points_path.ks_frac, \ special_points_path.path_norm, \ special_points_path.symbols ax.vlines(nrm, ylim[0], ylim[1]) fmtfunc = lambda x: "%.2g" % x if show_coords is None: labels = symbols else: if show_coords == 'cart': ks_plot = ks elif show_coords == 'frac': ks_plot = ks_frac else: raise Exception("show_coords = 'cart', 'frac' or " "None needed") labels = ['%s\n[%s]' %(sym, common.seq2str(kk, func=fmtfunc,sep=','))\ for sym,kk in zip(symbols, ks_plot)] ax.set_xticks(nrm) ax.set_xticklabels(labels) ax.set_xlim(path_norm[0], path_norm[-1]) ax.set_ylabel("frequency (cm$^{-1}$)") if dos is not None: # http://matplotlib.org/examples/axes_grid/scatter_hist.html from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) axdos = divider.append_axes("right", 1.2, pad=0.1, sharey=ax) axdos.plot(dos[:, 1], dos[:, 0], 'b') mpl.plt.setp(axdos.get_yticklabels(), visible=False) mpl.plt.setp(axdos.get_xticklabels(), visible=False) axdos.xaxis.set_tick_params(size=0) else: axdos = None return fig, ax, axdos
} for ii, cd in enumerate(celldm): rules['cd%i' %(ii+1,)] = cd print out.format(**rules) #------------------------------------------------------------------------------- # ABINIT #------------------------------------------------------------------------------- print "\n" print bar print "ABINIT" print bar print "natom %i" %struct.natoms print "ntypat %i" %struct.ntypat print "typat %s" %seq2str(struct.typat) print "znucl %s" %seq2str(struct.znucl) print "acell %s" %str_arr(struct.cryst_const[:3]) print "angdeg %s" %str_arr(struct.cryst_const[3:]) print "xred\n%s" %str_arr(struct.coords_frac) print "pseudopotential order:\n%s" %"\n".join(["%s %i" %(sym, zz) for sym,zz in zip(struct.symbols_unique, struct.znucl)]) #------------------------------------------------------------------------------- # CPMD #------------------------------------------------------------------------------- print "\n" print bar print "CPMD" print bar
} for ii, cd in enumerate(celldm): rules['cd%i' % (ii + 1, )] = cd print(out.format(**rules)) #------------------------------------------------------------------------------- # ABINIT #------------------------------------------------------------------------------- print("\n") print(bar) print("ABINIT") print(bar) print("natom %i" % struct.natoms) print("ntypat %i" % struct.ntypat) print("typat %s" % seq2str(struct.typat)) print("znucl %s" % seq2str(struct.znucl)) print("acell %s" % str_arr(struct.cryst_const[:3])) print("angdeg %s" % str_arr(struct.cryst_const[3:])) print("xred\n%s" % str_arr(struct.coords_frac)) print("pseudopotential order:\n%s" % "\n".join([ "%s %i" % (sym, zz) for sym, zz in zip(struct.symbols_unique, struct.znucl) ])) #------------------------------------------------------------------------------- # CPMD #------------------------------------------------------------------------------- print("\n") print(bar) print("CPMD") print(bar)
def plot_dis(path_norm, freqs, special_points_path=None, show_coords=None, dos=None, ax=None, ylim=None, **kwargs): """Plot dispersion. See ``bin/plot_dispersion.py`` for a usage example. This lives here (and not in :mod:`~pwtools.pwscf`) b/c it is not PWscf-specific. It can be used for any dispersion data (band structure). See :func:`~pwtools.pwscf.read_matdyn_freq` for how to get `freqs` in the case of phonon dispersions. This function is a convenience function, which can even plot the DOS as well. We do not expose many matplotlib parameters here. If you want to tweak your plot much, then operate on the returned `fig`, `ax` (dispersion) and `axdos` (dos), or copy and hack the function, which might be actually the easiest way. Parameters ---------- path_norm : array (nks,) x-axis with cumulative norms of points along the k-path, see :func:`get_path_norm` freqs : array (nks, nbnd) `nbnd` frequencies for each band at each k-point special_points_path : optional, :class:`SpecialPointsPath` instance used for pretty-printing the x-axis (set special point labels) show_coords : 'cart', 'frac', None Show the cartesian or fractional coordinates of special points in the x-axis label, on neither if None. dos : array (N,2) or None array with phonon dos to plot: ``dos[:,0]=freq``, ``dos[:,1]=phdos`` ax : matplotlib AxesSubplot (e.g. from ``fig,ax=pwtools.mpl.fig_ax()``) automatically created if None ylim : tuple (2,) frequency axis limits **kwargs : keywords passed to plot() Returns ------- fig, ax, axdos fig : matplotlib Figure to ax ax : matplotlib AxesSubplot with dispersion axdos : matplotlib AxesSubplot with dos, or None if `dos=None` Examples -------- >>> spp = kpath.SpecialPointsPath(ks=np.array([[0,0,0], [1.5,0,0], [2.3,0,0]]), symbols=['A', 'B', 'C']) >>> path_norm = np.linspace(0,2.5,100) >>> freqs = np.random.rand(100,5)*500 >>> # create fig,ax inside, returned axdos=None >>> fig,ax,axdos = kpath.plot_dis(path_norm, freqs, spp) >>> # pass ax from outside, returns fig,ax but we don't use that b/c ax >>> # is in-place modified >>> fig,ax = mpl.fig_ax() >>> kpath.plot_dis(path_norm, freqs, spp, ax=ax) >>> # plot also DOS >>> dos = np.empty((30,2)); dos[:,0]=np.linspace(0,500,30); dos[:,1]=rand(30) >>> fig,ax,axdos = kpath.plot_dis(path_norm, freqs, spp, dos=dos) See Also -------- :func:`get_path_norm` :func:`pwtools.pwscf.read_matdyn_freq` :ref:`dispersion_example` """ if ax is None: fig, ax = mpl.fig_ax() else: fig = ax.get_figure() # Plot columns of `freq` against q points (path_norm) ax.plot(path_norm, freqs, **kwargs) if special_points_path is not None: ylim = ax.get_ylim() if ylim is None else ylim ks, ks_frac, nrm, symbols = ( special_points_path.ks, special_points_path.ks_frac, special_points_path.path_norm, special_points_path.symbols, ) ax.vlines(nrm, ylim[0], ylim[1]) fmtfunc = lambda x: "%.2g" % x if show_coords is None: labels = symbols else: if show_coords == "cart": ks_plot = ks elif show_coords == "frac": ks_plot = ks_frac else: raise StandardError("show_coords = 'cart', 'frac' or " "None needed") labels = [ "%s\n[%s]" % (sym, common.seq2str(kk, func=fmtfunc, sep=",")) for sym, kk in zip(symbols, ks_plot) ] ax.set_xticks(nrm) ax.set_xticklabels(labels) ax.set_xlim(path_norm[0], path_norm[-1]) ax.set_ylabel("frequency (cm$^{-1}$)") if dos is not None: # http://matplotlib.org/examples/axes_grid/scatter_hist.html from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax) axdos = divider.append_axes("right", 1.2, pad=0.1, sharey=ax) axdos.plot(dos[:, 1], dos[:, 0], "b") mpl.plt.setp(axdos.get_yticklabels(), visible=False) mpl.plt.setp(axdos.get_xticklabels(), visible=False) axdos.xaxis.set_tick_params(size=0) else: axdos = None return fig, ax, axdos