Debian Codegraph @

src/Programs/validate_cif.py

raw symbols SCIP
1 # A program to check CIFs against dictionaries.
2 #
3 # Usage: validate_cif [-d dictionary_dir] -f dictionary file cifname
4 #
5 # We need option parsing:
6 from __future__ import print_function
7 from __future__ import unicode_literals
8 from __future__ import division
9 from __future__ import absolute_import
10
11 # Python 2,3 compatibility
12 try:
13 from urllib2 import urlopen # for arbitrary opening
14 from urllib.parse import url2pathname
15 except:
16 from urllib.request import urlopen,url2pathname
17
18 # Option parsing
19 from optparse import OptionParser
20 # We need our cif library:
21 import CifFile
22 import os
23 import urllib
24 import traceback
25
26 #
27 # return a CifFile object from an FTP location
28 def cif_by_ftp(ftp_ptr,store=True,directory="."):
29 # print "Opening %s" % ftp_ptr
30 if store:
31 new_fn = os.path.split(url2pathname(ftp_ptr))[1]
32 target = os.path.abspath(os.path.join(directory,new_fn))
33 if target != ftp_ptr:
34 response = urlopen(ftp_ptr)
35 contents = response.read()
36 open(target,"wb").write(contents)
37 print("Stored {} as {}".format(ftp_ptr,target))
38 print('Reading ' + target)
39 ret_cif = CifFile.CifFile(target)
40 else:
41 ret_cif = CifFile.ReadCif(ftp_ptr)
42 return ret_cif
43
44 # get a canonical CIF dictionary given name and version
45 # we use the IUCr repository file, perhaps stored locally
46
47 def locate_dic(dicname,dicversion,regloc="cifdic.register",store_dir = "."):
48 register = cif_by_ftp(regloc,directory=store_dir)
49 good_gen = register["validation_dictionaries"]
50 dataloop = good_gen.GetLoop("_cifdic_dictionary.version")
51 matches = [a for a in dataloop if getattr(a,"_cifdic_dictionary.name")==dicname and \
52 getattr(a,"_cifdic_dictionary.version")==dicversion]
53 if len(matches)==0:
54 print( "Unable to find any matches for {} version {}".format(dicname,dicversion))
55 return ""
56 elif len(matches)>1:
57 print( "Warning: found more than one candidate, choosing first.")
58 print( map(str,matches))
59 return getattr(matches[0],"_cifdic_dictionary.URL") # the location
60
61 def parse_options():
62 # define our options
63 op = OptionParser(usage="%prog [options] ciffile", version="%prog 0.7")
64 op.add_option("-d","--dict_dir", dest = "dirname", default = ".",
65 help = "Directory where locally stored dictionaries are located")
66 op.add_option("-f","--dict_file", dest = "dictnames",
67 action="append",
68 help = "A dictionary name stored locally")
69 op.add_option("-u","--dict-version", dest = "versions",
70 action="append",
71 help = "A dictionary version")
72 op.add_option("-n","--name", dest = "iucr_names",action="append",
73 help = "Dictionary name as registered by IUCr")
74 op.add_option("-s","--store", dest = "store_flag",action="store_true",
75 help = "Store this dictionary locally", default=True)
76 op.add_option("-c","--canon-reg", dest = "registry",action="store_const",
77 const = "ftp://ftp.iucr.org/pub/cifdics/cifdic.register",
78 help = "Fetch and use canonical dictionary registry from IUCr")
79 op.add_option("-m","--markup", dest = "use_html",action="store_true",
80 help = "Output result in HTML",default=False)
81 op.add_option("-t","--is_dict", dest = "dict_flag", action="store_true",default=False,
82 help = "CI y")
83 op.add_option("-r","--registry-loc", dest = "registry",
84 default = "file:cifdic.register",
85 help = "Location of global dictionary registry (see also -c option)")
86 op.add_option("-v", "--verbose_validation", action="store_true", default=False,
87 help="Log information in the validation process.")
88 op.add_option("-w", "--verbose_import", action="store_true", default=False,
89 help="Log information in the dictionary importing process.")
90 (options,args) = op.parse_args()
91 # our logic: if we are given a dictionary file using -f, the dictionaries
92 # are all located locally; otherwise, they are all located externally, and
93 # we use the IUCr register to locate them.
94 # create the dictionary file names
95
96 import sys
97 if len(sys.argv) <= 1:
98 print( "No arguments given: use option --help to get a help message\n")
99 exit
100
101 return options,args
102
103
104 def execute_with_options(options,args):
105 print(args)
106 print()
107 print(options)
108
109 verbose_import = options.verbose_import
110 verbose_validation = options.verbose_validation
111
112 if options.dictnames:
113 diclist = list(map(lambda a:os.path.join(options.dirname,a),options.dictnames))
114 print( "Using following local dictionaries to validate:")
115 for dic in diclist: print( "{}".format(dic))
116 #fulldic = CifFile.CifFile_module.merge_dic(diclist,mergemode='overlay')
117 fulldic = CifFile.CifFile_module.merge_dic(diclist, verbose_import=verbose_import, verbose_validation=verbose_validation)
118 else:
119 # print( "Locating dictionaries using registry at %s" % options.registry)
120 dics = zip(options.iucr_names,options.versions)
121 dicurls = map(lambda a:locate_dic(a[0],a[1],regloc=options.registry,store_dir=options.dirname),dics)
122 diccifs = map(lambda a:cif_by_ftp(a,options.store_flag,options.dirname),dicurls)
123 fulldic = CifFile.CifFile_module.merge_dic(diccifs, verbose_import=verbose_import, verbose_validation=verbose_validation)
124 diclist = dicurls # for use in reporting later
125
126 f = CifFile.CifFile(fulldic)
127
128 cif_file_name = args[0]
129 # open the cif file
130 with open(cif_file_name, "r") as f:
131 cif_text = f.read()
132
133 cf = CifFile.CifFile(cif_text,grammar="auto", from_str=True)
134
135 cf_json = cf.to_json()
136 print(cf_json)
137
138 result = cf.get_parsing_result()
139
140 # Some kind of parsing error occurred
141 # Parsing errors are identified with negative codes
142 if result[0] < 0:
143 error_str = CifFile.print_cif_syntax_error(result, cif_file_name)
144 cc = (False, None)
145
146 return cc, error_str
147
148
149 output_header(options.use_html,args[0],diclist)
150
151 cc = CifFile.Validate(cf,dic= fulldic,isdic=options.dict_flag)
152 report_str, dict_summary = CifFile.validate_report(cc,use_html=options.use_html)
153
154 print(report_str)
155 output_footer(options.use_html)
156
157 return cc, report_str
158
159 #
160 # Headers and footers for HTML/ASCII output
161 #
162
163 def output_header(use_html,filename,dictionaries):
164 prog_info = "Validate_cif version 0.7, Copyright ANSTO 2005-2020\n"
165 if use_html:
166 print( "<html><head><title>PyCIFRW validation report</title></head>")
167 print( '<style type="text/css">')
168 print( " body {font-family: verdana, sans-serif;}")
169 print( " body {margin-left: 5%; margin-right: 5%;}")
170 print( " table{background: #f0f0f8;}")
171 print( " h4 {background: #f0f8f0;}")
172 print( "</style><body>")
173 print( "<h1>Validation results for {}</h1>".format(filename))
174 print( "<p>Validation performed by {}</p>".format(prog_info))
175 print( "<p>Dictionaries used:<ul>")
176 for one_dic in dictionaries:
177 print( "<li>{}".format(one_dic))
178 print( "</ul>")
179 else:
180 print( "Validation results for {}\n".format(filename))
181 print( "Validation performed by {}".format(prog_info))
182 print( "File validated against following dictionaries:")
183
184 for one_dic in dictionaries:
185 print( " {}".format(one_dic))
186
187 def output_footer(use_html):
188 if use_html:
189 print( "</body></html>")
190
191 def main ():
192 execute_with_options(*parse_options())
193
194 if __name__ == "__main__":
195 main()