Debian Codegraph @

cclib/io/ccio.py

raw ◀ ▶
1 Debian patch touch this file
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2019, the cclib development team
4 #
5 # This file is part of cclib (http://cclib.github.io) and is distributed under
6 # the terms of the BSD 3-Clause License.
7 """Tools for identifying, reading and writing files and streams."""
8
9 from __future__ import print_function
10
11 import atexit
12 import io
13 import os
14 import sys
15 import re
16 from tempfile import NamedTemporaryFile
17
18 # We want this as long as we need to support both Python 2 and 3.
19 from six import string_types
20
21 # Python 2->3 changes the default file object hierarchy.
22 if sys.version_info[0] == 2:
23 fileclass = file
24
25 from urllib2 import urlopen, URLError
26 else:
27 fileclass = io.IOBase
28
29 from urllib.request import urlopen
30 from urllib.error import URLError
31
32
33 from cclib.parser import data
34 from cclib.parser import logfileparser
35 from cclib.parser.utils import find_package
36
37 from cclib.parser.adfparser import ADF
38 from cclib.parser.daltonparser import DALTON
39 from cclib.parser.gamessparser import GAMESS
40 from cclib.parser.gamessukparser import GAMESSUK
41 from cclib.parser.gaussianparser import Gaussian
42 from cclib.parser.jaguarparser import Jaguar
43 from cclib.parser.molcasparser import Molcas
44 from cclib.parser.molproparser import Molpro
45 from cclib.parser.mopacparser import MOPAC
46 from cclib.parser.nwchemparser import NWChem
47 from cclib.parser.orcaparser import ORCA
48 from cclib.parser.psi3parser import Psi3
49 from cclib.parser.psi4parser import Psi4
50 from cclib.parser.qchemparser import QChem
51 from cclib.parser.turbomoleparser import Turbomole
52
53 from cclib.io import cjsonreader
54 from cclib.io import cjsonwriter
55 from cclib.io import cmlwriter
56 from cclib.io import moldenwriter
57 from cclib.io import wfxwriter
58 from cclib.io import xyzreader
59 from cclib.io import xyzwriter
60
61 _has_cclib2openbabel = find_package("openbabel")
62 if _has_cclib2openbabel:
63 from cclib.bridge import cclib2openbabel
64
65 _has_pandas = find_package("pandas")
66 if _has_pandas:
67 import pandas as pd
68
69 # Regular expression for validating URLs
70 URL_PATTERN = re.compile(
71
72 r'^(?:http|ftp)s?://' # http:// or https://
73 r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
74 r'localhost|' # localhost...
75 r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
76 r'(?::\d+)?' # optional port
77 r'(?:/?|[/?]\S+)$', re.IGNORECASE
78
79 )
80
81 # Parser choice is triggered by certain phrases occurring the logfile. Where these
82 # strings are unique, we can set the parser and break. In other cases, the situation
83 # is a little but more complicated. Here are the exceptions:
84 # 1. The GAMESS trigger also works for GAMESS-UK files, so we can't break
85 # after finding GAMESS in case the more specific phrase is found.
86 # 2. Molpro log files don't have the program header, but always contain
87 # the generic string 1PROGRAM, so don't break here either to be cautious.
88 # 3. "MOPAC" is used in some packages like GAMESS, so match MOPAC20##
89 #
90 # The triggers are defined by the tuples in the list below like so:
91 # (parser, phrases, flag whether we should break)
92 triggers = [
93
94 (ADF, ["Amsterdam Density Functional"], True),
95 (DALTON, ["Dalton - An Electronic Structure Program"], True),
96 (GAMESS, ["GAMESS"], False),
97 (GAMESS, ["GAMESS VERSION"], True),
98 (GAMESSUK, ["G A M E S S - U K"], True),
99 (Gaussian, ["Gaussian, Inc."], True),
100 (Jaguar, ["Jaguar"], True),
101 (Molcas, ["MOLCAS"], True),
102 (Molpro, ["PROGRAM SYSTEM MOLPRO"], True),
103 (Molpro, ["1PROGRAM"], False),
104 (MOPAC, ["MOPAC20"], True),
105 (NWChem, ["Northwest Computational Chemistry Package"], True),
106 (ORCA, ["O R C A"], True),
107 (Psi3, ["PSI3: An Open-Source Ab Initio Electronic Structure Package"], True),
108 (Psi4, ["Psi4: An Open-Source Ab Initio Electronic Structure Package"], True),
109 (QChem, ["A Quantum Leap Into The Future Of Chemistry"], True),
110 (Turbomole, ["TURBOMOLE"], True),
111
112 ]
113
114 readerclasses = {
115 'cjson': cjsonreader.CJSON,
116 'json': cjsonreader.CJSON,
117 'xyz': xyzreader.XYZ,
118 }
119
120 writerclasses = {
121 'cjson': cjsonwriter.CJSON,
122 'json': cjsonwriter.CJSON,
123 'cml': cmlwriter.CML,
124 'molden': moldenwriter.MOLDEN,
125 'wfx': wfxwriter.WFXWriter,
126 'xyz': xyzwriter.XYZ,
127 }
128
129
130 class UnknownOutputFormatError(Exception):
131 """Raised when an unknown output format is encountered."""
132
133
134 def guess_filetype(inputfile):
135 """Try to guess the filetype by searching for trigger strings."""
136 if not inputfile:
137 return None
138
139 filetype = None
140 if isinstance(inputfile, string_types):
141 for line in inputfile:
142 for parser, phrases, do_break in triggers:
143 if all([line.lower().find(p.lower()) >= 0 for p in phrases]):
144 filetype = parser
145 if do_break:
146 return filetype
147 else:
148 for fname in inputfile:
149 for line in inputfile:
150 for parser, phrases, do_break in triggers:
151 if all([line.lower().find(p.lower()) >= 0 for p in phrases]):
152 filetype = parser
153 if do_break:
154 return filetype
155 return filetype
156
157
158 def ccread(source, *args, **kwargs):
159 """Attempt to open and read computational chemistry data from a file.
160
161 If the file is not appropriate for cclib parsers, a fallback mechanism
162 will try to recognize some common chemistry formats and read those using
163 the appropriate bridge such as Open Babel.
164
165 Inputs:
166 source - a single logfile, a list of logfiles (for a single job),
167 an input stream, or an URL pointing to a log file.
168 *args, **kwargs - arguments and keyword arguments passed to ccopen
169 Returns:
170 a ccData object containing cclib data attributes
171 """
172
173 log = ccopen(source, *args, **kwargs)
174 if log:
175 if kwargs.get('verbose', None):
176 print('Identified logfile to be in %s format' % log.logname)
177 # If the input file is a CJSON file and not a standard compchemlog file
178 cjson_as_input = kwargs.get("cjson", False)
179 if cjson_as_input:
180 return log.read_cjson()
181 else:
182 return log.parse()
183 else:
184 if kwargs.get('verbose', None):
185 print('Attempting to use fallback mechanism to read file')
186 return fallback(source)
187
188
189 def ccopen(source, *args, **kwargs):
190 """Guess the identity of a particular log file and return an instance of it.
191
192 Inputs:
193 source - a single logfile, a list of logfiles (for a single job),
194 an input stream, or an URL pointing to a log file.
195 *args, **kwargs - arguments and keyword arguments passed to filetype
196
197 Returns:
198 one of ADF, DALTON, GAMESS, GAMESS UK, Gaussian, Jaguar,
199 Molpro, MOPAC, NWChem, ORCA, Psi3, Psi/Psi4, QChem, CJSON or None
200 (if it cannot figure it out or the file does not exist).
201 """
202 inputfile = None
203 is_stream = False
204
205 # Check if source is a link or contains links. Retrieve their content.
206 # Try to open the logfile(s), using openlogfile, if the source is a string (filename)
207 # or list of filenames. If it can be read, assume it is an open file object/stream.
208 is_string = isinstance(source, str)
209 is_url = True if is_string and URL_PATTERN.match(source) else False
210 is_listofstrings = isinstance(source, list) and all([isinstance(s, str) for s in source])
211 if is_string or is_listofstrings:
212 # Process links from list (download contents into temporary location)
213 if is_listofstrings:
214 filelist = []
215 for filename in source:
216 if not URL_PATTERN.match(filename):
217 filelist.append(filename)
218 else:
219 try:
220 response = urlopen(filename)
221 tfile = NamedTemporaryFile(delete=False)
222 tfile.write(response.read())
223 # Close the file because Windows won't let open it second time
224 tfile.close()
225 filelist.append(tfile.name)
226 # Delete temporary file when the program finishes
227 atexit.register(os.remove, tfile.name)
228 except (ValueError, URLError) as error:
229 if not kwargs.get('quiet', False):
230 (errno, strerror) = error.args
231 return None
232 source = filelist
233
234 if not is_url:
235 try:
236 inputfile = logfileparser.openlogfile(source)
237 except IOError as error:
238 if not kwargs.get('quiet', False):
239 (errno, strerror) = error.args
240 return None
241 else:
242 try:
243 response = urlopen(source)
244 is_stream = True
245
246 # Retrieve filename from URL if possible
247 filename = re.findall("\w+\.\w+", source.split('/')[-1])
248 filename = filename[0] if filename else ""
249
250 inputfile = logfileparser.openlogfile(filename, object=response.read())
251 except (ValueError, URLError) as error:
252 if not kwargs.get('quiet', False):
253 (errno, strerror) = error.args
254 return None
255
256 elif hasattr(source, "read"):
257 inputfile = source
258 is_stream = True
259
260 # Streams are tricky since they don't have seek methods or seek won't work
261 # by design even if it is present. We solve this now by reading in the
262 # entire stream and using a StringIO buffer for parsing. This might be
263 # problematic for very large streams. Slow streams might also be an issue if
264 # the parsing is not instantaneous, but we'll deal with such edge cases
265 # as they arise. Ideally, in the future we'll create a class dedicated to
266 # dealing with these issues, supporting both files and streams.
267 if is_stream:
268 try:
269 inputfile.seek(0, 0)
270 except (AttributeError, IOError):
271 contents = inputfile.read()
272 try:
273 inputfile = io.StringIO(contents)
274 except:
275 inputfile = io.StringIO(unicode(contents))
276 inputfile.seek(0, 0)
277
278 # Proceed to return an instance of the logfile parser only if the filetype
279 # could be guessed. Need to make sure the input file is closed before creating
280 # an instance, because parsers will handle opening/closing on their own.
281 filetype = guess_filetype(inputfile)
282
283 # If the input file isn't a standard compchem log file, try one of
284 # the readers, falling back to Open Babel.
285 if not filetype:
286 if kwargs.get("cjson"):
287 filetype = readerclasses['cjson']
288 elif source and not is_stream:
289 ext = os.path.splitext(source)[1][1:].lower()
290 for extension in readerclasses:
291 if ext == extension:
292 filetype = readerclasses[extension]
293
294 # Proceed to return an instance of the logfile parser only if the filetype
295 # could be guessed. Need to make sure the input file is closed before creating
296 # an instance, because parsers will handle opening/closing on their own.
297 if filetype:
298 # We're going to close and reopen below anyway, so this is just to avoid
299 # the missing seek method for fileinput.FileInput. In the long run
300 # we need to refactor to support for various input types in a more
301 # centralized fashion.
302 if is_listofstrings:
303 pass
304 else:
305 inputfile.seek(0, 0)
306 if not is_stream:
307 if is_listofstrings:
308 if filetype == Turbomole:
309 source = sort_turbomole_outputs(source)
310 inputfile.close()
311 return filetype(source, *args, **kwargs)
312 return filetype(inputfile, *args, **kwargs)
313
314
315 def fallback(source):
316 """Attempt to read standard molecular formats using other libraries.
317
318 Currently this will read XYZ files with OpenBabel, but this can easily
319 be extended to other formats and libraries, too.
320 """
321
322 if isinstance(source, str):
323 ext = os.path.splitext(source)[1][1:].lower()
324 if _has_cclib2openbabel:
•325 import openbabel.pybel as pb
326 if ext in pb.informats:
327 return cclib2openbabel.readfile(source, ext)
328 else:
329 print("Could not import `openbabel`, fallback mechanism might not work.")
330
331
332 def ccwrite(ccobj, outputtype=None, outputdest=None,
333 indices=None, terse=False, returnstr=False,
334 *args, **kwargs):
335 """Write the parsed data from an outputfile to a standard chemical
336 representation.
337
338 Inputs:
339 ccobj - Either a job (from ccopen) or a data (from job.parse()) object
340 outputtype - The output format (should be a string)
341 outputdest - A filename or file object for writing
342 indices - One or more indices for extracting specific geometries/etc. (zero-based)
343 terse - This option is currently limited to the cjson/json format. Whether to indent the cjson/json or not
344 returnstr - Whether or not to return a string representation.
345
346 The different writers may take additional arguments, which are
347 documented in their respective docstrings.
348
349 Returns:
350 the string representation of the chemical datatype
351 requested, or None.
352 """
353
354 # Determine the correct output format.
355 outputclass = _determine_output_format(outputtype, outputdest)
356
357 # Is ccobj an job object (unparsed), or is it a ccdata object (parsed)?
358 if isinstance(ccobj, logfileparser.Logfile):
359 jobfilename = ccobj.filename
360 ccdata = ccobj.parse()
361 elif isinstance(ccobj, data.ccData):
362 jobfilename = None
363 ccdata = ccobj
364 else:
365 raise ValueError
366
367 # If the logfile name has been passed in through kwargs (such as
368 # in the ccwrite script), make sure it has precedence.
369 if 'jobfilename' in kwargs:
370 jobfilename = kwargs['jobfilename']
371 # Avoid passing multiple times into the main call.
372 del kwargs['jobfilename']
373
374 outputobj = outputclass(ccdata, jobfilename=jobfilename,
375 indices=indices, terse=terse,
376 *args, **kwargs)
377 output = outputobj.generate_repr()
378
379 # If outputdest isn't None, write the output to disk.
380 if outputdest is not None:
381 if isinstance(outputdest, str):
382 with open(outputdest, 'w') as outputobj:
383 outputobj.write(output)
384 elif isinstance(outputdest, fileclass):
385 outputdest.write(output)
386 else:
387 raise ValueError
388 # If outputdest is None, return a string representation of the output.
389 else:
390 return output
391
392 if returnstr:
393 return output
394
395
396 def _determine_output_format(outputtype, outputdest):
397 """
398 Determine the correct output format.
399
400 Inputs:
401 outputtype - a string corresponding to the file type
402 outputdest - a filename string or file handle
403 Returns:
404 outputclass - the class corresponding to the correct output format
405 Raises:
406 UnknownOutputFormatError for unsupported file writer extensions
407 """
408
409 # Priority for determining the correct output format:
410 # 1. outputtype
411 # 2. outputdest
412
413 outputclass = None
414 # First check outputtype.
415 if isinstance(outputtype, str):
416 extension = outputtype.lower()
417 if extension in writerclasses:
418 outputclass = writerclasses[extension]
419 else:
420 raise UnknownOutputFormatError(extension)
421 else:
422 # Then checkout outputdest.
423 if isinstance(outputdest, str):
424 extension = os.path.splitext(outputdest)[1].lower()
425 elif isinstance(outputdest, fileclass):
426 extension = os.path.splitext(outputdest.name)[1].lower()
427 else:
428 raise UnknownOutputFormatError
429 if extension in writerclasses:
430 outputclass = writerclasses[extension]
431 else:
432 raise UnknownOutputFormatError(extension)
433
434 return outputclass
435
436 def path_leaf(path):
437 """
438 Splits the path to give the filename. Works irrespective of '\'
439 or '/' appearing in the path and also with path ending with '/' or '\'.
440
441 Inputs:
442 path - a string path of a logfile.
443 Returns:
444 tail - 'directory/subdirectory/logfilename' will return 'logfilename'.
445 ntpath.basename(head) - 'directory/subdirectory/logfilename/' will return 'logfilename'.
446 """
447 head, tail = os.path.split(path)
448 return tail or os.path.basename(head)
449
450 def sort_turbomole_outputs(filelist):
451 """
452 Sorts a list of inputs (or list of log files) according to the order
453 defined below. Just appends the unknown files in the end of the sorted list.
454
455 Inputs:
456 filelist - a list of Turbomole log files needed to be parsed.
457 Returns:
458 sorted_list - a sorted list of Turbomole files needed for proper parsing.
459 """
460 sorting_order = {
461 'basis' : 0,
462 'control' : 1,
463 'mos' : 2,
464 'alpha' : 3,
465 'beta' : 4,
466 'job.last' : 5,
467 'coord' : 6,
468 'gradient' : 7,
469 'aoforce' : 8,
470 }
471
472 known_files = []
473 unknown_files = []
474 sorted_list = []
475 for fname in filelist:
476 filename = path_leaf(fname)
477 if filename in sorting_order:
478 known_files.append([fname, sorting_order[filename]])
479 else:
480 unknown_files.append(fname)
481 for i in sorted(known_files, key=lambda x: x[1]):
482 sorted_list.append(i[0])
483 if unknown_files:
484 sorted_list.extend(unknown_files)
485 return sorted_list
486
487
488 def _check_pandas(found_pandas):
489 if not found_pandas:
490 raise ImportError("You must install `pandas` to use this function")
491
492
493 def ccframe(ccobjs, *args, **kwargs):
494 """Returns a pandas.DataFrame of data attributes parsed by cclib from one
495 or more logfiles.
496
497 Inputs:
498 ccobjs - an iterable of either cclib jobs (from ccopen) or data (from
499 job.parse()) objects
500
501 Returns:
502 a pandas.DataFrame
503 """
504 _check_pandas(_has_pandas)
505 logfiles = []
506 for ccobj in ccobjs:
507 # Is ccobj an job object (unparsed), or is it a ccdata object (parsed)?
508 if isinstance(ccobj, logfileparser.Logfile):
509 jobfilename = ccobj.filename
510 ccdata = ccobj.parse()
511 elif isinstance(ccobj, data.ccData):
512 jobfilename = None
513 ccdata = ccobj
514 else:
515 raise ValueError
516
517 attributes = ccdata.getattributes()
518 attributes.update({
519 'jobfilename': jobfilename
520 })
521
522 logfiles.append(pd.Series(attributes))
523 return pd.DataFrame(logfiles)
524
525
526 del find_package