| 1 |
|
| 2 |
p |
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
from __future__ import print_function |
| 13 |
|
| 14 |
import os |
| 15 |
import re |
| 16 |
import subprocess |
| 17 |
import sys |
| 18 |
from contextlib import suppress |
| 19 |
from pathlib import Path |
| 20 |
from shutil import which, copyfile |
| 21 |
|
| 22 |
with suppress(ImportError): |
| 23 |
from shelxfile import Shelxfile |
| 24 |
from shelxfile.misc.misc import remove_file, sep_line, find_line |
| 25 |
from shelxfile.shelx.cards import ACTA |
| 26 |
|
| 27 |
|
| 28 |
def get_xl_version_string(exe: str) -> str: |
| 29 |
""" |
| 30 |
Extracts the version string from a SHELXL executable. |
| 31 |
This is fast and needs no hashes etc. |
| 32 |
:type exe: str |
| 33 |
:param exe: path to SHELXL executable |
| 34 |
""" |
| 35 |
try: |
| 36 |
with open(exe, 'rb') as f: |
| 37 |
binary = f.read() |
| 38 |
position = binary.find(b'Version 201') |
| 39 |
if position > 0: |
| 40 |
f.seek(position + 8, 0) |
| 41 |
version = f.read(6) |
| 42 |
return version.decode('ascii') |
| 43 |
else: |
| 44 |
return '' |
| 45 |
except IOError: |
| 46 |
print("Could not determine SHELXL version. Refinement might fail to run.") |
| 47 |
return '' |
| 48 |
|
| 49 |
|
| 50 |
def find_shelxl_exe(shelxpath=None) -> str: |
| 51 |
""" |
| 52 |
returns the appropriate shelxl executable |
| 53 |
""" |
| 54 |
names = ['shelxl', 'xl'] |
| 55 |
download = 'You can download SHELXL at http://shelx.uni-goettingen.de' |
| 56 |
exe = '' |
| 57 |
if shelxpath: |
| 58 |
return shelxpath |
| 59 |
for name in names: |
| 60 |
exe = which(name) |
| 61 |
if not exe: |
| 62 |
continue |
| 63 |
version = get_xl_version_string(exe) |
| 64 |
if not version and exe: |
| 65 |
|
| 66 |
return exe |
| 67 |
if not version: |
| 68 |
print('Your SHELXL version', exe, 'is too old for this Program') |
| 69 |
print('Please use SHELXL 2017 or above!') |
| 70 |
print(download) |
| 71 |
return exe |
| 72 |
version = version.split('/') |
| 73 |
if int(version[0]) < 2017: |
| 74 |
print('Your SHELXL version is too old. Please use SHELXL 2017 or above!') |
| 75 |
print(download) |
| 76 |
else: |
| 77 |
return exe |
| 78 |
return exe |
| 79 |
|
| 80 |
|
| 81 |
class ShelxlRefine(): |
| 82 |
""" |
| 83 |
A class to do a shelxl refinement. It is only for shelxl 2017 and above! |
| 84 |
The resfilename should be without ending. |
| 85 |
""" |
| 86 |
|
| 87 |
def __init__(self, shx: 'Shelxfile', resfile_path: Path, shelxpath: str = None): |
| 88 |
self.shx = shx |
| 89 |
self.shelxpath = shelxpath |
| 90 |
self.resfile_name = resfile_path.stem |
| 91 |
self._shelx_command = find_shelxl_exe(shelxpath) |
| 92 |
self.backup_file = os.path.abspath(str(self.resfile_name + '.shx-bak')) |
| 93 |
self._acta_card = '' |
| 94 |
|
| 95 |
if not self._shelx_command: |
| 96 |
print('\nSHELXL executable not found in system path.\n') |
| 97 |
print('You can download SHELXL at http://shelx.uni-goettingen.de\n') |
| 98 |
|
| 99 |
def get_b_array(self): |
| 100 |
""" |
| 101 |
Approximates the B array size to ensure refinement. |
| 102 |
""" |
| 103 |
number_of_atoms = self.shx.atoms.number |
| 104 |
|
| 105 |
barray = number_of_atoms * 8 |
| 106 |
if barray <= 3000: |
| 107 |
barray = 3000 |
| 108 |
return barray |
| 109 |
|
| 110 |
def remove_acta_card(self, acta_card): |
| 111 |
""" |
| 112 |
Removes ACTA x from reslist and stores value in self._acta_card. |
| 113 |
""" |
| 114 |
if not acta_card: |
| 115 |
return |
| 116 |
self._acta_card = acta_card._textline.strip('\r\n')[:] |
| 117 |
del self.shx._reslist[self.shx.index_of(acta_card)] |
| 118 |
|
| 119 |
|
| 120 |
self.shx.acta = None |
| 121 |
|
| 122 |
def restore_acta_card(self): |
| 123 |
""" |
| 124 |
Place ACTA after UNIT |
| 125 |
""" |
| 126 |
if not self._acta_card: |
| 127 |
return |
| 128 |
acta = ACTA(self.shx, self._acta_card.split()) |
| 129 |
self.shx._reslist.insert(self.shx.unit.index + 1, ' ') |
| 130 |
self.shx.acta = self.shx._assign_card(acta, self.shx.unit.index + 1) |
| 131 |
|
| 132 |
def backup_shx_file(self): |
| 133 |
""" |
| 134 |
makes a copy of the res file |
| 135 |
make backup in shxsaves before every fragment fit. |
| 136 |
name: self.resfile_name-date-time-seconds.res |
| 137 |
""" |
| 138 |
import datetime |
| 139 |
now = datetime.datetime.now() |
| 140 |
timestamp = (str(now.year) + '_' + str(now.month) + '_' + str(now.day) + '_' + |
| 141 |
str(now.hour) + '-' + str(now.minute) + '-' + str(now.second)) |
| 142 |
resfile = os.path.abspath(str(self.resfile_name + '.res')) |
| 143 |
bakup_dir = os.path.abspath(os.path.dirname(resfile)) + os.path.sep + os.path.relpath('shxsaves') |
| 144 |
try: |
| 145 |
copyfile(resfile, self.backup_file) |
| 146 |
except IOError: |
| 147 |
print('*** Unable to make backup file from {}. ***'.format(resfile)) |
| 148 |
sys.exit() |
| 149 |
if not os.path.exists(bakup_dir): |
| 150 |
try: |
| 151 |
os.makedirs(bakup_dir) |
| 152 |
except(IOError, OSError): |
| 153 |
print('*** Unable to create backup directory {}. ***'.format(bakup_dir)) |
| 154 |
try: |
| 155 |
copyfile(resfile, |
| 156 |
bakup_dir + os.path.sep + os.path.split(self.resfile_name)[1] + '_' + timestamp + '.res') |
| 157 |
except IOError: |
| 158 |
print('\n*** Unable to make backup file from {} in shxsaves. ***'.format(resfile)) |
| 159 |
|
| 160 |
def restore_shx_file(self): |
| 161 |
""" |
| 162 |
restores filename from backup |
| 163 |
""" |
| 164 |
resfile = os.path.abspath(str(self.resfile_name + '.res')) |
| 165 |
try: |
| 166 |
print('*** Restoring previous res file. ***') |
| 167 |
copyfile(self.backup_file, resfile) |
| 168 |
except IOError: |
| 169 |
print('Unable to restore res file from {}.'.format(self.backup_file)) |
| 170 |
try: |
| 171 |
remove_file(self.backup_file) |
| 172 |
except IOError: |
| 173 |
print('Unable to delete backup file {}.'.format(self.backup_file)) |
| 174 |
|
| 175 |
def pretty_shx_output(self, out: str): |
| 176 |
""" |
| 177 |
selectively prints the output from shelx |
| 178 |
""" |
| 179 |
if out.startswith(' + Copyright(C)'): |
| 180 |
print(' SHELXL {}'.format(' '.join(out.split()[6:8])), end='') |
| 181 |
if out.startswith(' R1'): |
| 182 |
line = out[:].split() |
| 183 |
print(' {} {} {:>6}'.format(line[0], line[1], line[2][:6]), end='') |
| 184 |
if re.match(r'.*CANNOT RESOLVE (SAME|RIGU|SIMU|DELU)', out): |
| 185 |
print('\nWarning: Are you sure that all atoms are in the correct order?\n') |
| 186 |
if re.match(r'.*CANNOT\s+OPEN\s+FILE.*hkl.*', out): |
| 187 |
print('*** No hkl file found! ***') |
| 188 |
print('*** You need a proper hkl file to run SHELXL! ***') |
| 189 |
sys.exit() |
| 190 |
if re.match(r'.*\*\* Extinction \(EXTI\) or solvent.*', out): |
| 191 |
return |
| 192 |
if re.match(r'.*\*\* MERG code changed to 0', out): |
| 193 |
return |
| 194 |
if re.match(r'.*\*\* Bond\(s\) to .* ignored', out): |
| 195 |
return |
| 196 |
if re.match(r'.*\*\*.*', out): |
| 197 |
print('\n SHELXL says:') |
| 198 |
print(' {}'.format(out.strip('\n\r')), end='') |
| 199 |
if 'before cycle' in out: |
| 200 |
print(out, end='') |
| 201 |
if 'finished at' in out: |
| 202 |
print(out, end='') |
| 203 |
|
| 204 |
def run_shelxl(self, anis: bool = False, backup_before: bool = True) -> None: |
| 205 |
""" |
| 206 |
This method runs shelxl 2013 on the res file self.resfile_name |
| 207 |
""" |
| 208 |
if not self._shelx_command: |
| 209 |
print('Unable to refine.') |
| 210 |
return |
| 211 |
if anis: |
| 212 |
self.shx.insert_anis() |
| 213 |
status = True |
| 214 |
resfile = self.resfile_name + '.res' |
| 215 |
hklfile = self.resfile_name + '.hkl' |
| 216 |
current_path = Path('.').resolve() |
| 217 |
|
| 218 |
os.chdir(Path(resfile).parent) |
| 219 |
if not os.path.exists(hklfile): |
| 220 |
print('You need a proper hkl file to run SHELXL.') |
| 221 |
sys.exit() |
| 222 |
command_line = ['{}'.format(self._shelx_command), "-b{}".format(self.get_b_array()), |
| 223 |
'{}'.format(self.resfile_name)] |
| 224 |
if backup_before: |
| 225 |
self.backup_shx_file() |
| 226 |
print(sep_line) |
| 227 |
print(' Running SHELXL with "{}" and "{}"'.format(' '.join(command_line), self.shx.cycles)) |
| 228 |
with subprocess.Popen(command_line, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, |
| 229 |
universal_newlines=True) as p: |
| 230 |
for line in p.stdout.readlines(): |
| 231 |
|
| 232 |
self.pretty_shx_output(line) |
| 233 |
lstfile = Path(f'{self.resfile_name}.lst') |
| 234 |
if lstfile.exists() and lstfile.is_file(): |
| 235 |
self.check_refinement_results(lstfile.read_text('latin1').splitlines(keepends=False)) |
| 236 |
|
| 237 |
os.chdir(current_path) |
| 238 |
if p.returncode != 0: |
| 239 |
status = False |
| 240 |
if os.stat(resfile).st_size < 10: |
| 241 |
|
| 242 |
status = False |
| 243 |
if not status: |
| 244 |
print(sep_line) |
| 245 |
print('\nError: SHELXL terminated unexpectedly.') |
| 246 |
print('Check for errors in your SHELX input file!\n') |
| 247 |
self.restore_shx_file() |
| 248 |
sys.exit() |
| 249 |
|
| 250 |
def check_refinement_results(self, list_file): |
| 251 |
""" |
| 252 |
Does some checks if the refinement makes sense e.g. if the data to parameter |
| 253 |
ratio is in an acceptable range. |
| 254 |
""" |
| 255 |
regex_final = r' Final Structure Factor Calculation.*' |
| 256 |
final_results = find_line(list_file, regex_final) |
| 257 |
|
| 258 |
try: |
| 259 |
dataobj = re.search(r'(\d+\s+data)', list_file[final_results + 4]) |
| 260 |
data = float(dataobj.group(0).split()[0]) |
| 261 |
parameterobj = re.search(r'(\d+\s+parameters)', list_file[final_results + 4]) |
| 262 |
parameters = float(parameterobj.group(0).split()[0]) |
| 263 |
restrobj = re.search(r'(\d+\s+restraints)', list_file[find_line(list_file, r" GooF = S =.*")]) |
| 264 |
restraints = float(restrobj.group(0).split()[0]) |
| 265 |
except AttributeError: |
| 266 |
if self.shx.debug: |
| 267 |
raise |
| 268 |
return False |
| 269 |
try: |
| 270 |
data_to_parameter_ratio = data / parameters |
| 271 |
restr_ratio = ((data + restraints) / parameters) |
| 272 |
except ZeroDivisionError: |
| 273 |
if self.shx.debug: |
| 274 |
raise |
| 275 |
return False |
| 276 |
lattline = find_line(list_file, r'^ LATT.*') |
| 277 |
centro = None |
| 278 |
if lattline: |
| 279 |
try: |
| 280 |
latt = int(list_file[lattline].split()[1]) |
| 281 |
except ValueError: |
| 282 |
latt = 1 |
| 283 |
if latt > 0: |
| 284 |
centro = True |
| 285 |
else: |
| 286 |
centro = False |
| 287 |
if centro and data_to_parameter_ratio < 10: |
| 288 |
print('*** Warning! The data/parameter ratio is getting low (ratio = {:.1f})! ***' |
| 289 |
'\n*** but consider (data+restraints)/parameter = {:.1f} ***' |
| 290 |
.format(data_to_parameter_ratio, restr_ratio)) |
| 291 |
if not centro and data_to_parameter_ratio < 7.5: |
| 292 |
print('*** Warning! The data/parameter ratio is getting low (ratio = {:.1f})! ***' |
| 293 |
'\n*** but consider (data+restraints)/parameter = {:.1f} ***' |
| 294 |
.format(data_to_parameter_ratio, restr_ratio)) |
| 295 |
|
| 296 |
|
| 297 |
if __name__ == '__main__': |
| 298 |
pass |