Coverage for ase/cli/find.py: 20.55%
73 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1# Note:
2# Try to avoid module level import statements here to reduce
3# import time during CLI execution
4import sys
7class CLICommand:
8 """Find files with atoms in them.
10 Search through files known to ASE applying a query to filter the results.
12 See https://docs.ase-lib.org/ase/db/db.html#querying for more
13 informations on how to construct the query string.
14 """
16 @staticmethod
17 def add_arguments(parser):
18 parser.add_argument('folder', help='Folder to look in.')
19 parser.add_argument(
20 'query',
21 nargs='?',
22 help='Examples: More than 2 hydrogens and no silver: "H>2,Ag=0". '
23 'More than 1000 atoms: "natoms>1000". '
24 'Slab geometry containing Cu and Ni: "pbc=TTF,Cu,Ni".',
25 )
26 parser.add_argument(
27 '-v', '--verbose', action='store_true', help='More output.'
28 )
29 parser.add_argument(
30 '-l',
31 '--long',
32 action='store_true',
33 help='Show also periodic boundary conditions, '
34 'chemical formula and filetype.',
35 )
36 parser.add_argument(
37 '-i',
38 '--include',
39 help='Include only filenames '
40 'ending with given strings. Example: '
41 '"-i .xyz,.traj".',
42 )
43 parser.add_argument(
44 '-x',
45 '--exclude',
46 help='Exclude filenames '
47 'ending with given strings. Example: '
48 '"-x .cif".',
49 )
51 @staticmethod
52 def run(args):
53 main(args)
56def main(args):
57 from ase.db.core import parse_selection
59 query = parse_selection(args.query)
60 include = args.include.split(',') if args.include else []
61 exclude = args.exclude.split(',') if args.exclude else []
63 if args.long:
64 print('pbc {:10} {:15} path'.format('formula', 'filetype'))
66 for path in allpaths(args.folder, include, exclude):
67 format, row = check(path, query, args.verbose)
68 if format:
69 if args.long:
70 print(
71 '{} {:10} {:15} {}'.format(
72 ''.join(str(p) for p in row.pbc.astype(int)),
73 row.formula,
74 format,
75 path,
76 )
77 )
78 else:
79 print(path)
82def allpaths(folder, include, exclude):
83 """Generate paths."""
84 import os
85 import os.path as op
87 exclude += ['.py', '.pyc']
88 for dirpath, dirnames, filenames in os.walk(folder):
89 for name in filenames:
90 if any(name.endswith(ext) for ext in exclude):
91 continue
92 if include:
93 for ext in include:
94 if name.endswith(ext):
95 break
96 else:
97 continue
98 path = op.join(dirpath, name)
99 yield path
101 # Skip .git, __pycache__ and friends:
102 dirnames[:] = (name for name in dirnames if name[0] not in '._')
105def check(path, query, verbose):
106 """Check a path.
108 Returns a (filetype, AtomsRow object) tuple.
109 """
110 from ase.db import connect
111 from ase.db.jsondb import JSONDatabase
112 from ase.db.row import atoms2dict
113 from ase.io import read
114 from ase.io.formats import UnknownFileTypeError, filetype
116 class FakeDB(JSONDatabase):
117 def __init__(self, atoms):
118 self.bigdct = {1: atoms2dict(atoms)}
120 def _read_json(self):
121 return self.bigdct, [1], 2
123 try:
124 format = filetype(path, guess=False)
125 except (OSError, UnknownFileTypeError):
126 return '', None
128 if format in ['db', 'json']:
129 db = connect(path)
130 else:
131 try:
132 atoms = read(path, format=format)
133 except Exception as x:
134 if verbose:
135 print(path + ':', x, file=sys.stderr)
136 return '', None
137 db = FakeDB(atoms)
139 try:
140 for row in db._select(*query):
141 return format, row
142 except Exception as x:
143 if verbose:
144 print(path + ':', x, file=sys.stderr)
146 return '', None