1#!/usr/bin/python
2# Convert <atomset> elements from quantum-simulation.org (QSO) format
3# to Qbox input file
4# use: qso2qbox.py [-last] {file|URL}
5# Default: only the first <atomset> element is processed
6# If using -last, only the last <atomset> element is processed
7
8from qso import *
9import os.path
10import xml.sax
11import sys
12import urllib2
13import datetime
14
15def usage():
16  print "use: ",sys.argv[0]," [-last] {file|URL}"
17  sys.exit()
18
19argc=len(sys.argv)
20if ( argc < 2 or argc > 3 ):
21  usage()
22
23# check if option "-last" is used
24# "-last" option: process all <atomset> and return only the last
25# default: extract first atomset only
26first_only = True
27input_source = sys.argv[1]
28if ( sys.argv[1] == "-last" ):
29  if ( argc != 3 ):
30    usage()
31  first_only = False
32  input_source = sys.argv[2]
33
34s = Sample()
35parser = xml.sax.make_parser()
36handler = QSOAtomSetHandler(s)
37parser.setContentHandler(handler)
38# test if input_source is a local file
39# if not, process as a URL
40if ( os.path.isfile(input_source) ):
41  file = open(input_source)
42  str = file.read(8192)
43  while ( str !="" and not (first_only and handler.done_first) ):
44    parser.feed(str)
45    str = file.read(8192)
46  file.close()
47else:
48  # attempt to open as a URL
49  try:
50    f = urllib2.urlopen(input_source)
51    str = f.read(8192)
52    while ( str !="" and not (first_only and handler.done_first) ):
53      parser.feed(str)
54      str = f.read(8192)
55    f.close()
56  except (ValueError,urllib2.HTTPError) as e:
57    print e
58    sys.exit()
59
60parser.reset()
61
62# write Qbox input file
63datestr=datetime.datetime.utcnow().isoformat()+'Z'
64print "# converted",datestr,"from",input_source
65print "set cell ",s.atoms.cell.a,s.atoms.cell.b,s.atoms.cell.c
66for sp in s.atoms.species_list:
67  print "species",sp.name,sp.href
68for a in s.atoms.atom_list:
69  print "atom",a.name,a.species,a.position[0],a.position[1],a.position[2],a.velocity[0],a.velocity[1],a.velocity[2]
70
71