def save_screen_shot_via_pil(self, file_name="wx_viewer", extensions=["png", "jpg", "tiff", "eps", "pdf"]): import gltbx.viewer_utils from libtbx.utils import Sorry from libtbx.str_utils import show_string pil_image = gltbx.viewer_utils.read_pixels_to_pil_image( x=0, y=0, width=self.w, height=self.h) if (pil_image is None): print \ "Cannot save screen shot to file:" \ " Python Imaging Library (PIL) not available." return 0 print "Screen shot width x height: %d x %d" % (self.w, self.h) save = pil_image.save def try_save(file_name_ext): try: save(file_name_ext) except KeyboardInterrupt: raise except Exception: return False return True for ext in extensions: if (file_name.endswith("."+ext)): print "Writing file: %s" % show_string(os.path.abspath(file_name)) if (not try_save(file_name_ext=file_name)): print "Failure saving screen shot as %s file." % ext.upper() return 1 n_written = 0 for ext in extensions: file_name_ext = file_name + "."+ext if (not try_save(file_name_ext=file_name_ext)): print "Image output format not available: %s" % ext.upper() else: print "Wrote file: %s" % show_string(os.path.abspath(file_name_ext)) n_written += 1 return n_written
def show(self, sites_cart, n_slots_difference_histogram=6, out=None, prefix=""): if (out is None): out = sys.stdout selection_strings = self.group.selection_strings for i_op, pair, mx, rms in zip(count(1), self.group.selection_pairs, self.matrices, self.rms): print >> out, prefix + "NCS operator %d:" % i_op print >> out, prefix + " Reference selection:", \ show_string(selection_strings[0]) print >> out, prefix + " Other selection:", \ show_string(selection_strings[i_op]) print >> out, prefix + " Number of atom pairs:", len(pair[0]) print >> out, mx.r.mathematica_form(label="Rotation", format="%.6g", one_row_per_line=True, prefix=prefix + " ") print >> out, mx.t.mathematica_form(label="Translation", format="%.6g", prefix=prefix + " ") x = sites_cart.select(pair[0]) y = mx * sites_cart.select(pair[1]) d_sq = (x - y).dot() if (n_slots_difference_histogram is not None): print >> out, prefix + " Histogram of differences:" diff_histogram = flex.histogram( data=flex.sqrt(d_sq), n_slots=n_slots_difference_histogram) diff_histogram.show(f=out, prefix=prefix + " ", format_cutoffs="%8.6f") print >> out, \ prefix + " RMS difference with respect to the reference: %8.6f" %(rms)
def run(args): if (len(args) != 2): raise Usage("""\ iotbx.cns.transfer_crystal_symmetry any_symmetry_source_file cns_input_file ********************************************* NOTE: the cns_input_file is changed in place. *********************************************""") # for file_name in args: if (not os.path.exists(file_name)): raise Sorry("No such file: %s" % show_string(file_name)) source, target = args crystal_symmetry = crystal_symmetry_from_any.extract_from(source) if (crystal_symmetry is None): raise Sorry("Unknown file format or unit cell and/or space group" " missing from file: " + show_string(source)) cns_space_group_symbol = cns.space_group_symbols.cns_format( space_group_info=crystal_symmetry.space_group_info()) if (cns_space_group_symbol is None): raise Sorry("Space group not available in CNS: %s" % show_string(str(crystal_symmetry.space_group_info()))) sg = '"%s"' % cns_space_group_symbol a, b, c, alpha, beta, gamma = [ "%.6g" % p for p in crystal_symmetry.unit_cell().parameters() ] parameter_names = ["sg", "a", "b", "c", "alpha", "beta", "gamma"] parameters_found = dict(zip(parameter_names, [0] * len(parameter_names))) parameters_changed = [] lines_out = [] detect_binary = detect_binary_file(monitor_initial=100) try: cns_inp = open(target).read().splitlines() except IOError, e: raise Sorry("Error reading file %s (%s)" % (show_string(target), str(e)))
def run(args): if (len(args) != 2): raise Usage("""\ iotbx.cns.transfer_crystal_symmetry any_symmetry_source_file cns_input_file ********************************************* NOTE: the cns_input_file is changed in place. *********************************************""") # for file_name in args: if (not os.path.exists(file_name)): raise Sorry("No such file: %s" % show_string(file_name)) source, target = args crystal_symmetry = crystal_symmetry_from_any.extract_from(source) if (crystal_symmetry is None): raise Sorry( "Unknown file format or unit cell and/or space group" " missing from file: " + show_string(source)) cns_space_group_symbol = cns.space_group_symbols.cns_format( space_group_info=crystal_symmetry.space_group_info()) if (cns_space_group_symbol is None): raise Sorry("Space group not available in CNS: %s" % show_string(str(crystal_symmetry.space_group_info()))) sg = '"%s"' % cns_space_group_symbol a,b,c,alpha,beta,gamma = ["%.6g" % p for p in crystal_symmetry.unit_cell().parameters()] parameter_names = ["sg", "a", "b", "c", "alpha", "beta", "gamma"] parameters_found = dict(zip(parameter_names, [0]*len(parameter_names))) parameters_changed = [] lines_out = [] detect_binary = detect_binary_file(monitor_initial=100) try: cns_inp = open(target).read().splitlines() except IOError, e: raise Sorry("Error reading file %s (%s)" % (show_string(target), str(e)))
def make_graph_of_graph(pg_object, file_name, out=None): if out is None: out = sys.stdout dot_path = libtbx.path.full_command_path(command="dot") if (dot_path is None): raise Sorry("""\ The program "dot" is not on PATH: For information about "dot" visit: http://www.graphviz.org/""") buffer = StringIO() pg_object.graphviz_pg_graph(out=buffer) command = "%s -Tpng > %s" % (show_string(dot_path), show_string(file_name)) # XXX warning - Fontconfig error messages cause raise_if_errors_or_output() # to crash even if 'dot' ran successfully. rc = easy_run.fully_buffered( command=command, stdin_lines=buffer.getvalue().splitlines())#.raise_if_errors_or_output() if (rc.return_code != 0): raise RuntimeError("Fatal error running %s:\n%s" % (dot_path, "\n".join(rc.stderr_lines))) print("A file named", show_string(file_name), \ "contains a graphical representation ", file=out) print("of the point group relations.", file=out)
def make_graph_of_graph(pg_object, file_name, out=None): if out is None: out = sys.stdout dot_path = libtbx.path.full_command_path(command="dot") if (dot_path is None): raise Sorry("""\ The program "dot" is not on PATH: For information about "dot" visit: http://www.graphviz.org/""") buffer = StringIO() pg_object.graphviz_pg_graph(out=buffer) command = "%s -Tpng > %s" % (show_string(dot_path), show_string(file_name)) # XXX warning - Fontconfig error messages cause raise_if_errors_or_output() # to crash even if 'dot' ran successfully. rc = easy_run.fully_buffered( command=command, stdin_lines=buffer.getvalue().splitlines())#.raise_if_errors_or_output() if (rc.return_code != 0) : raise RuntimeError("Fatal error running %s:\n%s" % (dot_path, "\n".join(rc.stderr_lines))) print >> out, "A file named", show_string(file_name), \ "contains a graphical representation " print >> out, "of the point group relations."
def show(self, sites_cart, n_slots_difference_histogram=6, out=None, prefix=""): if (out is None): out = sys.stdout selection_strings = self.group.selection_strings for i_op,pair,mx,rms in zip( count(1), self.group.selection_pairs, self.matrices, self.rms): print >> out, prefix + "NCS operator %d:" % i_op print >> out, prefix + " Reference selection:", \ show_string(selection_strings[0]) print >> out, prefix + " Other selection:", \ show_string(selection_strings[i_op]) print >> out, prefix + " Number of atom pairs:", len(pair[0]) print >> out, mx.r.mathematica_form( label="Rotation", format="%.6g", one_row_per_line=True, prefix=prefix+" ") print >> out, mx.t.mathematica_form( label="Translation", format="%.6g", prefix=prefix+" ") x = sites_cart.select(pair[0]) y = mx * sites_cart.select(pair[1]) d_sq = (x-y).dot() if (n_slots_difference_histogram is not None): print >> out, prefix + " Histogram of differences:" diff_histogram = flex.histogram( data=flex.sqrt(d_sq), n_slots=n_slots_difference_histogram) diff_histogram.show( f=out, prefix=prefix+" ", format_cutoffs="%8.6f") print >> out, \ prefix + " RMS difference with respect to the reference: %8.6f" %(rms)
def combine_symops_and_symbol(space_group_from_ops, space_group_symbol): space_group_symbol = space_group_symbol.replace(" ", "").upper() z = space_group_symbol[:1] if ("PABCIFRH".find(z) < 0): raise RuntimeError( "Cannot determine lattice centring type given space group symbol" " %s" % show_string(space_group_symbol)) if (z == "P"): return sgtbx.space_group_info(group=space_group_from_ops) if (z == "H"): space_group_symbol = "R" + space_group_symbol[1:] + ":H" z = "R" elif (z == "R" and not space_group_symbol.endswith(":H")): if (space_group_symbol.endswith(":R")): z = None else: for s in space_group_from_ops: r_info = s.r().info() if (abs(r_info.type()) == 3): if (r_info.ev() == (0, 0, 1)): space_group_symbol = "R" + space_group_symbol[1:] + ":H" break elif (r_info.ev() == (1, 1, 1)): space_group_symbol += ":R" z = None break space_group_exp = sgtbx.space_group(space_group_from_ops) if (z is not None): try: space_group_exp.expand_conventional_centring_type(z) except RuntimeError: space_group_exp = None if (space_group_exp is not None): try: space_group_from_symbol = sgtbx.space_group_info( symbol=space_group_symbol).group() except RuntimeError: space_group_from_symbol = None if (space_group_exp is None or space_group_from_symbol is None or space_group_exp != space_group_from_symbol): if space_group_from_symbol: warnings.warn( """ WARNING: Symmetry operations in input file are for space group %(space_group_exp)s However space group symbol is: %(space_group_symbol)s This may be a format error in the Scalepack file! Using %(space_group_symbol)s """ % { "space_group_exp": str(space_group_exp.info()), "space_group_symbol": show_string(space_group_symbol), }, UserWarning, stacklevel=10) space_group_exp = space_group_from_symbol else: raise RuntimeError( "Symmetry operations in unmerged SCALEPACK file incompatible with" " space group symbol %s" % show_string(space_group_symbol)) return sgtbx.space_group_info(group=space_group_exp)
def combine_symops_and_symbol(space_group_from_ops, space_group_symbol): space_group_symbol = space_group_symbol.replace(" ","").upper() z = space_group_symbol[:1] if ("PABCIFRH".find(z) < 0): raise RuntimeError( "Cannot determine lattice centring type given space group symbol" " %s" % show_string(space_group_symbol)) if (z == "P"): return sgtbx.space_group_info(group=space_group_from_ops) if (z == "H"): space_group_symbol = "R" + space_group_symbol[1:] + ":H" z = "R" elif (z == "R" and not space_group_symbol.endswith(":H")): if (space_group_symbol.endswith(":R")): z = None else: for s in space_group_from_ops: r_info = s.r().info() if (abs(r_info.type()) == 3): if (r_info.ev() == (0,0,1)): space_group_symbol = "R" + space_group_symbol[1:] + ":H" break elif (r_info.ev() == (1,1,1)): space_group_symbol += ":R" z = None break space_group_exp = sgtbx.space_group(space_group_from_ops) if (z is not None): try: space_group_exp.expand_conventional_centring_type(z) except RuntimeError: space_group_exp = None if (space_group_exp is not None): try: space_group_from_symbol = sgtbx.space_group_info( symbol=space_group_symbol).group() except RuntimeError: space_group_from_symbol = None if ( space_group_exp is None or space_group_from_symbol is None or space_group_exp != space_group_from_symbol): if space_group_from_symbol: warnings.warn(""" WARNING: Symmetry operations in input file are for space group %(space_group_exp)s However space group symbol is: %(space_group_symbol)s This may be a format error in the Scalepack file! Using %(space_group_symbol)s """ % {"space_group_exp" : str(space_group_exp.info()), "space_group_symbol" : show_string(space_group_symbol), }, UserWarning, stacklevel=10) space_group_exp = space_group_from_symbol else: raise RuntimeError( "Symmetry operations in unmerged SCALEPACK file incompatible with" " space group symbol %s" % show_string(space_group_symbol)) return sgtbx.space_group_info(group=space_group_exp)
def try_as_command_line_params(): try: command_line_params = argument_interpreter.process(arg=arg) except KeyboardInterrupt: raise except Exception: if (op.isfile(arg)): raise Sorry( "Error processing file: %s" % show_string(arg)) raise Sorry( "Command-line argument not recognized: %s" % show_string(arg)) input_objects["phil"].append(command_line_params)
def try_as_command_line_params(): try: command_line_params = argument_interpreter.process(arg=arg) except KeyboardInterrupt: raise except Exception: if (op.isfile(arg)): raise Sorry("Error processing file: %s" % show_string(arg)) raise Sorry("Command-line argument not recognized: %s" % show_string(arg)) input_objects["phil"].append(command_line_params)
def __init__(self, params, coeffs, atom_selection_manager=None, xray_structure=None): adopt_init_args(self, locals()) fft_map = coeffs.fft_map( resolution_factor=self.params.grid_resolution_factor) if (self.params.scale == "volume"): fft_map.apply_volume_scaling() elif (self.params.scale == "sigma"): fft_map.apply_sigma_scaling() else: raise RuntimeError title_lines = [ "REMARK file: %s" % show_string(os.path.basename(self.params.file_name)) ] title_lines.append("REMARK directory: %s" % show_string(os.path.dirname(self.params.file_name))) title_lines.append("REMARK %s" % date_and_time()) assert self.params.region in ["selection", "cell"] if (self.params.region == "selection" and xray_structure is not None): map_iselection = None if atom_selection_manager is not None: map_iselection = self.atom_iselection() frac_min, frac_max = self.box_around_selection( iselection=map_iselection, buffer=self.params.atom_selection_buffer) n_real = fft_map.n_real() gridding_first = [ifloor(f * n) for f, n in zip(frac_min, n_real)] gridding_last = [iceil(f * n) for f, n in zip(frac_max, n_real)] title_lines.append('REMARK map around selection') title_lines.append('REMARK atom_selection=%s' % show_string(self.params.atom_selection)) title_lines.append('REMARK atom_selection_buffer=%.6g' % self.params.atom_selection_buffer) if (map_iselection is None): sel_size = self.xray_structure.scatterers().size() else: sel_size = map_iselection.size() title_lines.append('REMARK number of atoms selected: %d' % sel_size) else: gridding_first = None gridding_last = None title_lines.append("REMARK map covering the unit cell") if params.format == "xplor": fft_map.as_xplor_map(file_name=self.params.file_name, title_lines=title_lines, gridding_first=gridding_first, gridding_last=gridding_last) else: fft_map.as_ccp4_map(file_name=self.params.file_name, gridding_first=gridding_first, gridding_last=gridding_last, labels=title_lines)
def write_only_if_safe(file_name, text): from libtbx.str_utils import show_string if (os.path.exists(file_name)): if (not os.path.isfile(file_name)): raise RuntimeError("Not a regular file: %s" % show_string(file_name)) stat = check_fingerprint(file_name=file_name) if (stat is None or not stat): raise RuntimeError("File appears to be manually modified: %s" % show_string(file_name)) hexdigest = compute_hexdigest(text=text) f = open(file_name, "w") f.write("// fingerprint %s\n" % hexdigest) f.write(text)
def show_summary(self, out=None, prefix=""): if (out is None): out = sys.stdout print >> out, prefix + "File name:", show_string(self.file_name) print >> out, prefix + "Space group symbol:", \ show_string(self.space_group_symbol) try: space_group_info = self.space_group_info() except KeyboardInterrupt: raise except Exception: pass else: space_group_info.show_summary( f=out, prefix=prefix+"Space group from operations: ") if (self.original_indices is not None): print >> out, prefix + "Number of original indices:", \ self.original_indices.size()
def show_summary(self, out=None, prefix=""): if (out is None): out = sys.stdout print(prefix + "File name:", show_string(self.file_name), file=out) print(prefix + "Space group symbol:", \ show_string(self.space_group_symbol), file=out) try: space_group_info = self.space_group_info() except KeyboardInterrupt: raise except Exception: pass else: space_group_info.show_summary( f=out, prefix=prefix+"Space group from operations: ") if (self.original_indices is not None): print(prefix + "Number of original indices:", \ self.original_indices.size(), file=out)
def __init__(self, params, coeffs, atom_selection_manager=None, xray_structure=None): adopt_init_args(self, locals()) fft_map = coeffs.fft_map(resolution_factor = self.params.grid_resolution_factor) if(self.params.scale == "volume"): fft_map.apply_volume_scaling() elif(self.params.scale == "sigma"): fft_map.apply_sigma_scaling() else: raise RuntimeError title_lines=["REMARK file: %s" % show_string(os.path.basename(self.params.file_name))] title_lines.append("REMARK directory: %s" % show_string(os.path.dirname(self.params.file_name))) title_lines.append("REMARK %s" % date_and_time()) assert self.params.region in ["selection", "cell"] if(self.params.region == "selection" and xray_structure is not None) : map_iselection = None if atom_selection_manager is not None : map_iselection = self.atom_iselection() frac_min, frac_max = self.box_around_selection( iselection = map_iselection, buffer = self.params.atom_selection_buffer) n_real = fft_map.n_real() gridding_first=[ifloor(f*n) for f,n in zip(frac_min,n_real)] gridding_last=[iceil(f*n) for f,n in zip(frac_max,n_real)] title_lines.append('REMARK map around selection') title_lines.append('REMARK atom_selection=%s' % show_string(self.params.atom_selection)) title_lines.append('REMARK atom_selection_buffer=%.6g' % self.params.atom_selection_buffer) if(map_iselection is None): sel_size = self.xray_structure.scatterers().size() else: sel_size = map_iselection.size() title_lines.append('REMARK number of atoms selected: %d' % sel_size) else: gridding_first = None gridding_last = None title_lines.append("REMARK map covering the unit cell") if params.format == "xplor" : fft_map.as_xplor_map( file_name = self.params.file_name, title_lines = title_lines, gridding_first = gridding_first, gridding_last = gridding_last) else : fft_map.as_ccp4_map( file_name = self.params.file_name, gridding_first = gridding_first, gridding_last = gridding_last, labels=title_lines)
def __call__(O, index_and_arg): assert len(index_and_arg) == 2 index, arg = index_and_arg sub_name = O.options.sub_name_format % index op = os.path if (op.exists(sub_name)): return ( "sub-directory exists already: %s" % show_string(sub_name), None) try: os.makedirs(sub_name, mode=O.options.makedirs_mode) except: # intentional return ( "cannot create sub-directory: %s" % show_string(sub_name), None) if (not op.isdir(sub_name)): return ( "failure creating sub-directory: %s" % show_string(sub_name), None) initial_cwd = os.getcwd() try: try: os.chdir(sub_name) except: # intentional return ( "cannot chdir to sub-directory: %s" % show_string(sub_name), None) def sub_log(): return show_string(op.join(sub_name, "log")) try: log = open("log", "w") except: # intentional return ("cannot open file: %s" % sub_log(), None) initial_out = sys.stdout initial_err = sys.stderr try: sys.stderr = sys.stdout = log try: result = O.func(arg) except: # intentional show_caught_exception(index, arg) return ("CAUGHT EXCEPTION: %s" % sub_log(), None) finally: sys.stdout = initial_out sys.stderr = initial_err log.close() finally: os.chdir(initial_cwd) return (None, result)
def build_rotamer_tor_atom_ids_by_tor_id(comp_comp_id, rotamer_info): comp_tor_by_id = {} for tor in comp_comp_id.tor_list: assert tor.id not in comp_tor_by_id comp_tor_by_id[tor.id] = tor rotmer_info_tor_ids = set(rotamer_info.tor_ids) rotamer_tor_by_id = {} for tor_atom_ids in rotamer_info.tor_atom_ids: assert len(tor_atom_ids) == 5 tor_id = tor_atom_ids[0] assert tor_id in rotmer_info_tor_ids assert tor_id not in rotamer_tor_by_id rotamer_tor_by_id[tor_id] = tuple(tor_atom_ids[1:]) result = {} for tor_id in rotamer_info.tor_ids: atom_ids = rotamer_tor_by_id.get(tor_id) if (atom_ids is not None): result[tor_id] = atom_ids else: comp_tor = comp_tor_by_id.get(tor_id) if (comp_tor is not None): result[tor_id] = comp_tor.atom_ids() else: raise Sorry("rotamer_info.tor_id %s is unknown." % show_string(tor_id)) return result
def get(self, name, must_exist=True): assert name is not None result = op.join(self.path, name) if (must_exist and not op.exists(result)): from libtbx.str_utils import show_string raise RuntimeError("No such file or directory: %s" % show_string(result)) return result
def write_only_if_safe(file_name, text): from libtbx.str_utils import show_string import os op = os.path if (op.exists(file_name)): if (not op.isfile(file_name)): raise RuntimeError( "Not a regular file: %s" % show_string(file_name)) stat = check_fingerprint(file_name=file_name) if (stat is None or not stat): raise RuntimeError( "File appears to be manually modified: %s" % show_string(file_name)) hexdigest = compute_hexdigest(text=text) f = open(file_name, "w") f.write("// fingerprint %s\n" % hexdigest) f.write(text)
def sub_directory(self, name, must_exist=True): result = directory(self.get(name)) if (must_exist and not op.isdir(result.path)): from libtbx.str_utils import show_string raise RuntimeError("Not a directory: %s" % show_string(result.path)) return result
def run(args): if (len(args) == 0): args = ["--help"] from libtbx.option_parser import option_parser import libtbx.load_env command_line = (option_parser( usage="%s [options] pdb_file" % libtbx.env.dispatcher_name) .option(None, "--buffer_layer", action="store", type="float", default=5) ).process(args=args, nargs=1) import iotbx.pdb pdb_inp = iotbx.pdb.input(file_name=command_line.args[0]) atoms = pdb_inp.atoms() from cctbx import uctbx box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center( sites_cart=atoms.extract_xyz(), buffer_layer=command_line.options.buffer_layer) atoms.set_xyz(new_xyz=box.sites_cart) from libtbx.str_utils import show_string print 'REMARK %s --buffer-layer=%.6g %s' % ( libtbx.env.dispatcher_name, command_line.options.buffer_layer, show_string(command_line.args[0])) from libtbx.utils import date_and_time print 'REMARK %s' % date_and_time() print iotbx.pdb.format_cryst1_record(crystal_symmetry=box.crystal_symmetry()) print pdb_inp.construct_hierarchy().as_pdb_string(append_end=True),
def run(args, command_name=libtbx.env.dispatcher_name): parser = argparse.ArgumentParser( prog=command_name, usage='%s pdb_file "atom_selection" [...]' % command_name) parser.add_argument("file_name", nargs=1, help="File name of the model file") parser.add_argument( "inselections", help="Atom selection strings", nargs='+', ) parser.add_argument("--write-pdb-file", action="store", help="write selected atoms to new PDB file", default=None) parser.add_argument( "--cryst1-replacement-buffer-layer", action="store", type=float, help="replace CRYST1 with pseudo unit cell covering the selected" " atoms plus a surrounding buffer layer", default=None) co = parser.parse_args(args) mon_lib_srv = server.server() ener_lib = server.ener_lib() processed_pdb_file = pdb_interpretation.process(mon_lib_srv=mon_lib_srv, ener_lib=ener_lib, file_name=co.file_name[0], log=sys.stdout) print acp = processed_pdb_file.all_chain_proxies selection_cache = acp.pdb_hierarchy.atom_selection_cache() atoms = acp.pdb_atoms all_bsel = flex.bool(atoms.size(), False) for selection_string in co.inselections: print selection_string isel = acp.iselection(string=selection_string, cache=selection_cache) all_bsel.set_selected(isel, True) if (not co.write_pdb_file): print " %d atom%s selected" % plural_s(isel.size()) for atom in atoms.select(isel): print " %s" % atom.format_atom_record() print if (co.write_pdb_file): print "Writing file:", show_string(co.write_pdb_file) sel_hierarchy = acp.pdb_hierarchy.select(all_bsel) if (co.cryst1_replacement_buffer_layer is None): crystal_symmetry = acp.special_position_settings else: import cctbx.crystal crystal_symmetry = cctbx.crystal.non_crystallographic_symmetry( sites_cart=sel_hierarchy.atoms().extract_xyz(), buffer_layer=co.cryst1_replacement_buffer_layer) write_whole_pdb_file(file_name=co.write_pdb_file, processed_pdb_file=processed_pdb_file, pdb_hierarchy=sel_hierarchy, crystal_symmetry=crystal_symmetry) print
def run(): debug_import = "--debug=import" in sys.argv[1:] def show_traceback(): if (debug_import): import traceback print >> sys.stderr traceback.print_exc() print >> sys.stderr engine_path = find_scons_engine_path() if (engine_path is not None): sys.path.insert(0, engine_path) try: import SCons except ImportError: show_traceback() del sys.path[0] try: import SCons.Script except ImportError: show_traceback() msg = ["SCons is not available.", " A possible solution is to unpack a SCons distribution in", " one of these directories:"] for path in libtbx.env.repository_paths: msg.append(" " + show_string(abs(path))) msg.extend([ " SCons distributions are available at this location:", " http://www.scons.org/", " It may be necessary to rename the unpacked distribution, e.g.:", " mv scons-0.96.1 scons"]) raise Sorry("\n".join(msg)) import SCons.Script.Main if (hasattr(SCons.Script.Main, "fetch_win32_parallel_msg")): SCons.Script.Main.fetch_win32_parallel_msg = dummy_fetch_win32_parallel_msg show_times_at_exit() SCons.Script.main()
def raise_bad_file(what, fn=None): msg = "%s file name (%s expected)" % (what, " or ".join(expected_exts)) if (fn is None): msg += "." else: msg += ": " + show_string(fn) raise RuntimeError(msg)
def rebuild_pickle_files(data_dir, file_prefix, target_db, amino_acids): from libtbx import easy_pickle from libtbx.str_utils import show_string from mmtbx.rotamer.n_dim_table import NDimTable os.chdir(data_dir) print("Processing data files in %s:" % show_string(data_dir)) for aa, aafile in amino_acids.items(): data_file = file_prefix+aafile+".data" pickle_file = file_prefix+aafile+".pickle" pair_info = target_db.pair_info( source_path=data_file, target_path=pickle_file, path_prefix=data_dir) print(" %s -> %s:" % (data_file, pickle_file), end=' ') if not pair_info.needs_update: print("already up to date.") else: print("converting ...", end=' ') sys.stdout.flush() pair_info.start_building_target() ndt = NDimTable.createFromText(data_file) easy_pickle.dump(file_name=pickle_file, obj=ndt) pair_info.done_building_target() print("done.") sys.stdout.flush() target_db.write()
def run(args): log = sys.stdout if (len(args) == 0): args = ["--help"] command_line = (option_parser(usage="%s [options] pdb_file" % libtbx.env.dispatcher_name).option( None, "--buffer_layer", action="store", type="float", default=5)).process(args=args, nargs=1) pdb_inp = iotbx.pdb.input(file_name=command_line.args[0]) model = mmtbx.model.manager(model_input=pdb_inp) box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center( sites_cart=model.get_sites_cart(), buffer_layer=command_line.options.buffer_layer) model.set_sites_cart(box.sites_cart) # Bad hack, never repeat. In fact, all the boxing functionality should # go into mmtbx.model.manager model._crystal_symmetry = box.crystal_symmetry() print('REMARK %s --buffer-layer=%.6g %s' % (libtbx.env.dispatcher_name, command_line.options.buffer_layer, show_string(command_line.args[0])), file=log) print('REMARK %s' % date_and_time(), file=log) print(model.model_as_pdb(), file=log)
def extract_from_scatterers_in_place(self, scatterers, tolerance=1.e-4): fps = flex.double() fdps = flex.double() fps.reserve(self.iselection.size()) fdps.reserve(fps.size()) for i_seq in self.iselection: fps.append(scatterers[i_seq].fp) fdps.append(scatterers[i_seq].fdp) for values, label in [(fps, "f_prime"), (fdps, "f_double_prime")]: stats = flex.min_max_mean_double(values) if (stats.max - stats.min <= tolerance): setattr(self, label, stats.mean) else: msg = [ "Anomalous scatterer group with significantly different %s:" % label ] if (self.selection_string is not None): msg.append(" Selection: %s" % show_string(self.selection_string)) msg.append(" Number of selected scatterers: %d" % stats.n) s = StringIO() stats.show(out=s, prefix=" %s " % label, show_n=False) msg.extend(s.getvalue().splitlines()) msg.append(" tolerance: %.6g" % tolerance) raise RuntimeError("\n".join(msg))
def build_rotamer_tor_atom_ids_by_tor_id(comp_comp_id, rotamer_info): comp_tor_by_id = {} for tor in comp_comp_id.tor_list: assert tor.id not in comp_tor_by_id comp_tor_by_id[tor.id] = tor rotmer_info_tor_ids = set(rotamer_info.tor_ids) rotamer_tor_by_id = {} for tor_atom_ids in rotamer_info.tor_atom_ids: assert len(tor_atom_ids) == 5 tor_id = tor_atom_ids[0] assert tor_id in rotmer_info_tor_ids assert tor_id not in rotamer_tor_by_id rotamer_tor_by_id[tor_id] = tuple(tor_atom_ids[1:]) result = {} for tor_id in rotamer_info.tor_ids: atom_ids = rotamer_tor_by_id.get(tor_id) if (atom_ids is not None): result[tor_id] = atom_ids else: comp_tor = comp_tor_by_id.get(tor_id) if (comp_tor is not None): result[tor_id] = comp_tor.atom_ids() else: raise RuntimeError( "rotamer_info.tor_id %s is unknown." % show_string(tor_id)) return result
def run(args): log = sys.stdout if (len(args) == 0): args = ["--help"] command_line = (option_parser(usage="%s [options] pdb_file" % libtbx.env.dispatcher_name).option( None, "--buffer_layer", action="store", type="float", default=5)).process(args=args, nargs=1) pdb_inp = iotbx.pdb.input(file_name=command_line.args[0]) atoms = pdb_inp.atoms() box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center( sites_cart=atoms.extract_xyz(), buffer_layer=command_line.options.buffer_layer) atoms.set_xyz(new_xyz=box.sites_cart) print >> log, 'REMARK %s --buffer-layer=%.6g %s' % ( libtbx.env.dispatcher_name, command_line.options.buffer_layer, show_string(command_line.args[0])) print >> log, 'REMARK %s' % date_and_time() iotbx.pdb.write_whole_pdb_file( output_file=log, pdb_hierarchy=pdb_inp.construct_hierarchy(), crystal_symmetry=box.crystal_symmetry(), ss_annotation=pdb_inp.extract_secondary_structure(log=null_out()))
def run(args, command_name="iotbx.r_free_flags_accumulation"): def raise_usage(): raise Usage("%s reflection_file [label=value]" % command_name) if (len(args) == 0 or "--help" in args or "-h" in args): raise_usage() phil_objects = [] argument_interpreter = master_params.command_line_argument_interpreter( home_scope="r_free_flags_accumulation") reflection_files = [] for arg in args: if (os.path.isfile(arg)): refl_file = reflection_file_reader.any_reflection_file( file_name=arg) if (refl_file.file_type() is not None): reflection_files.append(refl_file) arg = None if (arg is not None): try: command_line_params = argument_interpreter.process(arg=arg) except KeyboardInterrupt: raise except Exception: raise Sorry("Unknown file or keyword: %s" % arg) else: phil_objects.append(command_line_params) params_scope = master_params.fetch(sources=phil_objects).extract() params = params_scope.r_free_flags_accumulation srv = reflection_file_utils.reflection_file_server( reflection_files=reflection_files) r_free_flags, test_flag_value = srv.get_r_free_flags( file_name=params.file_name, label=params.label, test_flag_value=params.test_flag_value, disable_suitability_test=params.disable_suitability_test, parameter_scope="r_free_flags_accumulation") params.file_name = r_free_flags.info().source params.label = r_free_flags.info().label_string() params.test_flag_value = test_flag_value if (params.output is None): params.output = os.path.basename(params.file_name) \ + ".r_free_flags_accumulation" working_params = master_params.format(python_object=params_scope) working_params.show() print print "#phil __OFF__" r_free_flags = r_free_flags.array( data=r_free_flags.data()==params.test_flag_value) r_free_flags.show_r_free_flags_info() print accu = r_free_flags \ .sort(by_value="resolution") \ .r_free_flags_accumulation() print "Writing file: %s" % show_string(params.output) print " 1. column: reflection counts, sorted by resolution" print " 2. column: number of free reflections / total number of reflections" sys.stdout.flush() out = open(params.output, "w") for line in params.plot_header: print >> out, line for c,f in zip(accu.reflection_counts, accu.free_fractions): print >> out, c, f out.close() print sys.stdout.flush()
def __init__(O, args): import libtbx.load_env command_line = (libtbx_option_parser( usage="%s [options] pdb_file" % libtbx.env.dispatcher_name ).option( None, "--model_id", action="store", type="str", default=None, help="only show model with given id", metavar="STR" ).option( None, "--labels_threshold", action="store", type="int", default=20, help="do not show atom labels if more than given number of atoms", metavar="INT").option(None, "--serial_labels", action="store_true", default=False)).process(args=args, nargs=1) O.co = command_line.options file_name = command_line.args[0] import iotbx.pdb O.pdb_inp = iotbx.pdb.input(file_name=file_name) O.pdb_hierarchy = O.pdb_inp.construct_hierarchy() O.pdb_atoms = O.pdb_hierarchy.atoms() print(file_name) print(" number of models:", O.pdb_hierarchy.models_size()) print(" number of atoms:", O.pdb_atoms.size()) if (O.co.model_id is not None): mid = O.co.model_id.strip() from libtbx.str_utils import show_string print("Selecting model with id %s" % show_string(mid)) for mdl in O.pdb_hierarchy.models(): if (mdl.id.strip() == mid): O.pdb_hierarchy = iotbx.pdb.hierarchy.root() O.pdb_hierarchy.append_model(mdl) O.pdb_atoms = O.pdb_hierarchy.atoms() print(" number of atoms:", O.pdb_atoms.size()) break else: raise RuntimeError("--model-id=%s is not in the pdb file." % show_string(mid)) super(App, O).__init__(title=libtbx.env.dispatcher_name)
def __init__(self, model, ncs_params, ext_groups=None): # create bunch of group objects self.ncs_params = ncs_params self.n_excessive_site_distances = None self.ncs_restraints_group_list = class_ncs_restraints_group_list() if self.ncs_params is None: self.ncs_params = global_ncs_params.extract().ncs if ext_groups is not None: self.groups_list = ext_groups else: self.groups_list = [] ncs_obj = model.get_ncs_obj() if ncs_obj is None: return self.ncs_restraints_group_list = ncs_obj.get_ncs_restraints_group_list( ) ncs_groups_selection_string_list = self.ncs_restraints_group_list.get_array_of_str_selections( ) for i_gr, gr in enumerate(self.ncs_restraints_group_list): n_copies = gr.get_number_of_copies() registry = pair_registry(n_seq=model.get_number_of_atoms(), n_ncs=n_copies + 1) for i_copy, c in enumerate(gr.copies): for i_seq, j_seq in zip(gr.master_iselection, c.iselection): stat, i_diag = registry.enter(i_seq=i_seq, j_seq=j_seq, j_ncs=i_copy + 1) for i_pair, pair in enumerate(registry.selection_pairs()): if (pair[0].size() < 2): detail = [ "do not produce any pairs", "produce only one pair" ][pair[0].size()] raise Sorry("\n".join([ "NCS restraints selections %s of matching atoms:" % detail, " Reference selection: %s" % show_string(self.selection_strings[0]), " Other selection: %s" % show_string(self.selection_strings[i_pair + 1]) ])) g = _group( selection_strings=ncs_groups_selection_string_list[i_gr], registry=registry, u_average_min=1.e-6, ) self.groups_list.append(g)
def run(args, command_name=libtbx.env.dispatcher_name): if (len(args) == 0): raise Usage("%s cif [...]" % command_name) for file_name in args: obj_count = cif_triage.check_comp(file_name=file_name) if (obj_count == 0): raise Sorry("No data found in file: %s" % show_string(file_name)) print "OK"
def raise_bad_file(what, fn=None): msg = "%s file name (%s expected)" % ( what, " or ".join(expected_exts)) if (fn is None): msg += "." else: msg += ": " + show_string(fn) raise RuntimeError(msg)
def save_screen_shot_via_pil( self, file_name="wx_viewer", extensions=["png", "jpg", "tiff", "eps", "pdf"]): import gltbx.viewer_utils from libtbx.utils import Sorry from libtbx.str_utils import show_string pil_image = gltbx.viewer_utils.read_pixels_to_pil_image(x=0, y=0, width=self.w, height=self.h) if (pil_image is None): print \ "Cannot save screen shot to file:" \ " Python Imaging Library (PIL) not available." return 0 print "Screen shot width x height: %d x %d" % (self.w, self.h) save = pil_image.save def try_save(file_name_ext): try: save(file_name_ext) except KeyboardInterrupt: raise except Exception: return False return True for ext in extensions: if (file_name.endswith("." + ext)): print "Writing file: %s" % show_string( os.path.abspath(file_name)) if (not try_save(file_name_ext=file_name)): print "Failure saving screen shot as %s file." % ext.upper( ) return 1 n_written = 0 for ext in extensions: file_name_ext = file_name + "." + ext if (not try_save(file_name_ext=file_name_ext)): print "Image output format not available: %s" % ext.upper() else: print "Wrote file: %s" % show_string( os.path.abspath(file_name_ext)) n_written += 1 return n_written
def tidy_show_column_data_format_keyword(input): if (input is None): return show_column_data_format_keywords[0] input = input.lower() for k in show_column_data_format_keywords: if (input.startswith(k[0])): return k raise Sorry( "Column data format keyword not recognized: %s\n" % show_string(input) + " Valid keywords are: %s" % ", ".join(show_column_data_format_keywords))
def save_screen_shot_via_gl2ps(self, file_name): from libtbx.str_utils import show_string gl2ps = gltbx.util.gl2ps_interface if (not gl2ps(file_name=None, draw_background=False, callback=None)): print "PDF output via gl2ps not available: cannot write file %s" \ % file_name return 0 try: # preempt potential error in C++, for better reporting here open(file_name, "wb") except KeyboardInterrupt: raise except Exception: print "Error opening file for writing: %s" % \ show_string(os.path.abspath(file_name)) return 0 gl2ps(file_name=file_name, draw_background=False, callback=self.OnRedraw) print "Wrote file: %s" % show_string(os.path.abspath(file_name)) return 1
def _open(file_name, mode): import os file_name = os.path.expanduser(file_name) from libtbx.str_utils import show_string from libtbx import smart_open try: return smart_open.file(file_name=file_name, mode=mode) except IOError, e: raise IOError("Cannot open pickle file %s (%s)" % ( show_string(file_name), str(e)))
def process_cif(self, file_name): try: cif_object = read_cif(file_name=file_name) except KeyboardInterrupt: raise except Exception: raise Sorry( "Error reading CIF file:\n" " %s\n" " (%s)" % (show_string(file_name), format_exception())) self.process_cif_object(cif_object=cif_object, file_name=file_name)
def run(args): exe = libtbx.env.under_build("suitename/exe/suitename") if (os.name == "nt"): exe += ".exe" if (not os.path.isfile(exe)): from libtbx.str_utils import show_string from libtbx.utils import Sorry raise Sorry("Missing phenix.suitename executable: %s" % show_string(exe)) subprocess.call([exe] + args)
def write_geo(label, geo, geo_file_name): from libtbx.utils import date_and_time header = "# %sgeometry restraints for file:\n" % label header += "# %s\n# %s\n" % (show_string(pdb_file_name), date_and_time()) geo.write_geo_file(sites_cart=sites_cart, site_labels=site_labels, file_name=geo_file_name, header=header)
def gzip_open(file_name, mode): assert mode in ["r", "rb", "w", "wb", "a", "ab"] if (gzip is None): un = "" if (mode[0] == "r"): un = "un" raise RuntimeError( "gzip module not available: cannot %scompress file %s" % (un, show_string(file_name))) return gzip.open(file_name, mode)
def __init__(O, args): import libtbx.load_env command_line = (libtbx_option_parser( usage="%s [options] pdb_file" % libtbx.env.dispatcher_name) .option(None, "--model_id", action="store", type="str", default=None, help="only show model with given id", metavar="STR") .option(None, "--labels_threshold", action="store", type="int", default=20, help="do not show atom labels if more than given number of atoms", metavar="INT") .option(None, "--serial_labels", action="store_true", default=False) ).process(args=args, nargs=1) O.co = command_line.options file_name = command_line.args[0] import iotbx.pdb O.pdb_inp = iotbx.pdb.input(file_name=file_name) O.pdb_hierarchy = O.pdb_inp.construct_hierarchy() O.pdb_atoms = O.pdb_hierarchy.atoms() print file_name print " number of models:", O.pdb_hierarchy.models_size() print " number of atoms:", O.pdb_atoms.size() if (O.co.model_id is not None): mid = O.co.model_id.strip() from libtbx.str_utils import show_string print "Selecting model with id %s" % show_string(mid) for mdl in O.pdb_hierarchy.models(): if (mdl.id.strip() == mid): O.pdb_hierarchy = iotbx.pdb.hierarchy.root() O.pdb_hierarchy.append_model(mdl) O.pdb_atoms = O.pdb_hierarchy.atoms() print " number of atoms:", O.pdb_atoms.size() break else: raise RuntimeError( "--model-id=%s is not in the pdb file." % show_string(mid)) super(App, O).__init__(title=libtbx.env.dispatcher_name)
def __init__(O, bdf_file): """Converts a block of this form: STARTCHAR char0 ENCODING 0 SWIDTH 568 0 DWIDTH 8 0 BBX 8 13 0 -2 BITMAP 00 ... 00 ENDCHAR """ O.label = None O.encoding = None O.swidth = None O.dwidth = None O.bbx = None O.bitmap = None line = bdf_file.next().strip() if (line == "ENDFONT"): return assert line.startswith("STARTCHAR ") O.label = line.split(None, 1)[1] while True: line = bdf_file.next().strip() if (line.startswith("ENCODING ")): fields = line.split() assert len(fields) == 2 O.encoding = int(fields[1]) elif (line.startswith("SWIDTH ")): fields = line.split() assert len(fields) == 3 O.swidth = (int(fields[1]), int(fields[2])) elif (line.startswith("DWIDTH ")): fields = line.split() assert len(fields) == 3 O.dwidth = (int(fields[1]), int(fields[2])) elif (line.startswith("BBX ")): fields = line.split() assert len(fields) == 5 O.bbx = [int(field) for field in fields[1:]] elif (line == "BITMAP"): break else: raise RuntimeError( "Font file %s: unknown line in STARTCHAR block: %s" % ( show_string(bdf_file.name), line)) assert O.encoding is not None O.bitmap = [] while True: line = bdf_file.next().strip() if (line == "ENDCHAR"): break O.bitmap.append(line) assert len(O.bitmap) == O.bbx[1]
def run(self): # I'm guessing self.data_manager, self.params and self.logger # are already defined here... # this must be mmtbx.model.manager? model = self.data_manager.get_model() atoms = model.get_atoms() all_bsel = flex.bool(atoms.size(), False) for selection_string in self.params.atom_selection_program.inselection: print("Selecting '%s'" % selection_string, file=self.logger) isel = model.iselection(string=selection_string) all_bsel.set_selected(isel, True) if self.params.atom_selection_program.write_pdb_file is None: print(" %d atom%s selected" % plural_s(isel.size()), file=self.logger) for atom in atoms.select(isel): print(" %s" % atom.format_atom_record(), file=self.logger) print("", file=self.logger) if self.params.atom_selection_program.write_pdb_file is not None: print("Writing file:", show_string( self.params.atom_selection_program.write_pdb_file), file=self.logger) ss_ann = model.get_ss_annotation() if not model.crystal_symmetry() or \ (not model.crystal_symmetry().unit_cell()): model = shift_and_box_model(model, shift_model=False) selected_model = model.select(all_bsel) if (ss_ann is not None): selected_model.set_ss_annotation(ss_ann.\ filter_annotation( hierarchy=selected_model.get_hierarchy(), asc=selected_model.get_atom_selection_cache(), remove_short_annotations=False, remove_3_10_helices=False, remove_empty_annotations=True, concatenate_consecutive_helices=False, split_helices_with_prolines=False, filter_sheets_with_long_hbonds=False)) if self.params.atom_selection_program.cryst1_replacement_buffer_layer is not None: box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center( sites_cart=selected_model.get_atoms().extract_xyz(), buffer_layer=self.params.atom_selection_program. cryst1_replacement_buffer_layer) sp = crystal.special_position_settings(box.crystal_symmetry()) sites_frac = box.sites_frac() xrs_box = selected_model.get_xray_structure( ).replace_sites_frac(box.sites_frac()) xray_structure_box = xray.structure(sp, xrs_box.scatterers()) selected_model.set_xray_structure(xray_structure_box) pdb_str = selected_model.model_as_pdb() f = open(self.params.atom_selection_program.write_pdb_file, 'w') f.write(pdb_str) f.close() print("", file=self.logger)
def __init__(O, bdf_file): """Converts a block of this form: STARTCHAR char0 ENCODING 0 SWIDTH 568 0 DWIDTH 8 0 BBX 8 13 0 -2 BITMAP 00 ... 00 ENDCHAR """ O.label = None O.encoding = None O.swidth = None O.dwidth = None O.bbx = None O.bitmap = None line = bdf_file.next().strip() if (line == "ENDFONT"): return assert line.startswith("STARTCHAR ") O.label = line.split(None, 1)[1] while True: line = bdf_file.next().strip() if (line.startswith("ENCODING ")): fields = line.split() assert len(fields) == 2 O.encoding = int(fields[1]) elif (line.startswith("SWIDTH ")): fields = line.split() assert len(fields) == 3 O.swidth = (int(fields[1]), int(fields[2])) elif (line.startswith("DWIDTH ")): fields = line.split() assert len(fields) == 3 O.dwidth = (int(fields[1]), int(fields[2])) elif (line.startswith("BBX ")): fields = line.split() assert len(fields) == 5 O.bbx = [int(field) for field in fields[1:]] elif (line == "BITMAP"): break else: raise RuntimeError( "Font file %s: unknown line in STARTCHAR block: %s" % (show_string(bdf_file.name), line)) assert O.encoding is not None O.bitmap = [] while True: line = bdf_file.next().strip() if (line == "ENDCHAR"): break O.bitmap.append(line) assert len(O.bitmap) == O.bbx[1]
def write_geo(label, geo, geo_file_name): from libtbx.utils import date_and_time header = "# %sgeometry restraints for file:\n" % label header += "# %s\n# %s\n" % (show_string(pdb_file_name), date_and_time()) geo.write_geo_file( sites_cart=sites_cart, site_labels=site_labels, file_name=geo_file_name, header=header)
def run(args): import iotbx.phil pcl = iotbx.phil.process_command_line(args=args, master_string="""\ symmetry_search { structure_factor_d_min = 2 .type = float } """) if (len(pcl.remaining_args) != 1): from libtbx.utils import Usage import libtbx.load_env print pcl.master.show() print raise Usage( "%s pdb_file|poscar_file [parameters]" % libtbx.env.dispatcher_name) inp_file = pcl.remaining_args[0] from libtbx.str_utils import show_string import iotbx.pdb if (iotbx.pdb.is_pdb_file(inp_file)): print "PDB file:", show_string(inp_file) pdb_inp = iotbx.pdb.input(file_name=inp_file) xs = pdb_inp.xray_structure_simple() else: print "POSCAR file:", show_string(inp_file) import iotbx.poscar poscar = iotbx.poscar.reader(lines=open(inp_file).read().splitlines()) poscar.make_up_types_if_necessary() xs = poscar.xray_structure() print pcl.work.show() print params = pcl.work.extract().symmetry_search print "Unit cell:", xs.unit_cell() print fc_p1 = xs.structure_factors( d_min=params.structure_factor_d_min).f_calc().expand_to_p1() from cctbx import symmetry_search sf_symm = symmetry_search.structure_factor_symmetry(f_in_p1=fc_p1) print sf_symm print print sf_symm.space_group_info print
def _open(file_name, mode): import os file_name = os.path.expanduser(file_name) from libtbx.str_utils import show_string from libtbx import smart_open try: return smart_open.file(file_name=file_name, mode=mode) except IOError, e: raise IOError("Cannot open pickle file %s (%s)" % (show_string(file_name), str(e)))
def run(args, command_name=libtbx.env.dispatcher_name): parser = argparse.ArgumentParser( prog=command_name, usage='%s pdb_file "atom_selection" [...]' % command_name) parser.add_argument("file_name", nargs=1, help="File name of the model file") parser.add_argument( "inselections", help="Atom selection strings", nargs='+', ) parser.add_argument("--write-pdb-file", action="store", help="write selected atoms to new PDB file", default=None) parser.add_argument( "--cryst1-replacement-buffer-layer", action="store", type=float, help="replace CRYST1 with pseudo unit cell covering the selected" " atoms plus a surrounding buffer layer", default=None) co = parser.parse_args(args) pdb_inp = iotbx.pdb.input(file_name=co.file_name[0]) model = mmtbx.model.manager(model_input=pdb_inp, process_input=True) atoms = model.get_atoms() all_bsel = flex.bool(atoms.size(), False) for selection_string in co.inselections: print selection_string isel = model.iselection(selstr=selection_string) all_bsel.set_selected(isel, True) if (not co.write_pdb_file): print " %d atom%s selected" % plural_s(isel.size()) for atom in atoms.select(isel): print " %s" % atom.format_atom_record() print if (co.write_pdb_file): print "Writing file:", show_string(co.write_pdb_file) selected_model = model.select(all_bsel) if (co.cryst1_replacement_buffer_layer is not None): box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center( sites_cart=selected_model.get_atoms().extract_xyz(), buffer_layer=co.cryst1_replacement_buffer_layer) sp = crystal.special_position_settings(box.crystal_symmetry()) sites_frac = box.sites_frac() xrs_box = selected_model.get_xray_structure().replace_sites_frac( box.sites_frac()) xray_structure_box = xray.structure(sp, xrs_box.scatterers()) selected_model.set_xray_structure(xray_structure_box) pdb_str = selected_model.model_as_pdb() f = open(co.write_pdb_file, 'w') f.write(pdb_str) f.close() print
def show_and_raise(detected): if (show_command_if_error): print show_command_if_error print print "\n".join(lines) msg = detected + " detected in output" if (file_name is None): msg += "." else: msg += ": " + show_string(file_name) raise RunCommandError(msg)
def show_selection(i_ncs, pair): print >> out, prefix + "NCS selection:", \ show_string(self.group.selection_strings[i_ncs]) print >> out, prefix + " "*(max_label_size+2) \ + " B-iso NCS ave Difference" u_isos_current = self.u_isos.select(pair[1]) u_isos_average = self.u_isos_average.select(pair[0]) for i,c,a in zip(pair[1], u_isos_current, u_isos_average): c = adptbx.u_as_b(c) a = adptbx.u_as_b(a) print >> out, prefix + fmt % (site_labels[i], c, a, c-a)
def run(args, this_command="libtbx.find_under_build"): optional = False if ("--optional" in args): optional = True args.remove("--optional") if (len(args) != 1): raise Sorry("usage: %s [--optional] name" % this_command) name = args[0] result = libtbx.env.under_build(name) if (result is None and not optional): raise Sorry("%s: cannot locate %s" % (this_command, show_string(name))) print result