本文整理汇总了Python中monty.string.list_strings函数的典型用法代码示例。如果您正苦于以下问题:Python list_strings函数的具体用法?Python list_strings怎么用?Python list_strings使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了list_strings函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: merge
def merge(self, workdir, gswfk_file, dfpt_files, gkk_files, out_gkk, binascii=0):
"""
Merge GGK files, return the absolute path of the new database.
Args:
gswfk_file: Ground-state WFK filename
dfpt_files: List of 1WFK files to merge.
gkk_files: List of GKK files to merge.
out_gkk: Name of the output GKK file
binascii: Integer flat. 0 --> binary output, 1 --> ascii formatted output
"""
raise NotImplementedError("This method should be tested")
#out_gkk = out_gkk if cwd is None else os.path.join(os.path.abspath(cwd), out_gkk)
# We work with absolute paths.
gswfk_file = os.path.absath(gswfk_file)
dfpt_files = [os.path.abspath(s) for s in list_strings(dfpt_files)]
gkk_files = [os.path.abspath(s) for s in list_strings(gkk_files)]
print("Will merge %d 1WF files, %d GKK file in output %s" %
(len(dfpt_files), len(gkk_files), out_gkk))
if self.verbose:
for i, f in enumerate(dfpt_files): print(" [%d] 1WF %s" % (i, f))
for i, f in enumerate(gkk_files): print(" [%d] GKK %s" % (i, f))
self.stdin_fname, self.stdout_fname, self.stderr_fname = \
map(os.path.join, 3 * [workdir], ["mrggkk.stdin", "mrggkk.stdout", "mrggkk.stderr"])
inp = StringIO()
inp.write(out_gkk + "\n") # Name of the output file
inp.write(str(binascii) + "\n") # Integer flag: 0 --> binary output, 1 --> ascii formatted output
inp.write(gswfk_file + "\n") # Name of the groud state wavefunction file WF
#dims = len(dfpt_files, gkk_files, ?)
dims = " ".join([str(d) for d in dims])
inp.write(dims + "\n") # Number of 1WF, of GKK files, and number of 1WF files in all the GKK files
# Names of the 1WF files...
for fname in dfpt_files:
inp.write(fname + "\n")
# Names of the GKK files...
for fname in gkk_files:
inp.write(fname + "\n")
self.stdin_data = [s for s in inp.getvalue()]
with open(self.stdin_fname, "w") as fh:
fh.writelines(self.stdin_data)
# Force OS to write data to disk.
fh.flush()
os.fsync(fh.fileno())
self.execute(workdir)
return out_gkk
开发者ID:ExpHP,项目名称:pymatgen,代码行数:57,代码来源:wrappers.py
示例2: read_tensor3_terms
def read_tensor3_terms(self, key, components, itemp=0):
"""
Args:
key: Name of the netcdf variable to read.
components: List of cartesian tensor components to plot e.g. ["xxx", "xyz"].
"all" if all components available on file should be plotted on the same ax.
itemp: Temperature index.
Return:
:class:`OrderedDict` mapping cartesian components e.g. "xyz" to data dictionary.
Individual entries are listed in ALL_CHIS[key]["terms"]
"""
# arrays have Fortran shape [two, nomega, num_comp, ntemp]
if components == "all": components = self.computed_components[key]
components = list_strings(components)
if not (self.ntemp > itemp >= 0):
raise ValueError("Invalid itemp: %s, ntemp: %s" % (itemp, self.ntemp))
od = OrderedDict([(comp, OrderedDict()) for comp in components])
for chiname in ALL_CHIS[key]["terms"]:
#print("About to read:", chiname)
var = self.read_variable(chiname)
for comp in components:
try:
ijkp = self.computed_components[key].index(comp)
except ValueError:
raise ValueError("%s component %s was not computed" % (key, comp))
values = var[itemp, ijkp]
od[comp][chiname] = values[:, 0] + 1j * values[:, 1]
return od
开发者ID:gpetretto,项目名称:abipy,代码行数:30,代码来源:optic.py
示例3: plot_linopt
def plot_linopt(self, select="all", itemp=0, xlims=None, **kwargs):
"""
Subplots with all linear optic quantities selected by ``select`` at temperature ``itemp``.
Args:
select:
itemp: Temperature index.
xlims: Set the data limits for the x-axis. Accept tuple e.g. ``(left, right)``
or scalar e.g. ``left``. If left (right) is None, default values are used.
Returns: |matplotlib-Figure|
"""
key = "linopt"
if not self.reader.computed_components[key]: return None
if select == "all": select = list(LINEPS_WHAT2EFUNC.keys())
select = list_strings(select)
nrows, ncols = len(select), 1
ax_mat, fig, plt = get_axarray_fig_plt(None, nrows=nrows, ncols=ncols,
sharex=True, sharey=False, squeeze=True)
components = self.reader.computed_components[key]
for i, (what, ax) in enumerate(zip(select, ax_mat)):
self.plot_linear_epsilon(what=what, itemp=itemp, components=components,
ax=ax, xlims=xlims, with_xlabel=(i == len(select) - 1),
show=False)
return fig
开发者ID:gpetretto,项目名称:abipy,代码行数:27,代码来源:optic.py
示例4: merge_qpoints
def merge_qpoints(self, workdir, files_to_merge, out_prefix):
"""
Execute mrgscr inside directory `workdir` to merge `files_to_merge`.
Produce new file with prefix `out_prefix`
"""
# We work with absolute paths.
files_to_merge = [os.path.abspath(s) for s in list_strings(files_to_merge)]
nfiles = len(files_to_merge)
if self.verbose:
print("Will merge %d files with output_prefix %s" % (nfiles, out_prefix))
for (i, f) in enumerate(files_to_merge):
print(" [%d] %s" % (i, f))
if nfiles == 1:
raise self.Error("merge_qpoints does not support nfiles == 1")
self.stdin_fname, self.stdout_fname, self.stderr_fname = \
map(os.path.join, 3 * [workdir], ["mrgscr.stdin", "mrgscr.stdout", "mrgscr.stderr"])
inp = cStringIO()
inp.write(str(nfiles) + "\n") # Number of files to merge.
inp.write(out_prefix + "\n") # Prefix for the final output file:
for filename in files_to_merge:
inp.write(filename + "\n") # List with the files to merge.
inp.write("1\n") # Option for merging q-points.
self.stdin_data = [s for s in inp.getvalue()]
with open(self.stdin_fname, "w") as fh:
fh.writelines(self.stdin_data)
self.execute(workdir)
开发者ID:albalu,项目名称:pymatgen,代码行数:35,代码来源:wrappers.py
示例5: from_flow
def from_flow(cls, flow, outdirs="all", nids=None, ext=None, task_class=None):
"""
Build a robot from a |Flow| object.
Args:
flow: |Flow| object
outdirs: String used to select/ignore the files in the output directory of flow, works and tasks
outdirs="work" selects only the outdir of the Works,
outdirs="flow+task" selects the outdir of the Flow and the outdirs of the tasks
outdirs="-work" excludes the outdir of the Works.
Cannot use ``+`` and ``-`` flags in the same string.
Default: `all` that is equivalent to "flow+work+task"
nids: List of node identifiers used to select particular nodes. Not used if None
ext: File extension associated to the robot. Mainly used if method is invoked with the BaseClass
task_class: Task class or string with the class name used to select the tasks in the flow.
None implies no filtering.
Usage example:
.. code-block:: python
with abilab.GsrRobot.from_flow(flow) as robot:
print(robot)
# That is equivalent to:
with Robot.from_flow(flow, ext="GSR") as robot:
print(robot)
Returns:
``Robot`` subclass.
"""
robot = cls() if ext is None else cls.class_for_ext(ext)()
all_opts = ("flow", "work", "task")
if outdirs == "all":
tokens = all_opts
elif "+" in outdirs:
assert "-" not in outdirs
tokens = outdirs.split("+")
elif "-" in outdirs:
assert "+" not in outdirs
tokens = [s for s in all if s not in outdirs.split("-")]
else:
tokens = list_strings(outdirs)
if not all(t in all_opts for t in tokens):
raise ValueError("Wrong outdirs string %s" % outdirs)
if "flow" in tokens:
robot.add_extfile_of_node(flow, nids=nids, task_class=task_class)
if "work" in tokens:
for work in flow:
robot.add_extfile_of_node(work, nids=nids, task_class=task_class)
if "task" in tokens:
for task in flow.iflat_tasks():
robot.add_extfile_of_node(task, nids=nids, task_class=task_class)
return robot
开发者ID:gmatteo,项目名称:abipy,代码行数:60,代码来源:robots.py
示例6: parse
def parse(self, filenames):
"""
Read and parse a filename or a list of filenames.
Files that cannot be opened are ignored. A single filename may also be given.
Return list of successfully read files.
"""
filenames = list_strings(filenames)
read_ok = []
for fname in filenames:
try:
fh = open(fname)
except IOError:
logger.warning("Cannot open file %s" % fname)
continue
try:
self._read(fh, fname)
read_ok.append(fname)
except self.Error as e:
logger.warning("exception while parsing file %s:\n%s" % (fname, str(e)))
continue
finally:
fh.close()
# Add read_ok to the list of files that have been parsed.
self._filenames.extend(read_ok)
return read_ok
开发者ID:sonium0,项目名称:pymatgen,代码行数:31,代码来源:abitimer.py
示例7: remove_variables
def remove_variables(self, keys):
"""Remove the variables listed in keys."""
for key in list_strings(keys):
if key not in self:
raise KeyError("key: %s not in self:\n %s" % (key, list(self.keys())))
#self.pop(key, None)
self.pop(key)
开发者ID:yanikou19,项目名称:abipy,代码行数:7,代码来源:input.py
示例8: from_files
def from_files(cls, filenames, labels=None, abspath=False):
"""
Build a Robot from a list of `filenames`.
if labels is None, labels are automatically generated from absolute paths.
Args:
abspath: True if paths in index should be absolute. Default: Relative to `top`.
"""
filenames = list_strings(filenames)
from abipy.abilab import abiopen
filenames = [f for f in filenames if cls.class_handles_filename(f)]
items = []
for i, f in enumerate(filenames):
try:
abifile = abiopen(f)
except Exception as exc:
cprint("Exception while opening file: `%s`" % str(f), "red")
cprint(exc, "red")
abifile = None
if abifile is not None:
label = abifile.filepath if labels is None else labels[i]
items.append((label, abifile))
new = cls(*items)
if labels is None and not abspath: new.trim_paths(start=None)
return new
开发者ID:gmatteo,项目名称:abipy,代码行数:27,代码来源:robots.py
示例9: from_dojodir
def from_dojodir(cls, top, exclude_basenames=None):
"""
Initialize the table of pseudos for one of the top level directories
located in the pseudo_dojo.pseudos directory.
Args:
exclude_basenames: Optional string or list of strings with the
pseudo basenames to be excluded.
.. warning::
The table may contain multiple pseudos for a given chemical element.
Don't use this method unless you need this feature and you know what
you are doing.
"""
# Read metadata from the __init__.py file
import imp
module_name = os.path.join(top, "__init__.py")
meta = imp.load_source(module_name, os.path.join(top, "__init__.py") )
# Gather all pseudos starting from the current working directory
all_symbols = set(element.symbol for element in PeriodicTable().all_elements)
dirs = [os.path.join(top, d) for d in os.listdir(top) if d in all_symbols]
exclude = set(list_strings(exclude_basenames)) if exclude_basenames is not None else set()
paths = []
for dir in dirs:
paths.extend(os.path.join(dir, f) for f in os.listdir(dir)
if f.endswith(meta.pseudo_ext)
and f not in exclude #!= "Sr-sp.psp8"
)
new = cls(paths).sort_by_z()
return new
开发者ID:vormar,项目名称:pseudo_dojo,代码行数:35,代码来源:pseudos.py
示例10: fix_paths
def fix_paths(self, paths):
"""
Fix the filenames in the iterable paths
Returns:
old2new: Mapping old_path --> new_path
"""
old2new, fixed_exts = {}, []
for path in list_strings(paths):
newpath, ext = self._fix_path(path)
if newpath is not None:
#if ext not in fixed_exts:
# if ext == "1WF": continue
# raise ValueError("Unknown extension %s" % ext)
#print(ext, path, fixed_exts)
#if ext != '1WF':
# assert ext not in fixed_exts
if ext not in fixed_exts:
if ext == "1WF": continue
raise ValueError("Unknown extension %s" % ext)
fixed_exts.append(ext)
old2new[path] = newpath
return old2new
开发者ID:ExpHP,项目名称:pymatgen,代码行数:26,代码来源:utils.py
示例11: find_file
def find_file(files, ext, prefix=None, dataset=None, image=None):
"""
Given a list of file names, return the file with extension "_" + ext, None if not found.
The prefix, the dataset index and the image index can be specified
.. warning::
There are some border cases that will confuse the algorithm
since the order of dataset and image is not tested.
Solving this problem requires the knowledge of ndtset and nimages
This code, however should work in 99.9% of the cases.
"""
separator = "_"
for filename in list_strings(files):
# Remove Netcdf extension (if any)
f = filename[:-3] if filename.endswith(".nc") else filename
if separator not in f: continue
tokens = f.split(separator)
if tokens[-1] == ext:
found = True
if prefix is not None: found = found and filename.startswith(prefix)
if dataset is not None: found = found and "DS" + str(dataset) in tokens
if image is not None: found = found and "IMG" + str(image) in tokens
if found: return filename
else:
return None
开发者ID:akakcolin,项目名称:abipy,代码行数:28,代码来源:utils.py
示例12: __init__
def __init__(self, parent, dirpaths=None, filepaths=None, walk=True, wildcard="", **kwargs):
"""
Args:
parent:
parent window
dirpaths:
List of directories to scan.
filepaths
List of filepaths (absolute paths).
walk:
True if we have to browse all files and directories starting from filepaths.
wildcard
Regular expressions for selecting files (tokens are separated by |).
"""
super(FileListFrame, self).__init__(parent, -1, **kwargs)
if dirpaths is not None:
dirpaths = map(os.path.abspath, list_strings(dirpaths))
else:
dirpaths = []
if filepaths is not None:
filepaths = map(os.path.abspath, list_strings(filepaths))
else:
filepaths = []
wildcard = WildCard(wildcard)
self.all_filepaths = filepaths
if walk:
for dirpath in dirpaths:
for root, dirnames, filenames in os.walk(dirpath):
fnames = [os.path.join(root, f) for f in filenames]
self.all_filepaths += wildcard.filter(fnames)
else:
# Select only the files in dirpaths.
for dirpath in dirpaths:
fnames = [os.path.join(dirpat, f) for f in os.listdir(dirpath)]
fnames = filter(os.path.isfile, fnames)
self.all_filepaths += wildcard.filter(fnames)
self.BuildUi()
开发者ID:gmatteo,项目名称:abipy,代码行数:43,代码来源:browser.py
示例13: vars_with_section
def vars_with_section(self, sections):
"""
List of :class:`Variable` associated to the given sections.
sections can be a string or a list of strings.
"""
sections = set(list_strings(sections))
vars = []
for v in self.values():
if v.section in sections:
vars.append(v)
return vars
开发者ID:temok-mx,项目名称:abipy,代码行数:11,代码来源:abivars_db.py
示例14: edit_files
def edit_files(self, fnames, ask_for_exit=True):
for (idx, fname) in enumerate(list_strings(fnames)):
exit_status = self.edit_file(fname)
if exit_status != 0:
return exit_status
if ask_for_exit and idx != len(fnames) - 1 and _user_wants_to_exit():
break
return 0
开发者ID:akakcolin,项目名称:abipy,代码行数:11,代码来源:iotools.py
示例15: vars_with_char
def vars_with_char(self, chars):
"""
List of :class:`Variable` with the specified characteristic.
chars can be a string or a list of strings.
"""
chars = set(list_strings(chars))
vars = []
for v in self.values():
#if v.characteristic: print(v.characteristic)
if v.characteristic in chars:
vars.append(v)
return vars
开发者ID:temok-mx,项目名称:abipy,代码行数:12,代码来源:abivars_db.py
示例16: get_eos_fits_dataframe
def get_eos_fits_dataframe(self, eos_names="murnaghan"):
"""
Fit energy as function of volume to get the equation of state,
equilibrium volume, bulk modulus and its derivative wrt to pressure.
Args:
eos_names: String or list of strings with EOS names.
For the list of available models, see pymatgen.analysis.eos.
Return:
(fits, dataframe) namedtuple.
fits is a list of ``EOSFit object``
dataframe is a |pandas-DataFrame| with the final results.
"""
# Read volumes and energies from the GSR files.
energies, volumes = [], []
for label, gsr in self.items():
energies.append(float(gsr.energy))
volumes.append(float(gsr.structure.volume))
# Order data by volumes if needed.
if np.any(np.diff(volumes) < 0):
ves = sorted(zip(volumes, energies), key=lambda t: t[0])
volumes = [t[0] for t in ves]
energies = [t[1] for t in ves]
# Note that eos.fit expects lengths in Angstrom, and energies in eV.
# I'm also monkey-patching the plot method.
from pymatgen.analysis.eos import EOS
if eos_names == "all":
# Use all the available models.
eos_names = [n for n in EOS.MODELS if n not in ("deltafactor", "numerical_eos")]
else:
eos_names = list_strings(eos_names)
fits, index, rows = [], [], []
for eos_name in eos_names:
try:
fit = EOS(eos_name=eos_name).fit(volumes, energies)
except Exception as exc:
cprint("EOS %s raised exception:\n%s" % (eos_name, str(exc)))
continue
# Replace plot with plot_ax method
fit.plot = fit.plot_ax
fits.append(fit)
index.append(eos_name)
rows.append(OrderedDict([(aname, getattr(fit, aname)) for aname in
("v0", "e0", "b0_GPa", "b1")]))
dataframe = pd.DataFrame(rows, index=index, columns=list(rows[0].keys()) if rows else None)
return dict2namedtuple(fits=fits, dataframe=dataframe)
开发者ID:gpetretto,项目名称:abipy,代码行数:52,代码来源:gsr.py
示例17: filter
def filter(self, names):
"""
Returns a list with the names matching the pattern.
"""
names = list_strings(names)
fnames = []
for f in names:
for pat in self.pats:
if fnmatch.fnmatch(f, pat):
fnames.append(f)
return fnames
开发者ID:antoinedewandre,项目名称:pymatgen,代码行数:13,代码来源:string_utils.py
示例18: __init__
def __init__(self, parent, filepaths, **kwargs):
"""
Args:
parent:
Parent window.
filepaths:
String or List of strings with filepaths.
"""
super(FileCheckBoxPanel, self).__init__(parent, -1, **kwargs)
self.all_filepaths = list_strings(filepaths)
self.BuildUi()
开发者ID:gmatteo,项目名称:abipy,代码行数:13,代码来源:comparison.py
示例19: from_dojodir
def from_dojodir(cls, top, exclude_wildcard=None, exclude_basenames=None):
"""
Initialize the table from one of the top level directories located
in the pseudo_dojo.pseudos directory.
Args:
top: top level directory
exclude_basenames: Optional string or list of strings with the
pseudo basenames to be excluded.
exclude_wildcard: String of tokens separated by "|". Each token represents a pattern.
to be exluded
Example:
wildcard="*_r.psp8|*.xml" selects only those files that do not end with _r.psp8 or .xml
.. warning::
The table may contain multiple pseudos for a given chemical element.
Don't use this method unless you need this feature and you know what you are doing.
"""
# Read metadata from the __init__.py file
import imp
module_name = os.path.join(top, "__init__.py")
if not os.path.isfile(module_name):
raise RuntimeError("__init_.py file is missing in dir: %s" % top)
meta = imp.load_source(module_name, os.path.join(top, "__init__.py") )
# Gather all pseudos starting from the current working directory
all_symbols = set(e.symbol for e in Element)
dirs = [os.path.join(top, d) for d in os.listdir(top) if d in all_symbols]
exclude = set(list_strings(exclude_basenames)) if exclude_basenames is not None else set()
paths = []
for dr in dirs:
paths.extend(os.path.join(dr, f) for f in os.listdir(dr)
if f.endswith(meta.pseudo_ext) and f not in exclude)
if exclude_wildcard is not None:
wild = WildCard(exclude_wildcard)
paths = [p for p in paths if not wild.match(os.path.basename(p))]
pseudos = []
for p in paths:
pseudo = dojopseudo_from_file(p)
if pseudo is None:
print("Error while parsing:", p)
continue
pseudos.append(pseudo)
return cls(pseudos).sort_by_z()
开发者ID:ebousq,项目名称:pseudo_dojo,代码行数:51,代码来源:pseudos.py
示例20: __init__
def __init__(self, parent, filepaths=(), **kwargs):
"""
Args:
parent:
parent window.
filepaths:
String or list of strings with the path of the nc files to open
Empty tuple if no file should be opened during the initialization of the frame.
"""
if "size" not in kwargs:
kwargs["size"] = (1200, 800)
super(NcViewerFrame, self).__init__(parent, id=-1, **kwargs)
# This combination of options for config seems to work on my Mac.
self.config = wx.FileConfig(appName=self.codename, localFilename=self.codename + ".ini",
style=wx.CONFIG_USE_LOCAL_FILE)
# Build menu, toolbar and status bar.
self.makeMenu()
self.makeToolBar()
self.statusbar = self.CreateStatusBar()
# Open netcdf files.
filepaths, datasets = list_strings(filepaths), []
filepaths = map(os.path.abspath, filepaths)
for path in filepaths:
datasets.append(netCDF4.Dataset(path, mode="r"))
self.AddFileToHistory(path)
# Create the notebook (each file will have its own tab).
panel = wx.Panel(self, -1)
try:
self.notebook = fnb.FlatNotebook(panel, -1, style=fnb.FNB_NAV_BUTTONS_WHEN_NEEDED)
except AttributeError:
self.notebook = fnb.FlatNotebook(panel, -1)
for path, dataset in zip(filepaths, datasets):
tab = NcFileTab(self.notebook, dataset)
self.notebook.AddPage(tab, os.path.basename(path))
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.notebook, 1, wx.EXPAND, 5)
panel.SetSizerAndFit(sizer)
self.Bind(wx.EVT_CLOSE, self.OnExit)
# Intercept the command event associated to variable/dimension comparison.
self.Bind(EVT_COMPARE, self.OnCompare)
开发者ID:GkAntonius,项目名称:abipy,代码行数:50,代码来源:wxncview.py
注:本文中的monty.string.list_strings函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论