def run(args): command_line = (option_parser( usage="iotbx.lattice_symmetry [options] [centring_type_symbol]", description="Example: iotbx.lattice_symmetry" + " --unit_cell=12,12,12.1,89,90,92 F").enable_symmetry_comprehensive( ).option(None, "--delta", action="store", type="float", default=3., help="angular tolerance in degrees")).process(args=args, max_nargs=1) # Pick up symmetry object input_symmetry = command_line.symmetry # Check that we have what we need if (input_symmetry.unit_cell() is None): print() print("***********************************") print("Please specify unit cell parameters") print("***********************************") print() command_line.parser.show_help() return if (len(command_line.args) > 0): input_symmetry = crystal.symmetry(unit_cell=input_symmetry.unit_cell(), space_group_symbol="Hall: %s 1" % command_line.args[0]) elif (input_symmetry.space_group_info() is None): input_symmetry = crystal.symmetry(unit_cell=input_symmetry.unit_cell(), space_group_symbol="P 1") # Do it groups = metric_subgroups(input_symmetry, command_line.options.delta, enforce_max_delta_for_generated_two_folds=True) groups.show()
def run(args, out=sys.stdout): assert len(args) > 0 command_line = (option_parser() .option(None, "--file_ext", action="store", default="cif") .option(None, "--build_xray_structure", action="store_true") .option(None, "--build_miller_arrays", action="store_true")).process(args=args[1:]) filepath = args[0] if not os.path.isabs(filepath): abs_path = libtbx.env.find_in_repositories(relative_path=filepath) if abs_path is not None: filepath = abs_path file_ext = command_line.options.file_ext build_miller_arrays = command_line.options.build_miller_arrays == True build_xray_structure = command_line.options.build_xray_structure == True if os.path.isdir(filepath): crawl(filepath, file_ext=file_ext, build_miller_arrays=build_miller_arrays, build_xray_structure=build_xray_structure) elif os.path.isfile(filepath): run_once(filepath, build_miller_arrays=build_miller_arrays, build_xray_structure=build_xray_structure) else: try: file_object = urllib2.urlopen(filepath) except urllib2.URLError, e: pass else:
def run(args): command_line = (option_parser( usage="iotbx.lattice_symmetry [options] [centring_type_symbol]", description="Example: iotbx.lattice_symmetry" +" --unit_cell=12,12,12.1,89,90,92 F") .enable_symmetry_comprehensive() .option(None, "--delta", action="store", type="float", default=3., help="angular tolerance in degrees") ).process(args=args, max_nargs=1) # Pick up symmetry object input_symmetry = command_line.symmetry # Check that we have what we need if (input_symmetry.unit_cell() is None): print print "***********************************" print "Please specify unit cell parameters" print "***********************************" print command_line.parser.show_help() return if (len(command_line.args) > 0): input_symmetry = crystal.symmetry( unit_cell=input_symmetry.unit_cell(), space_group_symbol="Hall: %s 1" % command_line.args[0]) elif (input_symmetry.space_group_info() is None): input_symmetry = crystal.symmetry( unit_cell=input_symmetry.unit_cell(), space_group_symbol="P 1") # Do it groups = metric_subgroups(input_symmetry, command_line.options.delta, enforce_max_delta_for_generated_two_folds=True) groups.show()
def run(args, out=sys.stdout): assert len(args) > 0 command_line = (option_parser() .option(None, "--file_ext", action="store", default="cif") .option(None, "--build_xray_structure", action="store_true") .option(None, "--build_miller_arrays", action="store_true")).process(args=args[1:]) filepath = args[0] if not os.path.isabs(filepath): abs_path = libtbx.env.find_in_repositories(relative_path=filepath) if abs_path is not None: filepath = abs_path file_ext = command_line.options.file_ext build_miller_arrays = command_line.options.build_miller_arrays == True build_xray_structure = command_line.options.build_xray_structure == True if os.path.isdir(filepath): crawl(filepath, file_ext=file_ext, build_miller_arrays=build_miller_arrays, build_xray_structure=build_xray_structure) elif os.path.isfile(filepath): run_once(filepath, build_miller_arrays=build_miller_arrays, build_xray_structure=build_xray_structure) else: try: file_object = urllib.request.urlopen(filepath) except urllib.error.URLError as e: pass else: cm = reader(file_object=file_object).model()
def run(args, out=sys.stdout): if len(args) == 0: args = ["--help"] command_line = (option_parser( usage="iotbx.cif.validate filepath|directory [options]").option( None, "--file_ext", action="store", default="cif").option( None, "--dic", action="append", dest="dictionaries").option( None, "--show_warnings", action="store_true").option( None, "--show_timings", action="store_true").option( None, "--strict", action="store", type="bool", default="true")).process(args=args) if len(command_line.args) != 1: command_line.parser.show_help() return total_timer = time_log("total").start() filepath = command_line.args[0] if not os.path.isabs(filepath): abs_path = libtbx.env.find_in_repositories(relative_path=filepath) if abs_path is None: abs_path = libtbx.env.find_in_repositories(relative_path=filepath, test=os.path.isfile) if abs_path is not None: filepath = abs_path cif_dics = command_line.options.dictionaries if cif_dics is None: cif_dics = ["cif_core.dic"] cif_dic = validation.smart_load_dictionary(name=cif_dics[0]) if len(cif_dics) > 1: [ cif_dic.update(validation.smart_load_dictionary(name=d)) for d in cif_dics[1:] ] show_warnings = command_line.options.show_warnings == True show_timings = command_line.options.show_timings == True strict = command_line.options.strict if os.path.isdir(filepath): file_ext = command_line.options.file_ext crawl(filepath, file_ext=file_ext, cif_dic=cif_dic, show_warnings=show_warnings, show_timings=show_timings, strict=strict) elif os.path.isfile(filepath): cm = cif.reader(file_path=filepath, strict=strict).model() cm.validate(cif_dic, show_warnings=show_warnings) else: try: file_object = urllib.request.urlopen(filepath) except urllib.error.URLError as e: pass else: cm = cif.reader(file_object=file_object, strict=strict).model() cm.validate(cif_dic, show_warnings=show_warnings) if show_timings: total_timer.stop() print(total_timer.report())
def run(args, command_name="phenix.emma"): command_line = (option_parser( usage=command_name + " [options]" + " reference_coordinates other_coordinates", description="Example: %s model1.pdb model2.sdb" % command_name ).enable_symmetry_comprehensive().option( None, "--output_pdb", action="store", type="str", default="", help="Output pdb: second model transformed to best match first model", metavar="STR").option( None, "--tolerance", action="store", type="float", default=3., help="match tolerance", metavar="FLOAT").option( None, "--diffraction_index_equivalent", action="store_true", help="Use only if models are diffraction-index equivalent.") ).process(args=args, nargs=2) crystal_symmetry = command_line.symmetry if (crystal_symmetry.unit_cell() is None or crystal_symmetry.space_group_info() is None): for file_name in command_line.args: crystal_symmetry = crystal_symmetry.join_symmetry( other_symmetry=crystal_symmetry_from_any.extract_from( file_name=file_name), force=False) output_pdb = command_line.options.output_pdb if output_pdb: print "Output pdb:", output_pdb tolerance = command_line.options.tolerance print "Tolerance:", tolerance if (tolerance <= 0.): raise ValueError, "Tolerance must be greater than zero." print diffraction_index_equivalent = \ command_line.options.diffraction_index_equivalent if (diffraction_index_equivalent): print "Models are diffraction index equivalent." print second_model_as_pdb_inp = None emma_models = [] for file_name in command_line.args: emma_models.append( get_emma_model(file_name=file_name, crystal_symmetry=crystal_symmetry)) if len(emma_models) == 2 and os.path.isfile(file_name): try: second_model_as_pdb_inp = iotbx.pdb.input(file_name=file_name) except Exception, e: pass
def run(args, command_name="phenix.emma"): command_line = (option_parser( usage=command_name + " [options]" +" reference_coordinates other_coordinates", description="Example: %s model1.pdb model2.sdb" % command_name) .enable_symmetry_comprehensive() .option(None, "--output_pdb", action="store", type="str", default="", help="Output pdb: second model transformed to best match first model", metavar="STR") .option(None, "--tolerance", action="store", type="float", default=3., help="match tolerance", metavar="FLOAT") .option(None, "--diffraction_index_equivalent", action="store_true", help="Use only if models are diffraction-index equivalent.") ).process(args=args, nargs=2) crystal_symmetry = command_line.symmetry if ( crystal_symmetry.unit_cell() is None or crystal_symmetry.space_group_info() is None): for file_name in command_line.args: crystal_symmetry = crystal_symmetry.join_symmetry( other_symmetry=crystal_symmetry_from_any.extract_from( file_name=file_name), force=False) output_pdb = command_line.options.output_pdb if output_pdb: print "Output pdb:",output_pdb tolerance = command_line.options.tolerance print "Tolerance:", tolerance if (tolerance <= 0.): raise ValueError, "Tolerance must be greater than zero." print diffraction_index_equivalent = \ command_line.options.diffraction_index_equivalent if (diffraction_index_equivalent): print "Models are diffraction index equivalent." print second_model_as_pdb_inp=None emma_models = [] for file_name in command_line.args: emma_models.append(get_emma_model( file_name=file_name, crystal_symmetry=crystal_symmetry)) if len(emma_models)==2 and os.path.isfile(file_name): try: second_model_as_pdb_inp=iotbx.pdb.input( file_name=file_name) except Exception,e: pass
def run(args): command_line = (option_parser( usage="iotbx.reflection_file_reader [options] reflection_file ...", description="Example: iotbx.reflection_file_reader w1.sca w2.mtz w3.cns" ).enable_symmetry_comprehensive().option( None, "--weak_symmetry", action="store_true", default=False, help="symmetry on command line is weaker than symmetry found in files" ).option( None, "--show_data", action="store_true", default=False, help="show Miller indices and data of all arrays" ).option( None, "--pickle", action="store", type="string", help="write all data to FILE ('--pickle .' copies name of input file)", metavar="FILE")).process(args=args) if (len(command_line.args) == 0): command_line.parser.show_help() return if (command_line.options.show_data): verbose = 3 else: verbose = 2 all_miller_arrays = collect_arrays( file_names=command_line.args, crystal_symmetry=command_line.symmetry, force_symmetry=not command_line.options.weak_symmetry, discard_arrays=command_line.options.pickle is None, verbose=verbose, report_out=sys.stdout) if (all_miller_arrays is not None and len(all_miller_arrays) > 0): if (len(all_miller_arrays) == 1): all_miller_arrays = all_miller_arrays[0] pickle_file_name = command_line.options.pickle if (pickle_file_name == "."): if (len(command_line.args) > 1): raise Sorry( "Ambiguous name for pickle file (more than one input file)." ) pickle_file_name = os.path.basename(command_line.args[0]) if (pickle_file_name.lower().endswith(".pickle")): raise Sorry("Input file is already a pickle file.") if (not pickle_file_name.lower().endswith(".pickle")): pickle_file_name += ".pickle" print() print("Writing all Miller arrays to file:", pickle_file_name) easy_pickle.dump(pickle_file_name, all_miller_arrays) print()
def run(args, out=sys.stdout): if len(args) == 0: args = ["--help"] command_line = (option_parser( usage="iotbx.cif.validate filepath|directory [options]") .option(None, "--file_ext", action="store", default="cif") .option(None, "--dic", action="append", dest="dictionaries") .option(None, "--show_warnings", action="store_true") .option(None, "--show_timings", action="store_true") .option(None, "--strict", action="store", type="bool", default="true")).process(args=args) if len(command_line.args) != 1: command_line.parser.show_help() return total_timer = time_log("total").start() filepath = command_line.args[0] if not os.path.isabs(filepath): abs_path = libtbx.env.find_in_repositories(relative_path=filepath) if abs_path is None: abs_path = libtbx.env.find_in_repositories( relative_path=filepath, test=os.path.isfile) if abs_path is not None: filepath = abs_path cif_dics = command_line.options.dictionaries if cif_dics is None: cif_dics = ["cif_core.dic"] cif_dic = validation.smart_load_dictionary(name=cif_dics[0]) if len(cif_dics) > 1: [cif_dic.update( validation.smart_load_dictionary(name=d)) for d in cif_dics[1:]] show_warnings = command_line.options.show_warnings == True show_timings = command_line.options.show_timings == True strict = command_line.options.strict if os.path.isdir(filepath): file_ext = command_line.options.file_ext crawl(filepath, file_ext=file_ext, cif_dic=cif_dic, show_warnings=show_warnings, show_timings=show_timings, strict=strict) elif os.path.isfile(filepath): cm = cif.reader(file_path=filepath, strict=strict).model() cm.validate(cif_dic, show_warnings=show_warnings) else: try: file_object = urllib2.urlopen(filepath) except urllib2.URLError, e: pass else:
def run(args): command_line = (option_parser( usage="smtbx.absolute_structure directory|cif|fcf|hkl|ins/res [options]" ).enable_symmetry_comprehensive().option( None, "--ext", action="store", default="cif").option( None, "--nu", action="store", type="float").option( None, "--atomic_form_factors", action="store", default="it1992").option( None, "--inelastic_form_factors", action="store", default="henke").option( None, "--debug", action="store_true").option( None, "--verbose", action="store_true").option( None, "--log", action="store").option( None, "--chiral_space_groups_only", action="store_true").option( None, "--outlier_cutoff_factor", action="store", type="float")).process(args=args) if len(command_line.args) != 1: command_line.parser.show_help() return if command_line.options.log is not None: log = open(command_line.options.log, 'wb') else: log = None if os.path.isdir(command_line.args[0]): crawl( command_line.args[0], ext=command_line.options.ext, log=log, atomic_form_factors=command_line.options.atomic_form_factors, inelastic_form_factors=command_line.options.inelastic_form_factors, chiral_space_groups_only=command_line.options. chiral_space_groups_only, outlier_cutoff_factor=command_line.options.outlier_cutoff_factor) elif os.path.isfile(command_line.args[0]): run_once( command_line.args[0], nu=command_line.options.nu, log=log, atomic_form_factors=command_line.options.atomic_form_factors, inelastic_form_factors=command_line.options.inelastic_form_factors, outlier_cutoff_factor=command_line.options.outlier_cutoff_factor) else: print "Please provide a valid file or directory"
def run(args, command_name="phenix.find_reticular_twin_laws"): command_line = (option_parser( usage=command_name + " [options] ", description="Example: %s data1.mtz" % command_name ).enable_show_defaults().enable_symmetry_comprehensive().option( None, "--max_index", action="store", dest="max_index", default=3, type="int", metavar="INT").option(None, "--max_delta", dest="max_delta", default=5.0, type="float", metavar="FLOAT")).process(args=args) co = command_line.options if (len(args) == 0): command_line.parser.show_help() return max_delta = co.max_delta max_index = co.max_index xs = command_line.symmetry print "----- Input symmetry -----" xs.show_summary() print print " Settings:" print " max_delta: ", max_delta print " max_index: ", max_index print print "----- Finding reticular twin laws -----" print print """ Reticular twin laws are grouped by their associated sublattice. The matrix M acting on the input (base) lattice is listed, as well as the metric R value (\%) between the symmetrized sublattice and the unsymmetrized sublattice. reticular twin laws of twin index 1, are 'normal' twin laws """ tl = reticular_twin_laws.reticular_twin_laws(xs, max_delta, max_index) print "--------------- Twin law listing ---------------" print tl.show()
def run(args): command_line = (option_parser( usage="iotbx.reflection_file_reader [options] reflection_file ...", description="Example: iotbx.reflection_file_reader w1.sca w2.mtz w3.cns") .enable_symmetry_comprehensive() .option(None, "--weak_symmetry", action="store_true", default=False, help="symmetry on command line is weaker than symmetry found in files") .option(None, "--show_data", action="store_true", default=False, help="show Miller indices and data of all arrays") .option(None, "--pickle", action="store", type="string", help="write all data to FILE ('--pickle .' copies name of input file)", metavar="FILE") ).process(args=args) if (len(command_line.args) == 0): command_line.parser.show_help() return if (command_line.options.show_data): verbose = 3 else: verbose = 2 all_miller_arrays = collect_arrays( file_names=command_line.args, crystal_symmetry=command_line.symmetry, force_symmetry=not command_line.options.weak_symmetry, discard_arrays=command_line.options.pickle is None, verbose=verbose, report_out=sys.stdout) if (all_miller_arrays is not None and len(all_miller_arrays) > 0): if (len(all_miller_arrays) == 1): all_miller_arrays = all_miller_arrays[0] pickle_file_name = command_line.options.pickle if (pickle_file_name == "."): if (len(command_line.args) > 1): raise Sorry( "Ambiguous name for pickle file (more than one input file).") pickle_file_name = os.path.basename(command_line.args[0]) if (pickle_file_name.lower().endswith(".pickle")): raise Sorry("Input file is already a pickle file.") if (not pickle_file_name.lower().endswith(".pickle")): pickle_file_name += ".pickle" print print "Writing all Miller arrays to file:", pickle_file_name easy_pickle.dump(pickle_file_name, all_miller_arrays) print
def run(args): command_line = (option_parser( usage="smtbx.absolute_structure directory|cif|fcf|hkl|ins/res [options]") .enable_symmetry_comprehensive() .option(None, "--ext", action="store", default="cif") .option(None, "--nu", action="store", type="float") .option(None, "--atomic_form_factors", action="store", default="it1992") .option(None, "--inelastic_form_factors", action="store", default="henke") .option(None, "--debug", action="store_true") .option(None, "--verbose", action="store_true") .option(None, "--log", action="store") .option(None, "--chiral_space_groups_only", action="store_true") .option(None, "--outlier_cutoff_factor", action="store", type="float") ).process(args=args) if len(command_line.args) != 1: command_line.parser.show_help() return if command_line.options.log is not None: log = open(command_line.options.log, 'wb') else: log = None if os.path.isdir(command_line.args[0]): crawl(command_line.args[0], ext=command_line.options.ext, log=log, atomic_form_factors=command_line.options.atomic_form_factors, inelastic_form_factors=command_line.options.inelastic_form_factors, chiral_space_groups_only=command_line.options.chiral_space_groups_only, outlier_cutoff_factor=command_line.options.outlier_cutoff_factor) elif os.path.isfile(command_line.args[0]): run_once(command_line.args[0], nu=command_line.options.nu, log=log, atomic_form_factors=command_line.options.atomic_form_factors, inelastic_form_factors=command_line.options.inelastic_form_factors, outlier_cutoff_factor=command_line.options.outlier_cutoff_factor) else: print "Please provide a valid file or directory"
def run(args, command_name="iotbx.pdb.superpose_centers_of_mass"): if len(args) == 0: args = ["--help"] command_line = ( option_parser(usage="%s [options] [reference_file] [other_file] [parameter_file]" % command_name) .enable_show_defaults() .enable_symmetry_comprehensive() ).process(args=args) if command_line.expert_level is not None: master_params.show(expert_level=command_line.expert_level, attributes_level=command_line.attributes_level) sys.exit(0) # # Loop over command-line arguments. # parameter_interpreter = master_params.command_line_argument_interpreter() parsed_params = [] pdb_file_names = [] command_line_params = [] for arg in command_line.args: arg_is_processed = False if os.path.isfile(arg): params = None try: params = iotbx.phil.parse(file_name=arg) except KeyboardInterrupt: raise except RuntimeError: pass else: if len(params.objects) == 0: params = None if params is not None: parsed_params.append(params) arg_is_processed = True elif pdb.is_pdb_file(file_name=arg): pdb_file_names.append(arg) arg_is_processed = True if not arg_is_processed: try: params = parameter_interpreter.process(arg=arg) except Sorry, e: if not os.path.isfile(arg): raise raise Sorry("Unknown file format: %s" % arg) else: command_line_params.append(params)
def run(args, command_name="iotbx.pdb.superpose_centers_of_mass"): if (len(args) == 0): args = ["--help"] command_line = (option_parser( usage= "%s [options] [reference_file] [other_file] [parameter_file]" % command_name) .enable_show_defaults() .enable_symmetry_comprehensive() ).process(args=args) if (command_line.expert_level is not None): master_params.show( expert_level=command_line.expert_level, attributes_level=command_line.attributes_level) sys.exit(0) # # Loop over command-line arguments. # parameter_interpreter = master_params.command_line_argument_interpreter() parsed_params = [] pdb_file_names = [] command_line_params = [] for arg in command_line.args: arg_is_processed = False if (os.path.isfile(arg)): params = None try: params = iotbx.phil.parse(file_name=arg) except KeyboardInterrupt: raise except RuntimeError: pass else: if (len(params.objects) == 0): params = None if (params is not None): parsed_params.append(params) arg_is_processed = True elif (pdb.is_pdb_file(file_name=arg)): pdb_file_names.append(arg) arg_is_processed = True if (not arg_is_processed): try: params = parameter_interpreter.process(arg=arg) except Sorry, e: if (not os.path.isfile(arg)): raise raise Sorry("Unknown file format: %s" % arg) else: command_line_params.append(params)
def run(args, command_name="phenix.find_reticular_twin_laws"): command_line = (option_parser( usage=command_name+" [options] ", description="Example: %s data1.mtz" % command_name) .enable_show_defaults() .enable_symmetry_comprehensive() .option(None, "--max_index", action="store", dest="max_index",default=3,type="int",metavar="INT") .option(None,"--max_delta", dest="max_delta", default=5.0,type="float",metavar="FLOAT") ).process(args=args) co = command_line.options if (len(args) == 0): command_line.parser.show_help() return max_delta = co.max_delta max_index = co.max_index xs = command_line.symmetry print "----- Input symmetry -----" xs.show_summary() print print " Settings:" print " max_delta: ", max_delta print " max_index: ", max_index print print "----- Finding reticular twin laws -----" print print """ Reticular twin laws are grouped by their associated sublattice. The matrix M acting on the input (base) lattice is listed, as well as the metric R value (\%) between the symmetrized sublattice and the unsymmetrized sublattice. reticular twin laws of twin index 1, are 'normal' twin laws """ tl = reticular_twin_laws.reticular_twin_laws(xs,max_delta,max_index) print "--------------- Twin law listing ---------------" print tl.show()
def run(args, command_name="phenix.mtz.dump"): if (len(args) == 0): args = ["--help"] command_line = (option_parser( usage=command_name+" [options] file_name [...]") .option("-v", "--verbose", action="store_true", default=False, help="Enable CMTZ library messages.") .option("-c", "--show_column_data", action="store_true") .option("-f", "--column_data_format", action="store", type="string", metavar="KEYWORD", help="Valid keywords are: %s." % ", ".join(mtz.show_column_data_format_keywords) +" Human readable is the default. The format keywords can be" +" abbreviated (e.g. -f s).") .option("-b", "--show_batches", action="store_true") .option(None, "--walk", action="store", type="string", metavar="ROOT_DIR", help="Find and process all MTZ files under ROOT_DIR") ).process(args=args) if (len(command_line.args) == 0): print command_line.parser.format_help() return if (command_line.options.verbose): mtz.ccp4_liberr_verbosity(1) for file_name in command_line.args: process( file_name=file_name, show_column_data=command_line.options.show_column_data, column_data_format=command_line.options.column_data_format, show_batches=command_line.options.show_batches) if (command_line.options.walk is not None): os.path.walk( top=command_line.options.walk, func=walk_callback, arg=command_line.options)
def run(args, command_name="phenix.mtz.dump"): if (len(args) == 0): args = ["--help"] command_line = (option_parser( usage=command_name + " [options] file_name [...]").option( "-v", "--verbose", action="store_true", default=False, help="Enable CMTZ library messages." ).option("-c", "--show_column_data", action="store_true").option( "-f", "--column_data_format", action="store", type="string", metavar="KEYWORD", help="Valid keywords are: %s." % ", ".join(mtz.show_column_data_format_keywords) + " Human readable is the default. The format keywords can be" + " abbreviated (e.g. -f s).").option( "-b", "--show_batches", action="store_true").option( None, "--walk", action="store", type="string", metavar="ROOT_DIR", help="Find and process all MTZ files under ROOT_DIR") ).process(args=args) if (len(command_line.args) == 0): print command_line.parser.format_help() return if (command_line.options.verbose): mtz.ccp4_liberr_verbosity(1) for file_name in command_line.args: process(file_name=file_name, show_column_data=command_line.options.show_column_data, column_data_format=command_line.options.column_data_format, show_batches=command_line.options.show_batches) if (command_line.options.walk is not None): os.path.walk(top=command_line.options.walk, func=walk_callback, arg=command_line.options)
def run(args, command_name="phenix.emma"): command_line = (option_parser( usage=command_name + " [options]" +" reference_coordinates other_coordinates", description="Example: %s model1.pdb model2.sdb" % command_name) .enable_symmetry_comprehensive() .option(None, "--output_pdb", action="store", type="str", default="", help="Output pdb: second model transformed to best match first model", metavar="STR") .option(None, "--tolerance", action="store", type="float", default=3., help="match tolerance", metavar="FLOAT") .option(None, "--diffraction_index_equivalent", action="store_true", help="Use only if models are diffraction-index equivalent.") ).process(args=args, nargs=2) crystal_symmetry = command_line.symmetry if ( crystal_symmetry.unit_cell() is None or crystal_symmetry.space_group_info() is None): for file_name in command_line.args: crystal_symmetry = crystal_symmetry.join_symmetry( other_symmetry=crystal_symmetry_from_any.extract_from( file_name=file_name), force=False) output_pdb = command_line.options.output_pdb if output_pdb: print "Output pdb:",output_pdb tolerance = command_line.options.tolerance print "Tolerance:", tolerance if (tolerance <= 0.): raise ValueError, "Tolerance must be greater than zero." print diffraction_index_equivalent = \ command_line.options.diffraction_index_equivalent if (diffraction_index_equivalent): print "Models are diffraction index equivalent." print emma_models = [] for file_name in command_line.args: emma_models.append(get_emma_model( file_name=file_name, crystal_symmetry=crystal_symmetry)) emma_models[0].show("Reference model") emma_models[1].show("Other model") for model,label in zip(emma_models, ["reference", "other"]): if (model.unit_cell() is None): raise RuntimeError("Unit cell parameters unknown (%s model)." % label) if (model.space_group_info() is None): raise RuntimeError("Space group unknown (%s model)." % label) model_matches = emma.model_matches( model1=emma_models[0], model2=emma_models[1], tolerance=tolerance, models_are_diffraction_index_equivalent=diffraction_index_equivalent) if (model_matches.n_matches() == 0): print "No matches." print else: max_n_pairs = None first=True for match in model_matches.refined_matches: if (max_n_pairs is None or len(match.pairs) > max_n_pairs*0.2): print "." * 79 print match.show() if first and output_pdb: # 2013-01-25 tt match.get_transformed_model2(output_pdb=output_pdb, scattering_type="SE",f=sys.stdout) first=False if (max_n_pairs is None): max_n_pairs = len(match.pairs)
def run(args, command_name=libtbx.env.dispatcher_name): if (len(args) == 0): args = ["--help"] command_line = (option_parser( usage='%s pdb_file "atom_selection" [...]' % command_name) .option(None, "--write_pdb_file", action="store", type="string", default=None, help="write selected atoms to new PDB file", metavar="FILE") .option(None, "--cryst1_replacement_buffer_layer", action="store", type="float", default=None, help="replace CRYST1 with pseudo unit cell covering the selected" " atoms plus a surrounding buffer layer", metavar="WIDTH") ).process(args=args, min_nargs=2) co = command_line.options 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=command_line.args[0], log=sys.stdout) print acp = processed_pdb_file.all_chain_proxies hierarchy=acp.pdb_hierarchy asc=hierarchy.atom_selection_cache() sel=asc.selection(string = "chain 'A' and resid 1 through 8 and icode ' '") h1=hierarchy.select(sel) # keep original hierarchy too print h1.as_pdb_string() selection_cache = acp.pdb_hierarchy.atom_selection_cache() atoms = acp.pdb_atoms all_bsel = flex.bool(atoms.size(), False) for selection_string in command_line.args[1:]: 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(args): command_line = (option_parser( usage="iotbx.python strudat_as_fis.py [options] studat_file [...]") .option(None, "--tag", action="store", type="string", help="tag as it appears in the strudat file") .option(None, "--coseq", action="store", type="string", help="name of file with known coordination sequences", metavar="FILE") ).process(args=args) if (len(command_line.args) == 0): command_line.parser.show_help() return if (command_line.options.coseq is not None): coseq_dict = coordination_sequences.get_kriber_coseq_file( file_name=command_line.options.coseq) else: coseq_dict = None n_fis = 0 n_errors = 0 for file_name in command_line.args: strudat_entries = strudat.read_all_entries(open(file_name)) for entry in strudat_entries.entries: if ( command_line.options.tag is not None and command_line.options.tag != entry.tag): continue print "strudat tag:", entry.tag print xray_structure = entry.as_xray_structure() pairs, term_table = display( distance_cutoff=3.4, show_cartesian=False, max_shell=10, coseq_dict=coseq_dict, xray_structure=xray_structure) fis = format_focus_input( tag=entry.tag, xray_structure=xray_structure, term_table=term_table) open("tmp.fis", "w").write(fis) open("%s.fis" % entry.tag, "w").write(fis) n_fis += 1 if (os.path.isfile("tmp.fo")): os.remove("tmp.fo") assert not os.path.isfile("tmp.fo") focus_run = easy_run.fully_buffered( command="focus -siteframe -sitelabel -coseq=10 tmp.fis > tmp.fo") focus_run.raise_if_errors_or_output() lines = open("tmp.fo").read().splitlines() focus_coseq = extract_coseq(lines=lines) for scatterer,terms in zip(xray_structure.scatterers(), term_table): focus_terms = focus_coseq[scatterer.label] if (list(terms) != focus_terms): print "ERROR:", entry.tag print " cctbx", list(terms) print " focus", focus_terms n_errors += 1 print "Number of .fis files written:", n_fis print "Number of errors:", n_errors for file_name in ["tmp.fis", "tmp.fo"]: if (os.path.isfile(file_name)): os.remove(file_name)
def run(args, command_name="phenix.cns_as_mtz"): if (len(args) == 0): args = ["--help"] command_line = (option_parser( usage="%s [options] cns_file" % command_name, description="Example: %s scale.hkl" % command_name) .enable_symmetry_comprehensive() .option("-q", "--quiet", action="store_true", default=False, help="suppress output") ).process(args=args) if (len(command_line.args) != 1): command_line.parser.show_help() return cns_file_name = command_line.args[0] crystal_symmetry = command_line.symmetry if (crystal_symmetry.unit_cell() is None): print print "*" * 79 print "Unknown unit cell parameters." print "Use --symmetry or --unit_cell to define unit cell:" print "*" * 79 print command_line.parser.show_help() return if (crystal_symmetry.space_group_info() is None): print print "*" * 79 print "Unknown space group." print "Use --symmetry or --space_group to define space group:" print "*" * 79 print command_line.parser.show_help() return if (not command_line.options.quiet): print "CNS file name:", cns_file_name print "Crystal symmetry:" crystal_symmetry.show_summary(prefix=" ") reflection_file = iotbx.cns.reflection_reader.cns_reflection_file( file_handle=open(cns_file_name, "r")) if (not command_line.options.quiet): reflection_file.show_summary() miller_arrays = reflection_file.as_miller_arrays( crystal_symmetry=crystal_symmetry) mtz_dataset = None for miller_array in miller_arrays: if (mtz_dataset is None): mtz_dataset = miller_array.as_mtz_dataset( column_root_label=miller_array.info().labels[0]) else: mtz_dataset.add_miller_array( miller_array=miller_array, column_root_label=miller_array.info().labels[0]) mtz_object = mtz_dataset.mtz_object() for column in mtz_object.columns(): column_type = { "FOM": "W", "PHASE": "P"}.get(column.label()) if (column_type is not None): column.set_type(new_type=column_type) mtz_object.show_summary() mtz_file_name = os.path.basename(cns_file_name) if (mtz_file_name.count(".") == 1): mtz_file_name = mtz_file_name[:mtz_file_name.index(".")] mtz_file_name += ".mtz" print "Writing MTZ file:", mtz_file_name mtz_object.write(mtz_file_name)
def run(args, distance_cutoff=3.5): from iotbx.option_parser import option_parser command_line = (option_parser( usage="iotbx.distance_least_squares [options] studat_file [...]", description="Example: iotbx.distance_least_squares strudat --tag=SOD" ).option( None, "--tag", action="store", type="string", help="tag as it appears in the strudat file").option( None, "--repulsion_function", action="store", type="choice", choices=["gaussian", "cos", "prolsq"], default="gaussian", help="Nonbonded repulsion function type", metavar="gaussian|cos|prolsq").option( None, "--bond_stretch_factor", action="store", type="float", default=0.1, help="Bond stretch factor used in max residual calculation" " for nonbonded cos or gaussian repulsion function", metavar="FLOAT").option( None, "--n_trials", action="store", type="int", default=1, help="Number of trial per structure", metavar="INT").option( None, "--n_macro_cycles", action="store", type="int", default=1, help="Number of macro cycles per trial", metavar="INT").option( None, "--dev", action="store_true", default=False)).process(args=args) if (len(command_line.args) == 0): command_line.parser.show_help() return co = command_line.options from cctbx.geometry_restraints import distance_least_squares as dls from iotbx.kriber import strudat for file_name in command_line.args: strudat_entries = strudat.read_all_entries(open(file_name)) for entry in strudat_entries.entries: if (co.tag is not None and co.tag != entry.tag): continue print("strudat tag:", entry.tag) print() dls.distance_and_repulsion_least_squares( si_structure=entry.as_xray_structure(), distance_cutoff=distance_cutoff, nonbonded_repulsion_function_type=co.repulsion_function, nonbonded_max_residual_bond_stretch_factor=co. bond_stretch_factor, n_trials=co.n_trials, n_macro_cycles=co.n_macro_cycles, connectivities=entry.connectivities(all_or_nothing=True), dev=co.dev)
def run(args, command_name="emma_shelxd_lst.py"): command_line = (option_parser( usage=command_name + " [options]" +" reference_coordinates shelxd-lst-file", description="Example: %s model1.pdb sad_fa.lst" % command_name) .enable_symmetry_comprehensive() .option(None, "--tolerance", action="store", type="float", default=.5, help="match tolerance", metavar="FLOAT") .option(None, "--diffraction_index_equivalent", action="store_true", help="Use only if models are diffraction-index equivalent.") ).process(args=args, nargs=2) crystal_symmetry = command_line.symmetry if ( crystal_symmetry.unit_cell() is None or crystal_symmetry.space_group_info() is None): for file_name in command_line.args: crystal_symmetry = crystal_symmetry.join_symmetry( other_symmetry=crystal_symmetry_from_any.extract_from( file_name=file_name), force=False) tolerance = command_line.options.tolerance print "Tolerance:", tolerance if (tolerance <= 0.): raise ValueError, "Tolerance must be greater than zero." print diffraction_index_equivalent = \ command_line.options.diffraction_index_equivalent if (diffraction_index_equivalent): print "Models are diffraction index equivalent." print emma_ref = get_emma_model(file_name=command_line.args[0], crystal_symmetry=crystal_symmetry) emma_ref.show("Reference model") emma_others = get_emma_models_from_lst(command_line.args[1], crystal_symmetry) print "try CCall CCweak nmatch rms order.min order.max" for emma_other, itry, ccall, ccweak in emma_others: model_matches = emma.model_matches(model1=emma_ref, model2=emma_other, tolerance=tolerance, models_are_diffraction_index_equivalent=diffraction_index_equivalent) print itry, ccall, ccweak, if (model_matches.n_matches() == 0): print "0 nan nan nan" else: max_n_pairs = None first=True for match in model_matches.refined_matches: if (max_n_pairs is None or len(match.pairs) > max_n_pairs*0.2): orders = map(lambda x: int(x[1]), match.pairs) print "%3d %.5f %3d %3d" % (len(match.pairs), match.rms, min(orders), max(orders)) #match.show() #first=False break if (max_n_pairs is None): max_n_pairs = len(match.pairs)
def run(args, command_name="phenix.explore_metric_symmetry"): command_line = (option_parser( usage=command_name + " [options]", description="""\ Explore Metric Symmetry. A list of possible unit cells and spacegroups is given for the given specified unit cell and spacegroup combination. If a second unit cell is given, linear combinations of the basis vector of one unit cell are sought that match the other.""" ).enable_symmetry_comprehensive().option( None, "--max_delta", action="store", type="float", default=5.0, dest="max_delta", help= "Maximum delta/obliquity used in determining the lattice symmetry, using a modified Le-Page algorithm. Default is 5.0 degrees", metavar="FLOAT" ).option( None, "--start_from_p1", action="store_true", dest="niggli", default=False, help= "Reduce to Niggli cell and forget the input spacegroup before higher metric symmetry is sought." ).option( None, "--graph", action="store", default=None, help="A graphical representation of the graph will be written out." " Requires Graphviz to be installed and on PATH.").option( None, "--centring_type", action="store", type="str", help="Centring type, choose from P,A,B,C,I,R,F" ).option( None, "--other_unit_cell", action="store", type="str", help="Other unit cell, for unit cell comparison", metavar="10,20,30,90,103.7,90" ).option( None, "--other_space_group", action="store", type="str", help="space group for other_unit_cell, for unit cell comparison" ).option( None, "--other_centring_type", action="store", type="str", help="Centring type, choose from P,A,B,C,I,R,F" ).option( None, "--no_point_group_graph", action="store_true", dest="pg_graph", default=False, help="Do not carry out the construction of a point group graph." ).option( None, "--relative_length_tolerance", action="store", type="float", help="Tolerance for unit cell lengths to be considered equal-ish.", default=0.10, metavar="FLOAT", dest="rel_length_tol").option( None, "--absolute_angle_tolerance", action="store", dest="abs_angle_tol", type="float", default=10.0, metavar="FLOAT", help="Angular tolerance in unit cell comparison").option( None, "--max_order", action="store", type="int", default=1, metavar="INT", help="Maximum volume change for target cell")).process( args=args) log = multi_out() log.register(label="stdout", file_object=sys.stdout) allowed_centring_types = { "P": "Primitive", "A": "A centered", "B": "B centered", "C": "C centered", "I": "Body centered", "R": "Rombohedral", "F": "Face centered" } if command_line.options.centring_type is not None: if not allowed_centring_types.has_key( command_line.options.centring_type): print >> log, "Sorry, the centring type %s is not known." % ( command_line.options.centring_type) print >> log, "Choose from P,A,B,C,I,R,F " return xs = None other_xs = None if len(args) == 0: command_line.parser.show_help() return if (command_line.symmetry.unit_cell() == None): print >> log print >> log, "Sorry: Unit cell not specified." print >> log command_line.parser.show_help() return if command_line.options.centring_type is None: if (command_line.symmetry.space_group_info() == None): print >> log print >> log, "Sorry: centring type or space group not specified." print >> log command_line.parser.show_help() return if command_line.symmetry.space_group_info() is not None: if not (command_line.symmetry.space_group().is_chiral()): print >> log, "Sorry, Non chiral space groups not yet supported." return if command_line.options.centring_type is not None: xs = crystal.symmetry(unit_cell=command_line.symmetry.unit_cell(), space_group_symbol="Hall: %s 1" % (command_line.options.centring_type)) command_line.symmetry = xs if command_line.options.niggli: print >> log, "*Unit cell will be niggli reduced and P1 will be assumed*" uc = command_line.symmetry.change_basis( command_line.symmetry.change_of_basis_op_to_niggli_cell( )).unit_cell() command_line.symmetry = crystal.symmetry(uc, "P 1") xs = command_line.symmetry ############################################################################ # ABOVE IS JUST INPUT PARSING, NOW THE ACTUAL STUFF HAPPENS ############################################################################ if not command_line.options.pg_graph: ############################## # get a point group graph # ############################## pg_object = do_pointgroup_tricks(xs.unit_cell(), xs.space_group(), command_line.options.max_delta, log) ################################################ # make a graphical representation if desired # ################################################ if command_line.options.graph is not None: make_graph_of_graph(pg_object, command_line.options.graph, log) ######################################### # Check if other cell has been defined # ######################################### if command_line.options.other_unit_cell is not None: print >> log, "A second unit cell has been specified. " other_xs = None if command_line.options.other_space_group is None: if command_line.options.other_centring_type is None: raise Sorry( "No space group or centring type for other cell specified." ) else: other_xs = crystal.symmetry( command_line.options.other_unit_cell, space_group_symbol="Hall: %s 1" % (command_line.options.other_centring_type)) else: other_xs = crystal.symmetry( command_line.options.other_unit_cell, space_group_symbol=command_line.options.other_space_group) # get the graph is desired if not command_line.options.pg_graph: other_pg_object = do_pointgroup_tricks( other_xs.unit_cell(), other_xs.space_group(), command_line.options.max_delta, log) # do the unit cell comparison print >> log print >> log print >> log, "Unit cell comparison" print >> log, "--------------------" print >> log print >> log, "The unit cells will be compared. The smallest niggli cell," print >> log, "will be used as a (semi-flexible) lego-block to see if it" print >> log, "can construct the larger Niggli cell." print >> log print >> log order = command_line.options.max_order if order == 1: sl_object = slt.compare_lattice( xs_a=xs, xs_b=other_xs, max_delta=command_line.options.max_delta, out=log, relative_length_tolerance=command_line.options.rel_length_tol, absolute_angle_tolerance=command_line.options.abs_angle_tol) else: tmp_a = xs.change_basis(xs.change_of_basis_op_to_niggli_cell()) tmp_b = other_xs.change_basis( other_xs.change_of_basis_op_to_niggli_cell()) modified_xs = None order = command_line.options.max_order lego_block = None if (tmp_a.unit_cell().volume() > tmp_b.unit_cell().volume()): modified_xs = slt.make_list_of_target_xs_up_to_order(xs, order) lego_block = other_xs else: modified_xs = slt.make_list_of_target_xs_up_to_order( other_xs, order) lego_block = xs print >> log print >> log, "Volume change of largest niggli cell requested via keyword --max_order" print >> log print >> log, "Input crystal symmetry is tranformed to niggli setting using the operator:" print >> log, modified_xs.basic_to_niggli_cb_op.as_xyz() print >> log print >> log, "Comparisons for various sublattices of the target cell are listed" print >> log for tmp_xs, cb_op, mat in zip(modified_xs.xs_list, modified_xs.extra_cb_op, modified_xs.matrices): mat = mat.as_list_of_lists() print >> log, "===================================================================" print >> log, "Niggli cell is expanded using matrix:" print >> log print >> log, " /%4i %4i %4i \ " % ( mat[0][0], mat[0][1], mat[0][2]) print >> log, " M = |%4i %4i %4i | " % ( mat[1][0], mat[1][1], mat[1][2]) print >> log, " \%4i %4i %4i / " % ( mat[2][0], mat[2][1], mat[2][2]) print >> log print >> log, "Change of basis operator to reference setting:" print >> log, " ", cb_op.as_xyz() print >> log, "resulting crystal symmetry:" tmp_xs.show_summary(f=log, prefix=" ") print >> log print >> log sl_object = slt.compare_lattice( xs_a=tmp_xs, xs_b=lego_block, max_delta=command_line.options.max_delta, out=log, relative_length_tolerance=command_line.options. rel_length_tol, absolute_angle_tolerance=command_line.options.abs_angle_tol )
def run(args, command_name="phenix.pdb.hierarchy"): if (len(args) == 0): args = ["--help"] command_line = (option_parser( usage="%s file..." % command_name) .option(None, "--details", action="store", type="string", default=None, help="level of detail", metavar="|".join(pdb.hierarchy.level_ids)) .option(None, "--residue_groups_max_show", action="store", type="int", default=10, help="maximum number of residue groups to be listed along with" " errors or warnings", metavar="INT") .option(None, "--duplicate_atom_labels_max_show", action="store", type="int", default=10, help="maximum number of groups of duplicate atom labels to be listed", metavar="INT") .option(None, "--prefix", action="store", type="string", default="", help="prefix for all output lines", metavar="STRING") .option(None, "--write_pdb_file", action="store", type="string", default=None, help="write hierarchy as PDB coordinate section to file", metavar="FILE") .option(None, "--set_element_simple", action="store_true", default=False, help="sets or tidies ATOM record element columns (77-78) if necessary" " before writing PDB file") .option(None, "--reset_serial_first_value", action="store", type="int", default=None, help="resets atom serial numbers before writing PDB file", metavar="INT") .option(None, "--interleaved_conf", action="store", type="int", default=0, help="interleave alt. conf. when writing PDB file; possible choices are:" " 0 (not interleaved)," " 1 (interleaved atom names but not resnames)," " 2 (fully interleaved)", metavar="INT") .option(None, "--no_anisou", action="store_true", default=False, help="suppress ANISOU records when writing PDB file") .option(None, "--no_sigatm", action="store_true", default=False, help="suppress SIGATM records when writing PDB file") .option(None, "--no_cryst", action="store_true", default=False, help="suppress crystallographic records (e.g. CRYST1 and SCALEn)" " when writing PDB file") ).process(args=args) co = command_line.options for file_name in command_line.args: if (not os.path.isfile(file_name)): continue pdb_objs = execute( file_name=file_name, prefix=co.prefix, residue_groups_max_show=co.residue_groups_max_show, duplicate_atom_labels_max_show=co.duplicate_atom_labels_max_show, level_id=co.details) if (co.write_pdb_file is not None): if (co.set_element_simple): pdb_objs.hierarchy.atoms().set_chemical_element_simple_if_necessary() open_append = False if (not co.no_cryst): s = pdb_objs.input.crystallographic_section() if (s.size() != 0): print >> open(co.write_pdb_file, "wb"), "\n".join(s) open_append = True pdb_objs.hierarchy.write_pdb_file( file_name=co.write_pdb_file, open_append=open_append, append_end=True, interleaved_conf=co.interleaved_conf, atoms_reset_serial_first_value=co.reset_serial_first_value, sigatm=not co.no_sigatm, anisou=not co.no_anisou, siguij=not co.no_anisou) print co.prefix.rstrip()
def run(args, distance_cutoff=3.5): from iotbx.option_parser import option_parser command_line = (option_parser( usage="iotbx.distance_least_squares [options] studat_file [...]", description="Example: iotbx.distance_least_squares strudat --tag=SOD") .option(None, "--tag", action="store", type="string", help="tag as it appears in the strudat file") .option(None, "--repulsion_function", action="store", type="choice", choices=["gaussian", "cos", "prolsq"], default="gaussian", help="Nonbonded repulsion function type", metavar="gaussian|cos|prolsq") .option(None, "--bond_stretch_factor", action="store", type="float", default=0.1, help="Bond stretch factor used in max residual calculation" " for nonbonded cos or gaussian repulsion function", metavar="FLOAT") .option(None, "--n_trials", action="store", type="int", default=1, help="Number of trial per structure", metavar="INT") .option(None, "--n_macro_cycles", action="store", type="int", default=1, help="Number of macro cycles per trial", metavar="INT") .option(None, "--dev", action="store_true", default=False) ).process(args=args) if (len(command_line.args) == 0): command_line.parser.show_help() return co = command_line.options from cctbx.geometry_restraints import distance_least_squares as dls from iotbx.kriber import strudat for file_name in command_line.args: strudat_entries = strudat.read_all_entries(open(file_name)) for entry in strudat_entries.entries: if (co.tag is not None and co.tag != entry.tag): continue print "strudat tag:", entry.tag print dls.distance_and_repulsion_least_squares( si_structure=entry.as_xray_structure(), distance_cutoff=distance_cutoff, nonbonded_repulsion_function_type=co.repulsion_function, nonbonded_max_residual_bond_stretch_factor=co.bond_stretch_factor, n_trials=co.n_trials, n_macro_cycles=co.n_macro_cycles, connectivities=entry.connectivities(all_or_nothing=True), dev=co.dev)
def run(args, log = sys.stdout, as_gui_program=False): if(len(args)==0): parsed = defaults(log=log) parsed.show(prefix=" ", out=log) return command_line = (option_parser() .enable_symmetry_comprehensive() .option("-q", "--quiet", action="store_true", default=False, help="suppress output") .option("--output_plots", action="store_true", default=False) ).process(args=args) parsed = defaults(log=log) processed_args = mmtbx.utils.process_command_line_args( args=command_line.args, cmd_cs=command_line.symmetry, master_params=parsed, log=log, suppress_symmetry_related_errors=True) processed_args.params.show(out=log) params = processed_args.params.extract().density_modification output_plots = command_line.options.output_plots crystal_symmetry = crystal.symmetry( unit_cell=params.input.unit_cell, space_group_info=params.input.space_group) reflection_files = {} for rfn in (params.input.reflection_data.file_name, params.input.experimental_phases.file_name, params.input.map_coefficients.file_name): if os.path.isfile(str(rfn)) and rfn not in reflection_files: reflection_files.setdefault( rfn, iotbx.reflection_file_reader.any_reflection_file( file_name=rfn, ensure_read_access=False)) server = iotbx.reflection_file_utils.reflection_file_server( crystal_symmetry=crystal_symmetry, reflection_files=reflection_files.values()) fo = mmtbx.utils.determine_data_and_flags( server, parameters=params.input.reflection_data, extract_r_free_flags=False,log=log).f_obs hl_coeffs = mmtbx.utils.determine_experimental_phases( server, params.input.experimental_phases, log=log, parameter_scope="", working_point_group=None, symmetry_safety_check=True, ignore_all_zeros=True) if params.input.map_coefficients.file_name is not None: map_coeffs = server.get_phases_deg( file_name=params.input.map_coefficients.file_name, labels=params.input.map_coefficients.labels, convert_to_phases_if_necessary=False, original_phase_units=None, parameter_scope="", parameter_name="labels").map_to_asu() else: map_coeffs = None ncs_object = None if params.input.ncs_file_name is not None: ncs_object = ncs.ncs() ncs_object.read_ncs(params.input.ncs_file_name) ncs_object.display_all(log=log) fo = fo.map_to_asu() hl_coeffs = hl_coeffs.map_to_asu() fo = fo.eliminate_sys_absent().average_bijvoet_mates() hl_coeffs = hl_coeffs.eliminate_sys_absent().average_bijvoet_mates() model_map = None model_map_coeffs = None if len(processed_args.pdb_file_names): pdb_file = mmtbx.utils.pdb_file( pdb_file_names=processed_args.pdb_file_names) xs = pdb_file.pdb_inp.xray_structure_simple() fo_, hl_ = fo, hl_coeffs if params.change_basis_to_niggli_cell: change_of_basis_op = xs.change_of_basis_op_to_niggli_cell() xs = xs.change_basis(change_of_basis_op) fo_ = fo_.change_basis(change_of_basis_op).map_to_asu() hl_ = hl_.change_basis(change_of_basis_op).map_to_asu() #fo_, hl_ = fo_.common_sets(hl_) fmodel_refined = mmtbx.utils.fmodel_simple( f_obs=fo_, scattering_table="wk1995",#XXX pva: 1) neutrons? 2) move up as a parameter. xray_structures=[xs], bulk_solvent_correction=True, anisotropic_scaling=True, r_free_flags=fo_.array(data=flex.bool(fo_.size(), False))) fmodel_refined.update(abcd=hl_) master_phil = mmtbx.maps.map_and_map_coeff_master_params() map_params = master_phil.fetch(iotbx.phil.parse("""\ map_coefficients { map_type = 2mFo-DFc isotropize = True } """)).extract().map_coefficients[0] model_map_coeffs = mmtbx.maps.map_coefficients_from_fmodel( fmodel=fmodel_refined, params=map_params) model_map = model_map_coeffs.fft_map( resolution_factor=params.grid_resolution_factor).real_map_unpadded() import time t0 = time.time() dm = density_modify( params, fo, hl_coeffs, ncs_object=ncs_object, map_coeffs=map_coeffs, model_map_coeffs=model_map_coeffs, log=log, as_gui_program=as_gui_program) time_dm = time.time()-t0 print >> log, "Time taken for density modification: %.2fs" %time_dm # run cns if 0: from cctbx.development import cns_density_modification cns_result = cns_density_modification.run(params, fo, hl_coeffs) print cns_result.modified_map.all() print dm.map.all() dm_map_coeffs = dm.map_coeffs_in_original_setting from cctbx import maptbx, miller crystal_gridding = maptbx.crystal_gridding( dm_map_coeffs.unit_cell(), space_group_info=dm_map_coeffs.space_group().info(), pre_determined_n_real=cns_result.modified_map.all()) dm_map = miller.fft_map(crystal_gridding, dm_map_coeffs).apply_sigma_scaling() corr = flex.linear_correlation(cns_result.modified_map.as_1d(), dm_map.real_map_unpadded().as_1d()) print "CNS dm/mmtbx dm correlation:" corr.show_summary() if dm.model_map_coeffs is not None: model_map = miller.fft_map( crystal_gridding, dm.miller_array_in_original_setting(dm.model_map_coeffs)).apply_sigma_scaling() corr = flex.linear_correlation(cns_result.modified_map.as_1d(), model_map.real_map_unpadded().as_1d()) print "CNS dm/model correlation:" corr.show_summary() if output_plots: plots_to_make = ( "fom", "skewness", "r1_factor", "r1_factor_fom", "mean_solvent_density", "mean_protein_density", "f000_over_v", "k_flip", "rms_solvent_density", "rms_protein_density", "standard_deviation_local_rms", "mean_delta_phi", "mean_delta_phi_initial", ) from matplotlib.backends.backend_pdf import PdfPages from libtbx import pyplot stats = dm.get_stats() pdf = PdfPages("density_modification.pdf") if len(dm.correlation_coeffs) > 1: if 0: start_coeffs, model_coeffs = dm.map_coeffs_start.common_sets(model_map_coeffs) model_phases = model_coeffs.phases(deg=True).data() exptl_phases = nearest_phase( model_phases, start_coeffs.phases(deg=True).data(), deg=True) corr = flex.linear_correlation(exptl_phases, model_phases) corr.show_summary() fig = pyplot.figure() ax = fig.add_subplot(1,1,1) ax.set_title("phases start") ax.set_xlabel("Experimental phases") ax.set_ylabel("Phases from refined model") ax.scatter(exptl_phases, model_phases, marker="x", s=10) pdf.savefig(fig) # dm_coeffs, model_coeffs = dm.map_coeffs.common_sets(model_map_coeffs) model_phases = model_coeffs.phases(deg=True).data() dm_phases = nearest_phase( model_phases, dm_coeffs.phases(deg=True).data(), deg=True) corr = flex.linear_correlation(dm_phases, model_phases) corr.show_summary() fig = pyplot.figure() ax = fig.add_subplot(1,1,1) ax.set_title("phases dm") ax.set_xlabel("Phases from density modification") ax.set_ylabel("Phases from refined model") ax.scatter(dm_phases, model_phases, marker="x", s=10) pdf.savefig(fig) # data = dm.correlation_coeffs fig = pyplot.figure() ax = fig.add_subplot(1,1,1) ax.set_title("correlation coefficient") ax.plot(range(1, dm.i_cycle+2), data) pdf.savefig(fig) # data = dm.mean_phase_errors fig = pyplot.figure() ax = fig.add_subplot(1,1,1) ax.set_title("Mean effective phase errors") ax.plot(range(1, dm.i_cycle+2), data) pdf.savefig(fig) for plot in plots_to_make: data = [getattr(stats.get_cycle_stats(i), plot) for i in range(1, dm.i_cycle+2)] fig = pyplot.figure() ax = fig.add_subplot(1,1,1) ax.set_title(plot.replace("_", " ")) ax.plot(range(1, dm.i_cycle+2), data) pdf.savefig(fig) data = [stats.get_cycle_stats(i).rms_solvent_density/ stats.get_cycle_stats(i).rms_protein_density for i in range(1, dm.i_cycle+2)] fig = pyplot.figure() ax = fig.add_subplot(1,1,1) ax.set_title("RMS solvent/protein density ratio") ax.plot(range(1, dm.i_cycle+2), data) pdf.savefig(fig) pdf.close() dm_map_coeffs = dm.map_coeffs_in_original_setting dm_hl_coeffs = dm.hl_coeffs_in_original_setting # output map if requested map_params = params.output.map if map_params.file_name is not None: fft_map = dm_map_coeffs.fft_map(resolution_factor=params.grid_resolution_factor) if map_params.scale == "sigma": fft_map.apply_sigma_scaling() else: fft_map.apply_volume_scaling() gridding_first = gridding_last = None title_lines = [] if map_params.format == "xplor": fft_map.as_xplor_map( file_name = map_params.file_name, title_lines = title_lines, gridding_first = gridding_first, gridding_last = gridding_last) else : fft_map.as_ccp4_map( file_name = map_params.file_name, gridding_first = gridding_first, gridding_last = gridding_last, labels=title_lines) # output map coefficients if requested mtz_params = params.output.mtz # Decide if we are going to actually write the mtz if mtz_params.file_name is not None: orig_fom,final_fom=dm.start_and_end_fom() if mtz_params.skip_output_if_worse and final_fom < orig_fom: ok_to_write_mtz=False print "Not writing out mtz. Final FOM (%7.3f) worse than start (%7.3f)" %( final_fom,orig_fom) else: # usual ok_to_write_mtz=True else: ok_to_write_mtz=True if mtz_params.file_name is not None and ok_to_write_mtz: label_decorator=iotbx.mtz.ccp4_label_decorator() fo = dm.miller_array_in_original_setting(dm.f_obs_complete).common_set(dm_map_coeffs) mtz_dataset = fo.as_mtz_dataset( column_root_label="F", label_decorator=label_decorator) mtz_dataset.add_miller_array( dm_map_coeffs, column_root_label="FWT", label_decorator=label_decorator) phase_source = dm.miller_array_in_original_setting(dm.phase_source).common_set(dm_map_coeffs) mtz_dataset.add_miller_array( phase_source.array(data=flex.abs(phase_source.data())), column_root_label="FOM", column_types='W', label_decorator=label_decorator) mtz_dataset.add_miller_array( phase_source.array(data=phase_source.phases(deg=True).data()), column_root_label="PHIB", column_types='P', label_decorator=None) if mtz_params.output_hendrickson_lattman_coefficients: mtz_dataset.add_miller_array( dm_hl_coeffs, column_root_label="HL", label_decorator=label_decorator) mtz_dataset.mtz_object().write(mtz_params.file_name) return result( map_file=map_params.file_name, mtz_file=mtz_params.file_name, stats=dm.get_stats())
def run(args): def vdw_radii_callback(option, opt_str, value, parser): # create a dict from space separated string of element types and radii radii = {} items = value.split() assert len(items) % 2 == 0 for i in range(int(len(items) / 2)): radii.setdefault(items[i*2], float(items[i*2+1])) setattr(parser.values, option.dest, radii) command_line = (option_parser( usage="smtbx.masks structure reflections [options]") .enable_symmetry_comprehensive() .option(None, "--solvent_radius", action="store", type="float", default=1.3) .option(None, "--shrink_truncation_radius", action="store", type="float", default=1.3) .option(None, "--debug", action="store_true") .option(None, "--verbose", action="store_true") .option(None, "--resolution_factor", action="store", type="float", default=1/4) .option(None, "--grid_step", action="store", type="float") .option(None, "--d_min", action="store", type="float") .option(None, "--two_theta_max", action="store", type="float") .option(None, "--cb_op", action="store", type="string") .option(None, "--vdw_radii", action="callback", callback=vdw_radii_callback, type="string", nargs=1) .option(None, "--use_space_group_symmetry", action="store_true")).process(args=args) structure_file = command_line.args[0] ext = os.path.splitext(structure_file)[-1].lower() if ext in ('.res', '.ins'): xs = xray.structure.from_shelx(filename=structure_file) elif ext == '.cif': xs = xray.structure.from_cif(filename=structure_file) else: print "%s: unsupported structure file format {shelx|cif}" %ext return reflections_server = reflection_file_utils.reflection_file_server( crystal_symmetry = xs.crystal_symmetry(), reflection_files = [ reflection_file_reader.any_reflection_file(command_line.args[1]) ] ) fo_sq = reflections_server.get_miller_arrays(None)[0] if command_line.options.cb_op is not None: cb_op = sgtbx.change_of_basis_op(sgtbx.rt_mx(command_line.options.cb_op)) fo_sq = fo_sq.change_basis(cb_op).customized_copy( crystal_symmetry=xs) print "structure file: %s" %command_line.args[0] print "reflection file: %s" %command_line.args[1] if command_line.options.debug: print "debug: %s" %command_line.options.debug print xs.show_summary() print d_min = command_line.options.d_min two_theta_max = command_line.options.two_theta_max assert [d_min, two_theta_max].count(None) > 0 if two_theta_max is not None: d_min = uctbx.two_theta_as_d(two_theta_max, wavelength=0.71073, deg=True) exercise_masks( xs, fo_sq, solvent_radius=command_line.options.solvent_radius, shrink_truncation_radius=command_line.options.shrink_truncation_radius, resolution_factor=command_line.options.resolution_factor, grid_step=command_line.options.grid_step, resolution_cutoff=d_min, atom_radii_table=command_line.options.vdw_radii, use_space_group_symmetry=command_line.options.use_space_group_symmetry, debug=command_line.options.debug, verbose=command_line.options.verbose) print "OK"
def run(args, command_name="phenix.emma"): command_line = (option_parser( usage=command_name + " [options]" + " reference_coordinates other_coordinates", description="Example: %s model1.pdb model2.sdb" % command_name ).enable_symmetry_comprehensive().option( None, "--output_pdb", action="store", type="str", default="", help="Output pdb: second model transformed to best match first model", metavar="STR").option( None, "--tolerance", action="store", type="float", default=3., help="match tolerance", metavar="FLOAT").option( None, "--diffraction_index_equivalent", action="store_true", help="Use only if models are diffraction-index equivalent.") ).process(args=args, nargs=2) crystal_symmetry = command_line.symmetry if (crystal_symmetry.unit_cell() is None or crystal_symmetry.space_group_info() is None): for file_name in command_line.args: crystal_symmetry = crystal_symmetry.join_symmetry( other_symmetry=crystal_symmetry_from_any.extract_from( file_name=file_name), force=False) output_pdb = command_line.options.output_pdb if output_pdb: print("Output pdb:", output_pdb) tolerance = command_line.options.tolerance print("Tolerance:", tolerance) if (tolerance <= 0.): raise ValueError("Tolerance must be greater than zero.") print() diffraction_index_equivalent = \ command_line.options.diffraction_index_equivalent if (diffraction_index_equivalent): print("Models are diffraction index equivalent.") print() second_model_as_pdb_inp = None emma_models = [] for file_name in command_line.args: emma_models.append( get_emma_model(file_name=file_name, crystal_symmetry=crystal_symmetry)) if len(emma_models) == 2 and os.path.isfile(file_name): try: second_model_as_pdb_inp = iotbx.pdb.input(file_name=file_name) except Exception as e: pass emma_models[0].show("Reference model") emma_models[1].show("Other model") for model, label in zip(emma_models, ["reference", "other"]): if (model.unit_cell() is None): raise RuntimeError("Unit cell parameters unknown (%s model)." % label) if (model.space_group_info() is None): raise RuntimeError("Space group unknown (%s model)." % label) model_matches = emma.model_matches( model1=emma_models[0], model2=emma_models[1], tolerance=tolerance, models_are_diffraction_index_equivalent=diffraction_index_equivalent) if (model_matches.n_matches() == 0): print("No matches.") print() else: max_n_pairs = None first = True for match in model_matches.refined_matches: if (max_n_pairs is None or len(match.pairs) > max_n_pairs * 0.2): print("." * 79) print() match.show() if first and output_pdb: # 2013-01-25 tt if second_model_as_pdb_inp: match.get_transformed_model2( output_pdb=output_pdb, template_pdb_inp=second_model_as_pdb_inp, f=sys.stdout) else: print("No output model as input model was not PDB") first = False if (max_n_pairs is None): max_n_pairs = len(match.pairs)
def run(args, command_name="iotbx.pdb.as_xray_structure"): command_line = (option_parser( usage=command_name+" [options] pdb_file ...", description="Example: %s pdb1ab1.ent" % command_name) .enable_symmetry_comprehensive() .option(None, "--weak_symmetry", action="store_true", default=False, help="symmetry on command line is weaker than symmetry found in files") .option(None, "--ignore_occ_for_site_symmetry", action="store_true", default=False, help="disables non_unit_occupancy_implies_min_distance_sym_equiv_zero") .option("-v", "--verbose", action="store_true", default=False, help="show scatterers") .option(None, "--pickle", action="store", type="string", help="write all data to FILE ('--pickle .' copies name of input file)", metavar="FILE") .option(None, "--fake_f_obs_and_r_free_flags_d_min", action="store", type="float", help="write F-calc as F-obs, add random R-free flags (MTZ format)", metavar="FLOAT") ).process(args=args) if (len(command_line.args) == 0): command_line.parser.show_help() co = command_line.options d_min = co.fake_f_obs_and_r_free_flags_d_min all_structures = [] for file_name in command_line.args: print "file_name:", file_name sys.stdout.flush() pdb_inp = pdb.input(file_name=file_name) structure = pdb_inp.xray_structure_simple( crystal_symmetry=command_line.symmetry, weak_symmetry=co.weak_symmetry, non_unit_occupancy_implies_min_distance_sym_equiv_zero= not co.ignore_occ_for_site_symmetry) structure.show_summary() if (structure.special_position_indices().size() != 0): structure.show_special_position_shifts( sites_cart_original=pdb_inp.atoms().extract_xyz()) structure.scattering_type_registry().show(show_gaussians=False) if (co.verbose): structure.show_scatterers() if (d_min is not None and d_min > 0): f_obs = abs(structure.structure_factors( d_min=d_min, anomalous_flag=False).f_calc()) f_obs = f_obs.customized_copy(sigmas=flex.sqrt(f_obs.data())) r_free_flags = f_obs.generate_r_free_flags(fraction=0.05, max_free=None) mtz_dataset = f_obs.as_mtz_dataset(column_root_label="F-obs") mtz_dataset.add_miller_array( miller_array=r_free_flags, column_root_label="R-free-flags") mtz_object = mtz_dataset.mtz_object() history = "%s %s" % (command_name, show_string(file_name)) lines = flex.std_string(["Fake F-obs, R-free-flags"]) while (len(history) != 0): lines.append(history[:77]) history = history[77:] mtz_object.add_history(lines=lines) mtz_object.show_summary() mtz_file_name = os.path.basename(file_name).replace(".","_") \ + "_fake.mtz" print "Writing file:", mtz_file_name mtz_object.write(file_name=mtz_file_name) all_structures.append(structure) print pickle_file_name = co.pickle if (pickle_file_name is not None and len(all_structures) > 0): if (pickle_file_name == "."): if (len(command_line.args) > 1): raise Sorry( "Ambiguous name for pickle file (more than one input file).") pickle_file_name = os.path.basename(command_line.args[0]) if (not pickle_file_name.lower().endswith(".pickle")): pickle_file_name += ".pickle" if (len(all_structures) == 1): all_structures = all_structures[0] else: print print "Writing all xray structures to file:", pickle_file_name easy_pickle.dump(pickle_file_name, all_structures) print
def run(args): command_line = (option_parser( usage="iotbx.show_distances [options] studat_file [...]", description="Example: iotbx.show_distances strudat --tag=SOD").option( None, "--cif_data_block_name", action="store", type="string", default=None, help="data block name as it appears in the CIF file").option( None, "--tag", action="store", type="string", help="tag as it appears in the strudat file").option( None, "--distance_cutoff", action="store", type="float", default=5, help="Maximum distance to be considered", metavar="FLOAT" ).option( None, "--min_distance_sym_equiv", action="store", type="float", default=0.5, help="Minimum distance between symmetry mates" " (for special position analysis)", metavar="FLOAT" ).option( None, "--show_cartesian", action="store_true", help="Show Cartesian coordinates (instead of fractional)" ).enable_symmetry_comprehensive().option( None, "--cs", action="store", type="int", help="Compute N terms of the coordination sequences", metavar="N").option( None, "--coseq", action="store", type="string", help="name of file with known coordination sequences", metavar="FILE")).process(args=args) if (len(command_line.args) == 0): command_line.parser.show_help() return co = command_line.options max_shell = co.cs if (co.coseq is not None): coseq_dict = coordination_sequences.get_kriber_coseq_file( file_name=co.coseq) if (max_shell is None): max_shell = 10 else: coseq_dict = None def call_display(xray_structure): display(distance_cutoff=co.distance_cutoff, show_cartesian=co.show_cartesian, max_shell=max_shell, coseq_dict=coseq_dict, xray_structure=xray_structure) cif_data_block_name_use_counter = 0 for file_name in command_line.args: xray_structure = None if (iotbx.pdb.is_pdb_file(file_name=file_name)): xray_structure = iotbx.pdb.input( file_name=file_name).xray_structure_simple( crystal_symmetry=command_line.symmetry, cryst1_substitution_buffer_layer=max( 5, co.distance_cutoff + 1), min_distance_sym_equiv=co.min_distance_sym_equiv, enable_scattering_type_unknown=True) call_display(xray_structure) continue if (file_name.lower().endswith(".cif")): xray_structures = iotbx.cif.reader( file_path=file_name).build_crystal_structures() if (co.cif_data_block_name is not None): xray_structure = xray_structures.get(co.cif_data_block_name) if (xray_structure is None): continue cif_data_block_name_use_counter += 1 xray_structures = [xray_structure] else: xray_structures = xray_structures.values() for xray_structure in xray_structures: call_display(xray_structure) continue if (file_name.endswith(".ins") or file_name.endswith(".res")): xray_structure = xray.structure.from_shelx(filename=file_name, strictly_shelxl=False) call_display(xray_structure) continue if (command_line.symmetry is not None and (command_line.symmetry.unit_cell() is not None or command_line.symmetry.space_group_info() is not None)): raise Sorry( "Command-line symmetry options not supported for strudat files." ) strudat_entries = strudat.read_all_entries(open(file_name)) for entry in strudat_entries.entries: if (co.tag is not None and co.tag != entry.tag): continue print "strudat tag:", entry.tag print xray_structure = entry.as_xray_structure( min_distance_sym_equiv=co.min_distance_sym_equiv) call_display(xray_structure) if (co.cif_data_block_name is not None and cif_data_block_name_use_counter == 0): raise Sorry("cif_data_block_name %s not found in any input files" % show_string(co.cif_data_block_name))
def run(args): command_line = (option_parser( usage="iotbx.show_distances [options] studat_file [...]", description="Example: iotbx.show_distances strudat --tag=SOD") .option(None, "--cif_data_block_name", action="store", type="string", default=None, help="data block name as it appears in the CIF file") .option(None, "--tag", action="store", type="string", help="tag as it appears in the strudat file") .option(None, "--distance_cutoff", action="store", type="float", default=5, help="Maximum distance to be considered", metavar="FLOAT") .option(None, "--min_distance_sym_equiv", action="store", type="float", default=0.5, help="Minimum distance between symmetry mates" " (for special position analysis)", metavar="FLOAT") .option(None, "--show_cartesian", action="store_true", help="Show Cartesian coordinates (instead of fractional)") .enable_symmetry_comprehensive() .option(None, "--cs", action="store", type="int", help="Compute N terms of the coordination sequences", metavar="N") .option(None, "--coseq", action="store", type="string", help="name of file with known coordination sequences", metavar="FILE") ).process(args=args) if (len(command_line.args) == 0): command_line.parser.show_help() return co = command_line.options max_shell = co.cs if (co.coseq is not None): coseq_dict = coordination_sequences.get_kriber_coseq_file( file_name=co.coseq) if (max_shell is None): max_shell = 10 else: coseq_dict = None def call_display(xray_structure): display( distance_cutoff=co.distance_cutoff, show_cartesian=co.show_cartesian, max_shell=max_shell, coseq_dict=coseq_dict, xray_structure=xray_structure) cif_data_block_name_use_counter = 0 for file_name in command_line.args: xray_structure = None if (iotbx.pdb.is_pdb_file(file_name=file_name)): xray_structure = iotbx.pdb.input( file_name=file_name).xray_structure_simple( crystal_symmetry=command_line.symmetry, cryst1_substitution_buffer_layer=max(5, co.distance_cutoff+1), min_distance_sym_equiv=co.min_distance_sym_equiv, enable_scattering_type_unknown=True) call_display(xray_structure) continue if (file_name.lower().endswith(".cif")): xray_structures = iotbx.cif.reader( file_path=file_name).build_crystal_structures() if (co.cif_data_block_name is not None): xray_structure = xray_structures.get(co.cif_data_block_name) if (xray_structure is None): continue cif_data_block_name_use_counter += 1 xray_structures = [xray_structure] else: xray_structures = xray_structures.values() for xray_structure in xray_structures: call_display(xray_structure) continue if ( file_name.endswith(".ins") or file_name.endswith(".res")): xray_structure = xray.structure.from_shelx( filename=file_name, strictly_shelxl=False) call_display(xray_structure) continue if (command_line.symmetry is not None and (command_line.symmetry.unit_cell() is not None or command_line.symmetry.space_group_info() is not None)): raise Sorry( "Command-line symmetry options not supported for strudat files.") strudat_entries = strudat.read_all_entries(open(file_name)) for entry in strudat_entries.entries: if ( co.tag is not None and co.tag != entry.tag): continue print "strudat tag:", entry.tag print xray_structure = entry.as_xray_structure( min_distance_sym_equiv=co.min_distance_sym_equiv) call_display(xray_structure) if ( co.cif_data_block_name is not None and cif_data_block_name_use_counter == 0): raise Sorry( "cif_data_block_name %s not found in any input files" % show_string(co.cif_data_block_name))
def run(args, log=sys.stdout, as_gui_program=False): if (len(args) == 0): parsed = defaults(log=log) parsed.show(prefix=" ", out=log) return command_line = (option_parser().enable_symmetry_comprehensive().option( "-q", "--quiet", action="store_true", default=False, help="suppress output").option("--output_plots", action="store_true", default=False)).process(args=args) parsed = defaults(log=log) processed_args = mmtbx.utils.process_command_line_args( args=command_line.args, cmd_cs=command_line.symmetry, master_params=parsed, log=log, suppress_symmetry_related_errors=True) processed_args.params.show(out=log) params = processed_args.params.extract().density_modification output_plots = command_line.options.output_plots crystal_symmetry = crystal.symmetry( unit_cell=params.input.unit_cell, space_group_info=params.input.space_group) reflection_files = {} for rfn in (params.input.reflection_data.file_name, params.input.experimental_phases.file_name, params.input.map_coefficients.file_name): if os.path.isfile(str(rfn)) and rfn not in reflection_files: reflection_files.setdefault( rfn, iotbx.reflection_file_reader.any_reflection_file( file_name=rfn, ensure_read_access=False)) # TODO is reflection_files a dict ? server = iotbx.reflection_file_utils.reflection_file_server( crystal_symmetry=crystal_symmetry, reflection_files=list(reflection_files.values())) fo = mmtbx.utils.determine_data_and_flags( server, parameters=params.input.reflection_data, extract_r_free_flags=False, log=log).f_obs hl_coeffs = mmtbx.utils.determine_experimental_phases( server, params.input.experimental_phases, log=log, parameter_scope="", working_point_group=None, symmetry_safety_check=True, ignore_all_zeros=True) if params.input.map_coefficients.file_name is not None: map_coeffs = server.get_phases_deg( file_name=params.input.map_coefficients.file_name, labels=params.input.map_coefficients.labels, convert_to_phases_if_necessary=False, original_phase_units=None, parameter_scope="", parameter_name="labels").map_to_asu() else: map_coeffs = None ncs_object = None if params.input.ncs_file_name is not None: ncs_object = ncs.ncs() ncs_object.read_ncs(params.input.ncs_file_name) ncs_object.display_all(log=log) fo = fo.map_to_asu() hl_coeffs = hl_coeffs.map_to_asu() fo = fo.eliminate_sys_absent().average_bijvoet_mates() hl_coeffs = hl_coeffs.eliminate_sys_absent().average_bijvoet_mates() model_map = None model_map_coeffs = None if len(processed_args.pdb_file_names): pdb_inp = mmtbx.utils.pdb_inp_from_multiple_files( pdb_files=processed_args.pdb_file_names, log=log) xs = pdb_inp.xray_structure_simple() fo_, hl_ = fo, hl_coeffs if params.change_basis_to_niggli_cell: change_of_basis_op = xs.change_of_basis_op_to_niggli_cell() xs = xs.change_basis(change_of_basis_op) fo_ = fo_.change_basis(change_of_basis_op).map_to_asu() hl_ = hl_.change_basis(change_of_basis_op).map_to_asu() #fo_, hl_ = fo_.common_sets(hl_) fmodel_refined = mmtbx.utils.fmodel_simple( f_obs=fo_, scattering_table= "wk1995", #XXX pva: 1) neutrons? 2) move up as a parameter. xray_structures=[xs], bulk_solvent_correction=True, anisotropic_scaling=True, r_free_flags=fo_.array(data=flex.bool(fo_.size(), False))) fmodel_refined.update(abcd=hl_) master_phil = mmtbx.maps.map_and_map_coeff_master_params() map_params = master_phil.fetch( iotbx.phil.parse("""\ map_coefficients { map_type = 2mFo-DFc isotropize = True } """)).extract().map_coefficients[0] model_map_coeffs = mmtbx.maps.map_coefficients_from_fmodel( fmodel=fmodel_refined, params=map_params) model_map = model_map_coeffs.fft_map( resolution_factor=params.grid_resolution_factor).real_map_unpadded( ) import time t0 = time.time() dm = density_modify(params, fo, hl_coeffs, ncs_object=ncs_object, map_coeffs=map_coeffs, model_map_coeffs=model_map_coeffs, log=log, as_gui_program=as_gui_program) time_dm = time.time() - t0 print("Time taken for density modification: %.2fs" % time_dm, file=log) # run cns if 0: from cctbx.development import cns_density_modification cns_result = cns_density_modification.run(params, fo, hl_coeffs) print(cns_result.modified_map.all()) print(dm.map.all()) dm_map_coeffs = dm.map_coeffs_in_original_setting from cctbx import maptbx, miller crystal_gridding = maptbx.crystal_gridding( dm_map_coeffs.unit_cell(), space_group_info=dm_map_coeffs.space_group().info(), pre_determined_n_real=cns_result.modified_map.all()) dm_map = miller.fft_map(crystal_gridding, dm_map_coeffs).apply_sigma_scaling() corr = flex.linear_correlation(cns_result.modified_map.as_1d(), dm_map.real_map_unpadded().as_1d()) print("CNS dm/mmtbx dm correlation:") corr.show_summary() if dm.model_map_coeffs is not None: model_map = miller.fft_map( crystal_gridding, dm.miller_array_in_original_setting( dm.model_map_coeffs)).apply_sigma_scaling() corr = flex.linear_correlation( cns_result.modified_map.as_1d(), model_map.real_map_unpadded().as_1d()) print("CNS dm/model correlation:") corr.show_summary() if output_plots: plots_to_make = ( "fom", "skewness", "r1_factor", "r1_factor_fom", "mean_solvent_density", "mean_protein_density", "f000_over_v", "k_flip", "rms_solvent_density", "rms_protein_density", "standard_deviation_local_rms", "mean_delta_phi", "mean_delta_phi_initial", ) from matplotlib.backends.backend_pdf import PdfPages from libtbx import pyplot stats = dm.get_stats() pdf = PdfPages("density_modification.pdf") if len(dm.correlation_coeffs) > 1: if 0: start_coeffs, model_coeffs = dm.map_coeffs_start.common_sets( model_map_coeffs) model_phases = model_coeffs.phases(deg=True).data() exptl_phases = nearest_phase( model_phases, start_coeffs.phases(deg=True).data(), deg=True) corr = flex.linear_correlation(exptl_phases, model_phases) corr.show_summary() fig = pyplot.figure() ax = fig.add_subplot(1, 1, 1) ax.set_title("phases start") ax.set_xlabel("Experimental phases") ax.set_ylabel("Phases from refined model") ax.scatter(exptl_phases, model_phases, marker="x", s=10) pdf.savefig(fig) # dm_coeffs, model_coeffs = dm.map_coeffs.common_sets( model_map_coeffs) model_phases = model_coeffs.phases(deg=True).data() dm_phases = nearest_phase(model_phases, dm_coeffs.phases(deg=True).data(), deg=True) corr = flex.linear_correlation(dm_phases, model_phases) corr.show_summary() fig = pyplot.figure() ax = fig.add_subplot(1, 1, 1) ax.set_title("phases dm") ax.set_xlabel("Phases from density modification") ax.set_ylabel("Phases from refined model") ax.scatter(dm_phases, model_phases, marker="x", s=10) pdf.savefig(fig) # data = dm.correlation_coeffs fig = pyplot.figure() ax = fig.add_subplot(1, 1, 1) ax.set_title("correlation coefficient") ax.plot(list(range(1, dm.i_cycle + 2)), data) pdf.savefig(fig) # data = dm.mean_phase_errors fig = pyplot.figure() ax = fig.add_subplot(1, 1, 1) ax.set_title("Mean effective phase errors") ax.plot(list(range(1, dm.i_cycle + 2)), data) pdf.savefig(fig) for plot in plots_to_make: data = [ getattr(stats.get_cycle_stats(i), plot) for i in range(1, dm.i_cycle + 2) ] fig = pyplot.figure() ax = fig.add_subplot(1, 1, 1) ax.set_title(plot.replace("_", " ")) ax.plot(list(range(1, dm.i_cycle + 2)), data) pdf.savefig(fig) data = [ stats.get_cycle_stats(i).rms_solvent_density / stats.get_cycle_stats(i).rms_protein_density for i in range(1, dm.i_cycle + 2) ] fig = pyplot.figure() ax = fig.add_subplot(1, 1, 1) ax.set_title("RMS solvent/protein density ratio") ax.plot(list(range(1, dm.i_cycle + 2)), data) pdf.savefig(fig) pdf.close() dm_map_coeffs = dm.map_coeffs_in_original_setting dm_hl_coeffs = dm.hl_coeffs_in_original_setting # output map if requested map_params = params.output.map if map_params.file_name is not None: fft_map = dm_map_coeffs.fft_map( resolution_factor=params.grid_resolution_factor) if map_params.scale == "sigma": fft_map.apply_sigma_scaling() else: fft_map.apply_volume_scaling() gridding_first = gridding_last = None title_lines = [] if map_params.format == "xplor": fft_map.as_xplor_map(file_name=map_params.file_name, title_lines=title_lines, gridding_first=gridding_first, gridding_last=gridding_last) else: fft_map.as_ccp4_map(file_name=map_params.file_name, gridding_first=gridding_first, gridding_last=gridding_last, labels=title_lines) # output map coefficients if requested mtz_params = params.output.mtz # Decide if we are going to actually write the mtz if mtz_params.file_name is not None: orig_fom, final_fom = dm.start_and_end_fom() if mtz_params.skip_output_if_worse and final_fom < orig_fom: ok_to_write_mtz = False print( "Not writing out mtz. Final FOM (%7.3f) worse than start (%7.3f)" % (final_fom, orig_fom)) else: # usual ok_to_write_mtz = True else: ok_to_write_mtz = True if mtz_params.file_name is not None and ok_to_write_mtz: label_decorator = iotbx.mtz.ccp4_label_decorator() fo = dm.miller_array_in_original_setting( dm.f_obs_complete).common_set(dm_map_coeffs) mtz_dataset = fo.as_mtz_dataset(column_root_label="F", label_decorator=label_decorator) mtz_dataset.add_miller_array(dm_map_coeffs, column_root_label="FWT", label_decorator=label_decorator) phase_source = dm.miller_array_in_original_setting( dm.phase_source).common_set(dm_map_coeffs) mtz_dataset.add_miller_array( phase_source.array(data=flex.abs(phase_source.data())), column_root_label="FOM", column_types='W', label_decorator=label_decorator) mtz_dataset.add_miller_array( phase_source.array(data=phase_source.phases(deg=True).data()), column_root_label="PHIB", column_types='P', label_decorator=None) if mtz_params.output_hendrickson_lattman_coefficients: mtz_dataset.add_miller_array(dm_hl_coeffs, column_root_label="HL", label_decorator=label_decorator) mtz_dataset.mtz_object().write(mtz_params.file_name) return result(map_file=map_params.file_name, mtz_file=mtz_params.file_name, stats=dm.get_stats())
def run(args, command_name="iotbx.pdb.as_xray_structure"): command_line = (option_parser( usage=command_name + " [options] pdb_file ...", description="Example: %s pdb1ab1.ent" % command_name ).enable_symmetry_comprehensive().option( None, "--weak_symmetry", action="store_true", default=False, help="symmetry on command line is weaker than symmetry found in files" ).option( None, "--ignore_occ_for_site_symmetry", action="store_true", default=False, help="disables non_unit_occupancy_implies_min_distance_sym_equiv_zero" ).option( "-v", "--verbose", action="store_true", default=False, help="show scatterers" ).option( None, "--pickle", action="store", type="string", help="write all data to FILE ('--pickle .' copies name of input file)", metavar="FILE").option( None, "--fake_f_obs_and_r_free_flags_d_min", action="store", type="float", help="write F-calc as F-obs, add random R-free flags (MTZ format)", metavar="FLOAT")).process(args=args) if (len(command_line.args) == 0): command_line.parser.show_help() co = command_line.options d_min = co.fake_f_obs_and_r_free_flags_d_min all_structures = [] for file_name in command_line.args: print "file_name:", file_name sys.stdout.flush() pdb_inp = pdb.input(file_name=file_name) structure = pdb_inp.xray_structure_simple( crystal_symmetry=command_line.symmetry, weak_symmetry=co.weak_symmetry, non_unit_occupancy_implies_min_distance_sym_equiv_zero=not co. ignore_occ_for_site_symmetry) structure.show_summary() if (structure.special_position_indices().size() != 0): structure.show_special_position_shifts( sites_cart_original=pdb_inp.atoms().extract_xyz()) structure.scattering_type_registry().show(show_gaussians=False) if (co.verbose): structure.show_scatterers() if (d_min is not None and d_min > 0): f_obs = abs( structure.structure_factors(d_min=d_min, anomalous_flag=False).f_calc()) f_obs = f_obs.customized_copy(sigmas=flex.sqrt(f_obs.data())) r_free_flags = f_obs.generate_r_free_flags(fraction=0.05, max_free=None) mtz_dataset = f_obs.as_mtz_dataset(column_root_label="F-obs") mtz_dataset.add_miller_array(miller_array=r_free_flags, column_root_label="R-free-flags") mtz_object = mtz_dataset.mtz_object() history = "%s %s" % (command_name, show_string(file_name)) lines = flex.std_string(["Fake F-obs, R-free-flags"]) while (len(history) != 0): lines.append(history[:77]) history = history[77:] mtz_object.add_history(lines=lines) mtz_object.show_summary() mtz_file_name = os.path.basename(file_name).replace(".","_") \ + "_fake.mtz" print "Writing file:", mtz_file_name mtz_object.write(file_name=mtz_file_name) all_structures.append(structure) print pickle_file_name = co.pickle if (pickle_file_name is not None and len(all_structures) > 0): if (pickle_file_name == "."): if (len(command_line.args) > 1): raise Sorry( "Ambiguous name for pickle file (more than one input file)." ) pickle_file_name = os.path.basename(command_line.args[0]) if (not pickle_file_name.lower().endswith(".pickle")): pickle_file_name += ".pickle" if (len(all_structures) == 1): all_structures = all_structures[0] else: print print "Writing all xray structures to file:", pickle_file_name easy_pickle.dump(pickle_file_name, all_structures) print
def run( args, command_name="phenix.reflection_file_converter", simply_return_all_miller_arrays=False): command_line = (option_parser( usage="%s [options] reflection_file ..." % command_name, description="Example: %s w1.sca --mtz ." % command_name) .enable_symmetry_comprehensive() .option(None, "--weak_symmetry", action="store_true", default=False, help="symmetry on command line is weaker than symmetry found in files") .enable_resolutions() .option(None, "--label", action="store", type="string", help="Substring of reflection data label or number", metavar="STRING") .option(None, "--non_anomalous", action="store_true", default=False, help="Averages Bijvoet mates to obtain a non-anomalous array") .option(None, "--r_free_label", action="store", type="string", help="Substring of reflection data label or number", metavar="STRING") .option(None, "--r_free_test_flag_value", action="store", type="int", help="Value in R-free array indicating assignment to free set.", metavar="FLOAT") .option(None, "--generate_r_free_flags", action="store_true", default=False, help="Generates a new array of random R-free flags" " (MTZ and CNS output only).") .option(None, "--use_lattice_symmetry_in_r_free_flag_generation", dest="use_lattice_symmetry_in_r_free_flag_generation", action="store_true", default=True, help="group twin/pseudo symmetry related reflections together" " in r-free set (this is the default).") .option(None, "--no_lattice_symmetry_in_r_free_flag_generation", dest="use_lattice_symmetry_in_r_free_flag_generation", action="store_false", help="opposite of --use-lattice-symmetry-in-r-free-flag-generation") .option(None, "--r_free_flags_fraction", action="store", default=0.10, type="float", help="Target fraction free/work reflections (default: 0.10).", metavar="FLOAT") .option(None, "--r_free_flags_max_free", action="store", default=2000, type="int", help="Maximum number of free reflections (default: 2000).", metavar="INT") .option(None, "--r_free_flags_format", choices=("cns", "ccp4", "shelx"), default="cns", help="Convention for generating R-free flags", metavar="cns|ccp4") .option(None, "--output_r_free_label", action="store", type="string", help="Label for newly generated R-free flags (defaults to R-free-flags)", default="R-free-flags", metavar="STRING") .option(None, "--random_seed", action="store", type="int", help="Seed for random number generator (affects generation of" " R-free flags).", metavar="INT") .option(None, "--change_of_basis", action="store", type="string", help="Change-of-basis operator: h,k,l or x,y,z" " or to_reference_setting, to_primitive_setting, to_niggli_cell," " to_inverse_hand", metavar="STRING") .option(None, "--eliminate_invalid_indices", action="store_true", default=False, help="Remove indices which are invalid given the change of basis desired") .option(None, "--expand_to_p1", action="store_true", default=False, help="Generates all symmetrically equivalent reflections." " The space group symmetry is reset to P1." " May be used in combination with --change_to_space_group to" " lower the symmetry.") .option(None, "--change_to_space_group", action="store", type="string", help="Changes the space group and merges equivalent reflections" " if necessary", metavar="SYMBOL|NUMBER") .option(None, "--write_mtz_amplitudes", action="store_true", default=False, help="Converts intensities to amplitudes before writing MTZ format;" " requires --mtz_root_label") .option(None, "--write_mtz_intensities", action="store_true", default=False, help="Converts amplitudes to intensities before writing MTZ format;" " requires --mtz_root_label") .option(None,"--remove_negatives", action="store_true", default=False, help="Remove negative intensities or amplitudes from the data set" ) .option(None,"--massage_intensities", action="store_true", default=False, help="'Treat' negative intensities to get a positive amplitude." " |Fnew| = sqrt((Io+sqrt(Io**2 +2sigma**2))/2.0). Requires" " intensities as input and the flags --mtz," " --write_mtz_amplitudes and --mtz_root_label.") .option(None, "--scale_max", action="store", type="float", help="Scales data such that the maximum is equal to the given value", metavar="FLOAT") .option(None, "--scale_factor", action="store", type="float", help="Multiplies data with the given factor", metavar="FLOAT") .option(None, "--sca", action="store", type="string", help= "write data to Scalepack FILE ('--sca .' copies name of input file)", metavar="FILE") .option(None, "--mtz", action="store", type="string", help="write data to MTZ FILE ('--mtz .' copies name of input file)", metavar="FILE") .option(None, "--mtz_root_label", action="store", type="string", help="Root label for MTZ file (e.g. Fobs)", metavar="STRING") .option(None, "--cns", action="store", type="string", help="write data to CNS FILE ('--cns .' copies name of input file)", metavar="FILE") .option(None, "--shelx", action="store", type="string", help="write data to SHELX FILE ('--shelx .' copies name of input file)", metavar="FILE") ).process(args=args) co = command_line.options if (co.random_seed is not None): random.seed(co.random_seed) flex.set_random_seed(value=co.random_seed) if ( co.write_mtz_amplitudes and co.write_mtz_intensities): print print "--write_mtz_amplitudes and --write_mtz_intensities" \ " are mutually exclusive." print return None if ( co.write_mtz_amplitudes or co.write_mtz_intensities): if (co.mtz_root_label is None): print print "--write_mtz_amplitudes and --write_mtz_intensities" \ " require --mtz_root_label." print return None if ( co.scale_max is not None and co.scale_factor is not None): print print "--scale_max and --scale_factor are mutually exclusive." print return None if (len(command_line.args) == 0): command_line.parser.show_help() return None all_miller_arrays = reflection_file_reader.collect_arrays( file_names=command_line.args, crystal_symmetry=None, force_symmetry=False, merge_equivalents=False, discard_arrays=False, verbose=1) if (simply_return_all_miller_arrays): return all_miller_arrays if (len(all_miller_arrays) == 0): print print "No reflection data found in input file%s." % ( plural_s(len(command_line.args))[1]) print return None label_table = reflection_file_utils.label_table( miller_arrays=all_miller_arrays) selected_array = label_table.select_array( label=co.label, command_line_switch="--label") if (selected_array is None): return None r_free_flags = None r_free_info = None if (co.r_free_label is not None): r_free_flags = label_table.match_data_label( label=co.r_free_label, command_line_switch="--r_free_label") if (r_free_flags is None): return None r_free_info = str(r_free_flags.info()) if (not r_free_flags.is_bool_array()): test_flag_value = reflection_file_utils.get_r_free_flags_scores( miller_arrays=[r_free_flags], test_flag_value=co.r_free_test_flag_value).test_flag_values[0] if (test_flag_value is None): if (co.r_free_test_flag_value is None): raise Sorry( "Cannot automatically determine r_free_test_flag_value." " Please use --r_free_test_flag_value to specify a value.") else: raise Sorry("Invalid --r_free_test_flag_value.") r_free_flags = r_free_flags.customized_copy( data=(r_free_flags.data() == test_flag_value)) print "Selected data:" print " ", selected_array.info() print " Observation type:", selected_array.observation_type() print if (r_free_info is not None): print "R-free flags:" print " ", r_free_info print processed_array = selected_array.customized_copy( crystal_symmetry=selected_array.join_symmetry( other_symmetry=command_line.symmetry, force=not co.weak_symmetry)).set_observation_type( selected_array.observation_type()) if (r_free_flags is not None): r_free_flags = r_free_flags.customized_copy( crystal_symmetry=processed_array) print "Input crystal symmetry:" crystal.symmetry.show_summary(processed_array, prefix=" ") print if (processed_array.unit_cell() is None): command_line.parser.show_help() print "Unit cell parameters unknown. Please use --symmetry or --unit_cell." print return None if (processed_array.space_group_info() is None): command_line.parser.show_help() print "Space group unknown. Please use --symmetry or --space_group." print return None if (r_free_flags is not None): r_free_flags = r_free_flags.customized_copy( crystal_symmetry=processed_array) if (co.change_of_basis is not None): processed_array, cb_op = processed_array.apply_change_of_basis( change_of_basis=co.change_of_basis, eliminate_invalid_indices=co.eliminate_invalid_indices) if (r_free_flags is not None): r_free_flags = r_free_flags.change_basis(cb_op=cb_op) if (not processed_array.is_unique_set_under_symmetry()): print "Merging symmetry-equivalent values:" merged = processed_array.merge_equivalents() merged.show_summary(prefix=" ") print processed_array = merged.array() del merged processed_array.show_comprehensive_summary(prefix=" ") print if (r_free_flags is not None and not r_free_flags.is_unique_set_under_symmetry()): print "Merging symmetry-equivalent R-free flags:" merged = r_free_flags.merge_equivalents() merged.show_summary(prefix=" ") print r_free_flags = merged.array() del merged r_free_flags.show_comprehensive_summary(prefix=" ") print if (co.expand_to_p1): print "Expanding symmetry and resetting space group to P1:" if (r_free_flags is not None): raise Sorry( "--expand_to_p1 not supported for arrays of R-free flags.") processed_array = processed_array.expand_to_p1() processed_array.show_comprehensive_summary(prefix=" ") print if (co.change_to_space_group is not None): if (r_free_flags is not None): raise Sorry( "--change_to_space_group not supported for arrays of R-free flags.") new_space_group_info = sgtbx.space_group_info( symbol=co.change_to_space_group) print "Change to space group:", new_space_group_info new_crystal_symmetry = crystal.symmetry( unit_cell=processed_array.unit_cell(), space_group_info=new_space_group_info, assert_is_compatible_unit_cell=False) if (not new_crystal_symmetry.unit_cell() .is_similar_to(processed_array.unit_cell())): print " *************" print " W A R N I N G" print " *************" print " Unit cell parameters adapted to new space group symmetry are" print " significantly different from input unit cell parameters:" print " Input unit cell parameters:", \ processed_array.unit_cell() print " Adapted unit cell parameters:", \ new_crystal_symmetry.unit_cell() processed_array = processed_array.customized_copy( crystal_symmetry=new_crystal_symmetry) print if (not processed_array.is_unique_set_under_symmetry()): print " Merging values symmetry-equivalent under new symmetry:" merged = processed_array.merge_equivalents() merged.show_summary(prefix=" ") print processed_array = merged.array() del merged processed_array.show_comprehensive_summary(prefix=" ") print if (processed_array.anomalous_flag() and co.non_anomalous): print "Converting data array from anomalous to non-anomalous." if (not processed_array.is_xray_intensity_array()): processed_array = processed_array.average_bijvoet_mates() else: processed_array = processed_array.f_sq_as_f() processed_array = processed_array.average_bijvoet_mates() processed_array = processed_array.f_as_f_sq() processed_array.set_observation_type_xray_intensity() if (r_free_flags is not None and r_free_flags.anomalous_flag() and co.non_anomalous): print "Converting R-free flags from anomalous to non-anomalous." r_free_flags = r_free_flags.average_bijvoet_mates() d_max = co.low_resolution d_min = co.resolution if (d_max is not None or d_min is not None): if (d_max is not None): print "Applying low resolution cutoff: d_max=%.6g" % d_max if (d_min is not None): print "Applying high resolution cutoff: d_min=%.6g" % d_min processed_array = processed_array.resolution_filter( d_max=d_max, d_min=d_min) print "Number of reflections:", processed_array.indices().size() print if (co.scale_max is not None): print "Scaling data such that the maximum value is: %.6g" % co.scale_max processed_array = processed_array.apply_scaling(target_max=co.scale_max) print if (co.scale_factor is not None): print "Multiplying data with the factor: %.6g" % co.scale_factor processed_array = processed_array.apply_scaling(factor=co.scale_factor) print if (([co.remove_negatives, co.massage_intensities]).count(True) == 2): raise Sorry( "It is not possible to use --remove_negatives and" " --massage_intensities at the same time.") if (co.remove_negatives): if processed_array.is_real_array(): print "Removing negatives items" processed_array = processed_array.select( processed_array.data() > 0) if processed_array.sigmas() is not None: processed_array = processed_array.select( processed_array.sigmas() > 0) else: raise Sorry("--remove_negatives not applicable to complex data arrays.") if (co.massage_intensities): if processed_array.is_real_array(): if processed_array.is_xray_intensity_array(): if (co.mtz is not None): if (co.write_mtz_amplitudes): print "The supplied intensities will be used to estimate" print " amplitudes in the following way: " print " Fobs = Sqrt[ (Iobs + Sqrt(Iobs**2 + 2sigmaIobs**2))/2 ]" print " Sigmas are estimated in a similar manner." print processed_array = processed_array.enforce_positive_amplitudes() else: raise Sorry( "--write_mtz_amplitudes has to be specified when using" " --massage_intensities") else: raise Sorry("--mtz has to be used when using --massage_intensities") else: raise Sorry( "Intensities must be supplied when using the option" " --massage_intensities") else: raise Sorry( "--massage_intensities not applicable to complex data arrays.") if (not co.generate_r_free_flags): if (r_free_flags is None): r_free_info = [] else: if (r_free_flags.anomalous_flag() != processed_array.anomalous_flag()): if (processed_array.anomalous_flag()): is_not = ("", " not") else: is_not = (" not", "") raise Sorry( "The data array is%s anomalous but the R-free array is%s.\n" % is_not + " Please try --non_anomalous.") r_free_info = ["R-free flags source: " + r_free_info] if (not r_free_flags.indices().all_eq(processed_array.indices())): processed_array = processed_array.map_to_asu() r_free_flags = r_free_flags.map_to_asu().common_set(processed_array) n_missing_r_free_flags = processed_array.indices().size() \ - r_free_flags.indices().size() if (n_missing_r_free_flags != 0): raise Sorry("R-free flags not compatible with data array:" " missing flag for %d reflections selected for output." % n_missing_r_free_flags) else: if (r_free_flags is not None): raise Sorry( "--r_free_label and --generate_r_free_flags are mutually exclusive.") print "Generating a new array of R-free flags:" r_free_flags = processed_array.generate_r_free_flags( fraction=co.r_free_flags_fraction, max_free=co.r_free_flags_max_free, use_lattice_symmetry=co.use_lattice_symmetry_in_r_free_flag_generation, format=co.r_free_flags_format) test_flag_value = True if (co.r_free_flags_format == "ccp4") : test_flag_value = 0 elif (co.r_free_flags_format == "shelx") : test_flag_value = -1 r_free_as_bool = r_free_flags.customized_copy( data=r_free_flags.data()==test_flag_value) r_free_info = [ "R-free flags generated by %s:" % command_name] r_free_info.append(" "+date_and_time()) r_free_info.append(" fraction: %.6g" % co.r_free_flags_fraction) r_free_info.append(" max_free: %s" % str(co.r_free_flags_max_free)) r_free_info.append(" size of work set: %d" % r_free_as_bool.data().count(False)) r_free_info.append(" size of free set: %d" % r_free_as_bool.data().count(True)) r_free_info_str = StringIO() r_free_as_bool.show_r_free_flags_info(prefix=" ", out=r_free_info_str) if (co.r_free_flags_format == "ccp4") : r_free_info.append(" convention: CCP4 (test=0, work=1-%d)" % flex.max(r_free_flags.data())) elif (co.r_free_flags_format == "shelx") : r_free_info.append(" convention: SHELXL (test=-1, work=1)") else : r_free_info.append(" convention: CNS/X-PLOR (test=1, work=0)") print "\n".join(r_free_info[2:4]) print r_free_info[-1] print r_free_info_str.getvalue() print n_output_files = 0 if (co.sca is not None): if (co.generate_r_free_flags): raise Sorry("Cannot write R-free flags to Scalepack file.") file_name = reflection_file_utils.construct_output_file_name( input_file_names=[selected_array.info().source], user_file_name=co.sca, file_type_label="Scalepack", file_extension="sca") print "Writing Scalepack file:", file_name iotbx.scalepack.merge.write( file_name=file_name, miller_array=processed_array) n_output_files += 1 print if (co.mtz is not None): file_name = reflection_file_utils.construct_output_file_name( input_file_names=[selected_array.info().source], user_file_name=co.mtz, file_type_label="MTZ", file_extension="mtz") print "Writing MTZ file:", file_name mtz_history_buffer = flex.std_string() mtz_history_buffer.append(date_and_time()) mtz_history_buffer.append("> program: %s" % command_name) mtz_history_buffer.append("> input file name: %s" % os.path.basename(selected_array.info().source)) mtz_history_buffer.append("> input directory: %s" % os.path.dirname(os.path.abspath(selected_array.info().source))) mtz_history_buffer.append("> input labels: %s" % selected_array.info().label_string()) mtz_output_array = processed_array if (co.write_mtz_amplitudes): if (not mtz_output_array.is_xray_amplitude_array()): print " Converting intensities to amplitudes." mtz_output_array = mtz_output_array.f_sq_as_f() mtz_history_buffer.append("> Intensities converted to amplitudes.") elif (co.write_mtz_intensities): if (not mtz_output_array.is_xray_intensity_array()): print " Converting amplitudes to intensities." mtz_output_array = mtz_output_array.f_as_f_sq() mtz_history_buffer.append("> Amplitudes converted to intensities.") column_root_label = co.mtz_root_label if (column_root_label is None): # XXX 2013-03-29: preserve original root label by default # XXX 2014-12-16: skip trailing "(+)" in root_label if anomalous column_root_label = selected_array.info().labels[0] column_root_label=remove_anomalous_suffix_if_necessary( miller_array=selected_array, column_root_label=column_root_label) mtz_dataset = mtz_output_array.as_mtz_dataset( column_root_label=column_root_label) del mtz_output_array if (r_free_flags is not None): mtz_dataset.add_miller_array( miller_array=r_free_flags, column_root_label=co.output_r_free_label) for line in r_free_info: mtz_history_buffer.append("> " + line) mtz_history_buffer.append("> output file name: %s" % os.path.basename(file_name)) mtz_history_buffer.append("> output directory: %s" % os.path.dirname(os.path.abspath(file_name))) mtz_object = mtz_dataset.mtz_object() mtz_object.add_history(mtz_history_buffer) mtz_object.write(file_name=file_name) n_output_files += 1 print if (co.cns is not None): file_name = reflection_file_utils.construct_output_file_name( input_file_names=[selected_array.info().source], user_file_name=co.cns, file_type_label="CNS", file_extension="cns") print "Writing CNS file:", file_name processed_array.export_as_cns_hkl( file_object=open(file_name, "w"), file_name=file_name, info=["source of data: "+str(selected_array.info())] + r_free_info, r_free_flags=r_free_flags) n_output_files += 1 print if (co.shelx is not None): if (co.generate_r_free_flags): raise Sorry("Cannot write R-free flags to SHELX file.") file_name = reflection_file_utils.construct_output_file_name( input_file_names=[selected_array.info().source], user_file_name=co.shelx, file_type_label="SHELX", file_extension="shelx") print "Writing SHELX file:", file_name processed_array.as_amplitude_array().export_as_shelx_hklf( open(file_name, "w")) n_output_files += 1 print if (n_output_files == 0): command_line.parser.show_help() print "Please specify at least one output file format,", print "e.g. --mtz, --sca, etc." print return None return processed_array
def run(args, command_name="phenix.reflection_statistics", additional_miller_arrays=[]): print "Command line arguments:", for arg in args: print arg, print print command_line = ( option_parser( usage=command_name + " [options] reflection_file [...]", description="Example: %s data1.mtz data2.sca" % command_name, ) .enable_symmetry_comprehensive() .option( None, "--weak_symmetry", action="store_true", default=False, help="symmetry on command line is weaker than symmetry found in files", ) .option(None, "--quick", action="store_true", help="Do not compute statistics between pairs of data arrays") .enable_resolutions() .option( None, "--bins", action="store", type="int", dest="n_bins", default=10, help="Number of bins", metavar="INT" ) .option( None, "--bins_twinning_test", action="store", type="int", dest="n_bins_twinning_test", default=None, help="Number of bins for twinning test", metavar="INT", ) .option( None, "--bins_second_moments", action="store", type="int", dest="n_bins_second_moments", default=None, help="Number of bins for second moments of intensities", metavar="INT", ) .option( None, "--lattice_symmetry_max_delta", action="store", type="float", default=3.0, help="angular tolerance in degrees used in the determination" " of the lattice symmetry", ) .option( None, "--completeness_as_non_anomalous_or_anomalous", action="store_true", help="analyze completeness as is, without conversion to non-anomalous", ) ).process(args=args) if len(command_line.args) == 0 and len(additional_miller_arrays) == 0: command_line.parser.show_help() return active_miller_arrays = [] completeness_as_non_anomalous = not command_line.options.completeness_as_non_anomalous_or_anomalous n_f_sq_as_f = 0 for file_name in command_line.args: reflection_file = reflection_file_reader.any_reflection_file(file_name=file_name) miller_arrays = None if reflection_file.file_type() is not None: try: miller_arrays = reflection_file.as_miller_arrays( crystal_symmetry=command_line.symmetry, force_symmetry=not command_line.options.weak_symmetry, merge_equivalents=False, ) except Sorry, KeyboardInterrupt: raise except Exception: pass
def run(args): def vdw_radii_callback(option, opt_str, value, parser): # create a dict from space separated string of element types and radii radii = {} items = value.split() assert len(items) % 2 == 0 for i in range(int(len(items) / 2)): radii.setdefault(items[i * 2], float(items[i * 2 + 1])) setattr(parser.values, option.dest, radii) command_line = (option_parser( usage="smtbx.masks structure reflections [options]" ).enable_symmetry_comprehensive().option( None, "--solvent_radius", action="store", type="float", default=1.3).option( None, "--shrink_truncation_radius", action="store", type="float", default=1.3).option(None, "--debug", action="store_true").option( None, "--verbose", action="store_true").option( None, "--resolution_factor", action="store", type="float", default=1 / 4).option( None, "--grid_step", action="store", type="float").option( None, "--d_min", action="store", type="float").option( None, "--two_theta_max", action="store", type="float").option( None, "--cb_op", action="store", type="string").option( None, "--vdw_radii", action="callback", callback=vdw_radii_callback, type="string", nargs=1).option( None, "--use_space_group_symmetry", action="store_true")).process( args=args) structure_file = command_line.args[0] ext = os.path.splitext(structure_file)[-1].lower() if ext in ('.res', '.ins'): xs = xray.structure.from_shelx(filename=structure_file) elif ext == '.cif': xs = xray.structure.from_cif(filename=structure_file) else: print "%s: unsupported structure file format {shelx|cif}" % ext return reflections_server = reflection_file_utils.reflection_file_server( crystal_symmetry=xs.crystal_symmetry(), reflection_files=[ reflection_file_reader.any_reflection_file(command_line.args[1]) ]) fo_sq = reflections_server.get_miller_arrays(None)[0] if command_line.options.cb_op is not None: cb_op = sgtbx.change_of_basis_op( sgtbx.rt_mx(command_line.options.cb_op)) fo_sq = fo_sq.change_basis(cb_op).customized_copy(crystal_symmetry=xs) print "structure file: %s" % command_line.args[0] print "reflection file: %s" % command_line.args[1] if command_line.options.debug: print "debug: %s" % command_line.options.debug print xs.show_summary() print d_min = command_line.options.d_min two_theta_max = command_line.options.two_theta_max assert [d_min, two_theta_max].count(None) > 0 if two_theta_max is not None: d_min = uctbx.two_theta_as_d(two_theta_max, wavelength=0.71073, deg=True) exercise_masks( xs, fo_sq, solvent_radius=command_line.options.solvent_radius, shrink_truncation_radius=command_line.options.shrink_truncation_radius, resolution_factor=command_line.options.resolution_factor, grid_step=command_line.options.grid_step, resolution_cutoff=d_min, atom_radii_table=command_line.options.vdw_radii, use_space_group_symmetry=command_line.options.use_space_group_symmetry, debug=command_line.options.debug, verbose=command_line.options.verbose) print "OK"
def run(args, command_name="iotbx.pdb.superpose_centers_of_mass"): if (len(args) == 0): args = ["--help"] command_line = (option_parser( usage="%s [options] [reference_file] [other_file] [parameter_file]" % command_name).enable_show_defaults().enable_symmetry_comprehensive() ).process(args=args) if (command_line.expert_level is not None): master_params.show(expert_level=command_line.expert_level, attributes_level=command_line.attributes_level) sys.exit(0) # # Loop over command-line arguments. # parameter_interpreter = master_params.command_line_argument_interpreter() parsed_params = [] pdb_file_names = [] command_line_params = [] for arg in command_line.args: arg_is_processed = False if (os.path.isfile(arg)): params = None try: params = iotbx.phil.parse(file_name=arg) except KeyboardInterrupt: raise except RuntimeError: pass else: if (len(params.objects) == 0): params = None if (params is not None): parsed_params.append(params) arg_is_processed = True elif (pdb.is_pdb_file(file_name=arg)): pdb_file_names.append(arg) arg_is_processed = True if (not arg_is_processed): try: params = parameter_interpreter.process(arg=arg) except Sorry as e: if (not os.path.isfile(arg)): raise raise Sorry("Unknown file format: %s" % arg) else: command_line_params.append(params) # # Consolidation of inputs, resulting in effective phil_params. # phil_params = master_params.fetch(sources=parsed_params + command_line_params) params = phil_params.extract() for param_group in [params.reference, params.other, params.output]: if (param_group.file_name is None and len(pdb_file_names) > 0): param_group.file_name = pdb_file_names[0] pdb_file_names = pdb_file_names[1:] if (len(pdb_file_names) > 0): raise Sorry("Too many PDB file names: %s" % ", ".join([show_string(s) for s in pdb_file_names])) if (params.output.file_name is None and params.other.file_name is not None): name = os.path.basename(params.other.file_name) if (name.lower().endswith(".pdb")): name = name[:-4] name += "_superposed.pdb" params.output.file_name = name if (params.crystal_symmetry.unit_cell is None): params.crystal_symmetry.unit_cell = \ command_line.symmetry.unit_cell() if (params.crystal_symmetry.space_group is None): params.crystal_symmetry.space_group = \ command_line.symmetry.space_group_info() phil_params = master_params.format(python_object=params) phil_params.show() print("#phil __OFF__") # # Final checks. # if (params.reference.file_name is None): raise Sorry("Required file name is missing: reference.file_name") if (params.other.file_name is None): raise Sorry("Required file name is missing: other.file_name") if (params.output.file_name is None): raise Sorry("Required file name is missing: output.file_name") # # Processing of input PDB files. # pdb_objs = [] sites_carts = [] centers_of_mass = [] for param_group in [params.reference, params.other]: pdb_obj = pdb.hierarchy.input(file_name=param_group.file_name) pdb_obj.atoms = pdb_obj.hierarchy.atoms() pdb_objs.append(pdb_obj) sites_carts.append(pdb_obj.atoms.extract_xyz()) sites_sel = sites_carts[-1] if (param_group.atom_selection is not None): sel = pdb_obj.hierarchy.atom_selection_cache().selection( param_group.atom_selection) sites_sel = sites_sel.select(sel) print("Number of selected sites:", sites_sel.size()) centers_of_mass.append(sites_sel.mean()) # # Consolidation of crystal symmetries. # crystal_symmetry = command_line.symmetry for pdb_obj in pdb_objs: crystal_symmetry_from_pdb = pdb_obj.input.crystal_symmetry() if (crystal_symmetry_from_pdb is not None): crystal_symmetry = crystal_symmetry.join_symmetry( other_symmetry=crystal_symmetry_from_pdb, force=False) if (crystal_symmetry.unit_cell() is None): raise Sorry( "Unknown unit cell parameters." "\n Use --unit_cell or --symmetry to supply unit cell parameters." ) if (crystal_symmetry.space_group_info() is None): raise Sorry( "Unknown space group symmetry." "\n Use --space_group or --symmetry to supply symmetry information." ) crystal_symmetry.show_summary() # # Obtain transformation to reference setting. # To ensure all allowed origin shifts are parallel to the basis vectors. # cb_op_to_ref = crystal_symmetry.change_of_basis_op_to_reference_setting() sym_ref = crystal_symmetry.change_basis(cb_op=cb_op_to_ref) # # Obtain allowed origin shifts. # This is the most convenient interface. Essentially we just need # sgtbx.structure_seminvariants. # match_symmetry = euclidean_model_matching.euclidean_match_symmetry( space_group_info=sym_ref.space_group_info(), use_k2l=False, use_l2n=False) # # Compute the symmetry operation which maps the center of mass of # "other" closest to the center of mass of "reference." # centers_frac = [ sym_ref.unit_cell().fractionalize(cb_op_to_ref.c() * center_cart) for center_cart in centers_of_mass ] dist_info = sgtbx.min_sym_equiv_distance_info( sym_ref.special_position_settings().sym_equiv_sites(centers_frac[0]), centers_frac[1], match_symmetry.continuous_shift_flags) sym_op = cb_op_to_ref.inverse().apply(dist_info.sym_op()) print("Rotation in fractional space:", sym_op.r().as_xyz()) sym_op = sym_op.as_rational().as_float() \ + matrix.col(dist_info.continuous_shifts()) print("Translation in fractional space: (%s)" % (", ".join(["%.6g" % t for t in sym_op.t]))) # centers_frac = [ sym_ref.unit_cell().fractionalize(center_cart) for center_cart in centers_of_mass ] sym_center_frac = sym_op * centers_frac[1] sym_center_cart = crystal_symmetry.unit_cell().orthogonalize( sym_center_frac) print("Centers of mass:") print(" Reference: (%s)" % ", ".join(["%8.2f" % v for v in centers_of_mass[0]])) print(" Original other: (%s)" % ", ".join(["%8.2f" % v for v in centers_of_mass[1]])) print(" Symmetry related other: (%s)" % ", ".join(["%8.2f" % v for v in sym_center_cart])) print("Cartesian distance between centers of mass: %.4f" % dist_info.dist()) # # Internal consistency check (in input setting). # assert approx_equal( crystal_symmetry.unit_cell().distance(centers_frac[0], sym_center_frac), dist_info.dist()) # # Transform atomic coordinates of "other." # sites_frac_other = crystal_symmetry.unit_cell().fractionalize( sites_cart=sites_carts[1]) sites_frac_other_superposed = sym_op * sites_frac_other sites_cart_other_superposed = crystal_symmetry.unit_cell().orthogonalize( sites_frac=sites_frac_other_superposed) # # Replace original coordinates with transformed coordinates. # pdb_objs[1].atoms.set_xyz(new_xyz=sites_cart_other_superposed) # # Write (selected) transformed coordinates. # pdb_hierarchy = pdb_objs[1].hierarchy if (params.output.atom_selection is not None): sel = pdb_hierarchy.atom_selection_cache().selection( params.output.atom_selection) pdb_hierarchy = pdb_hierarchy.select(atom_selection=sel) pdb_hierarchy.write_pdb_file(file_name=params.output.file_name, crystal_symmetry=crystal_symmetry, append_end=True, atoms_reset_serial_first_value=1)
def run(args, command_name="phenix.reflection_statistics", additional_miller_arrays=[]): print "Command line arguments:", for arg in args: print arg, print print command_line = (option_parser( usage=command_name + " [options] reflection_file [...]", description="Example: %s data1.mtz data2.sca" % command_name ).enable_symmetry_comprehensive().option( None, "--weak_symmetry", action="store_true", default=False, help="symmetry on command line is weaker than symmetry found in files" ).option( None, "--quick", action="store_true", help="Do not compute statistics between pairs of data arrays" ).enable_resolutions().option( None, "--bins", action="store", type="int", dest="n_bins", default=10, help="Number of bins", metavar="INT" ).option( None, "--bins_twinning_test", action="store", type="int", dest="n_bins_twinning_test", default=None, help="Number of bins for twinning test", metavar="INT" ).option( None, "--bins_second_moments", action="store", type="int", dest="n_bins_second_moments", default=None, help="Number of bins for second moments of intensities", metavar="INT" ).option( None, "--lattice_symmetry_max_delta", action="store", type="float", default=3., help="angular tolerance in degrees used in the determination" " of the lattice symmetry" ).option( None, "--completeness_as_non_anomalous_or_anomalous", action="store_true", help="analyze completeness as is, without conversion to non-anomalous") ).process(args=args) if (len(command_line.args) == 0 and len(additional_miller_arrays) == 0): command_line.parser.show_help() return active_miller_arrays = [] completeness_as_non_anomalous = ( not command_line.options.completeness_as_non_anomalous_or_anomalous) n_f_sq_as_f = 0 for file_name in command_line.args: reflection_file = reflection_file_reader.any_reflection_file( file_name=file_name) miller_arrays = None if (reflection_file.file_type() is not None): try: miller_arrays = reflection_file.as_miller_arrays( crystal_symmetry=command_line.symmetry, force_symmetry=not command_line.options.weak_symmetry, merge_equivalents=False) except Sorry, KeyboardInterrupt: raise except Exception: pass
def run(args, command_name=libtbx.env.dispatcher_name): if (len(args) == 0): args = ["--help"] command_line = (option_parser( usage='%s pdb_file "atom_selection" [...]' % command_name).option( None, "--write_pdb_file", action="store", type="string", default=None, help="write selected atoms to new PDB file", metavar="FILE" ).option( None, "--cryst1_replacement_buffer_layer", action="store", type="float", default=None, help="replace CRYST1 with pseudo unit cell covering the selected" " atoms plus a surrounding buffer layer", metavar="WIDTH")).process(args=args, min_nargs=2) co = command_line.options 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=command_line.args[0], log=sys.stdout) print acp = processed_pdb_file.all_chain_proxies hierarchy = acp.pdb_hierarchy asc = hierarchy.atom_selection_cache() sel = asc.selection(string="chain 'A' and resid 1 through 8 and icode ' '") h1 = hierarchy.select(sel) # keep original hierarchy too print h1.as_pdb_string() selection_cache = acp.pdb_hierarchy.atom_selection_cache() atoms = acp.pdb_atoms all_bsel = flex.bool(atoms.size(), False) for selection_string in command_line.args[1:]: 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(args): command_line = (option_parser( usage="mmtbx.p-plotter [options]", description="produces a gnuplot plot") .option(None, "--fobs", action="store", type="float", help="F obs", metavar="FLOAT") .option( None, "--sigma", action="store", type="float", help="sigma Fobs", metavar="FLOAT") .option(None, "--fcalc", action="store", type="float", help="F calc", metavar="FLOAT") .option(None, "--alpha", action="store", type="float", help="alpha", metavar="FLOAT") .option(None, "--beta", action="store", type="float", help="beta") .option(None, "--epsilon", action="store", type="float", help="epsilon") .option(None, "--centric", action="store_true", default=False, help="centricity flag") .option(None, "--limit", action="store", type="float", default=10, help="plotting limit") .option(None, "--steps", action="store", type="int", default=1000, help="number of steps") ).process(args=args) if command_line.options.fobs is None: raise Sorry("please provide fobs") if command_line.options.fcalc is None: raise Sorry("please provide fcalc") if command_line.options.epsilon is None: raise Sorry("please provide epsilon") if command_line.options.alpha is None: raise Sorry("please provide alpha") if command_line.options.beta is None: raise Sorry("please provide beta") #print dir(command_line.options) plottery = plotit( command_line.options.fobs, command_line.options.sigma, command_line.options.fcalc, command_line.options.alpha, command_line.options.beta, command_line.options.epsilon, command_line.options.centric, sys.stdout, command_line.options.limit, command_line.options.steps)
def run(args, command_name="phenix.explore_metric_symmetry"): command_line = ( option_parser( usage=command_name+" [options]", description="""\ Explore Metric Symmetry. A list of possible unit cells and spacegroups is given for the given specified unit cell and spacegroup combination. If a second unit cell is given, linear combinations of the basis vector of one unit cell are sought that match the other.""") .enable_symmetry_comprehensive() .option(None, "--max_delta", action = "store", type="float", default=5.0, dest = "max_delta", help = "Maximum delta/obliquity used in determining the lattice symmetry, using a modified Le-Page algorithm. Default is 5.0 degrees", metavar="FLOAT") .option(None, "--start_from_p1", action="store_true", dest="niggli", default=False, help="Reduce to Niggli cell and forget the input spacegroup before higher metric symmetry is sought.") .option(None, "--graph", action="store", default=None, help="A graphical representation of the graph will be written out." " Requires Graphviz to be installed and on PATH.") .option(None, "--centring_type", action="store", type="str", help="Centring type, choose from P,A,B,C,I,R,F") .option(None, "--other_unit_cell", action="store", type="str", help="Other unit cell, for unit cell comparison", metavar="10,20,30,90,103.7,90") .option(None, "--other_space_group", action="store", type="str", help="space group for other_unit_cell, for unit cell comparison") .option(None, "--other_centring_type", action="store", type="str", help="Centring type, choose from P,A,B,C,I,R,F") .option(None, "--no_point_group_graph", action="store_true", dest="pg_graph", default=False, help="Do not carry out the construction of a point group graph." ) .option(None, "--relative_length_tolerance", action="store", type="float", help="Tolerance for unit cell lengths to be considered equal-ish.", default=0.10, metavar="FLOAT", dest="rel_length_tol") .option(None, "--absolute_angle_tolerance", action="store", dest="abs_angle_tol", type="float", default=10.0, metavar="FLOAT", help="Angular tolerance in unit cell comparison") .option(None, "--max_order", action="store", type="int", default=1, metavar="INT", help="Maximum volume change for target cell" ) ).process(args=args) log = multi_out() log.register(label="stdout", file_object=sys.stdout) allowed_centring_types={"P":"Primitive", "A":"A centered", "B":"B centered", "C":"C centered", "I":"Body centered", "R":"Rombohedral", "F":"Face centered"} if command_line.options.centring_type is not None: if not allowed_centring_types.has_key( command_line.options.centring_type ): print >> log, "Sorry, the centring type %s is not known."%(command_line.options.centring_type) print >> log, "Choose from P,A,B,C,I,R,F " return xs = None other_xs = None if len(args)==0: command_line.parser.show_help() return if ( command_line.symmetry.unit_cell() == None ): print >> log print >> log, "Sorry: Unit cell not specified." print >> log command_line.parser.show_help() return if command_line.options.centring_type is None: if ( command_line.symmetry.space_group_info() == None ): print>> log print>> log, "Sorry: centring type or space group not specified." print>> log command_line.parser.show_help() return if command_line.symmetry.space_group_info() is not None: if not ( command_line.symmetry.space_group().is_chiral() ): print >> log, "Sorry, Non chiral space groups not yet supported." return if command_line.options.centring_type is not None: xs = crystal.symmetry( unit_cell=command_line.symmetry.unit_cell(), space_group_symbol="Hall: %s 1" %( command_line.options.centring_type ) ) command_line.symmetry = xs if command_line.options.niggli: print >> log, "*Unit cell will be niggli reduced and P1 will be assumed*" uc = command_line.symmetry.change_basis( command_line.symmetry.change_of_basis_op_to_niggli_cell() ).unit_cell() command_line.symmetry = crystal.symmetry( uc, "P 1" ) xs = command_line.symmetry ############################################################################ # ABOVE IS JUST INPUT PARSING, NOW THE ACTUAL STUFF HAPPENS ############################################################################ if not command_line.options.pg_graph: ############################## # get a point group graph # ############################## pg_object = do_pointgroup_tricks( xs.unit_cell(), xs.space_group(), command_line.options.max_delta, log ) ################################################ # make a graphical representation if desired # ################################################ if command_line.options.graph is not None: make_graph_of_graph(pg_object, command_line.options.graph, log) ######################################### # Check if other cell has been defined # ######################################### if command_line.options.other_unit_cell is not None: print >> log, "A second unit cell has been specified. " other_xs = None if command_line.options.other_space_group is None: if command_line.options.other_centring_type is None: raise Sorry("No space group or centring type for other cell specified.") else: other_xs = crystal.symmetry( command_line.options.other_unit_cell, space_group_symbol="Hall: %s 1" %( command_line.options.other_centring_type ) ) else: other_xs = crystal.symmetry( command_line.options.other_unit_cell, space_group_symbol=command_line.options.other_space_group ) # get the graph is desired if not command_line.options.pg_graph: other_pg_object = do_pointgroup_tricks( other_xs.unit_cell(), other_xs.space_group(), command_line.options.max_delta, log ) # do the unit cell comparison print >> log print >> log print >> log, "Unit cell comparison" print >> log, "--------------------" print >> log print >> log, "The unit cells will be compared. The smallest niggli cell," print >> log, "will be used as a (semi-flexible) lego-block to see if it" print >> log, "can construct the larger Niggli cell." print >> log print >> log order = command_line.options.max_order if order==1: sl_object = slt.compare_lattice(xs_a=xs, xs_b=other_xs, max_delta=command_line.options.max_delta, out=log, relative_length_tolerance=command_line.options.rel_length_tol, absolute_angle_tolerance=command_line.options.abs_angle_tol) else: tmp_a = xs.change_basis( xs.change_of_basis_op_to_niggli_cell() ) tmp_b = other_xs.change_basis( other_xs.change_of_basis_op_to_niggli_cell() ) modified_xs = None order = command_line.options.max_order lego_block = None if ( tmp_a.unit_cell().volume() > tmp_b.unit_cell().volume() ): modified_xs = slt.make_list_of_target_xs_up_to_order( xs, order ) lego_block = other_xs else: modified_xs = slt.make_list_of_target_xs_up_to_order( other_xs, order ) lego_block = xs print >> log print >> log, "Volume change of largest niggli cell requested via keyword --max_order" print >> log print >> log, "Input crystal symmetry is tranformed to niggli setting using the operator:" print >> log, modified_xs.basic_to_niggli_cb_op.as_xyz() print >> log print >> log, "Comparisons for various sublattices of the target cell are listed" print >> log for tmp_xs,cb_op,mat in zip(modified_xs.xs_list, modified_xs.extra_cb_op, modified_xs.matrices ): mat=mat.as_list_of_lists() print >> log, "===================================================================" print >> log, "Niggli cell is expanded using matrix:" print >> log print >> log, " /%4i %4i %4i \ "%(mat[0][0],mat[0][1],mat[0][2]) print >> log, " M = |%4i %4i %4i | "%(mat[1][0],mat[1][1],mat[1][2]) print >> log, " \%4i %4i %4i / "%(mat[2][0],mat[2][1],mat[2][2]) print >> log print >> log, "Change of basis operator to reference setting:" print >> log, " ", cb_op.as_xyz() print >> log, "resulting crystal symmetry:" tmp_xs.show_summary(f=log,prefix=" ") print >> log print >> log sl_object = slt.compare_lattice(xs_a=tmp_xs, xs_b=lego_block, max_delta=command_line.options.max_delta, out=log, relative_length_tolerance=command_line.options.rel_length_tol, absolute_angle_tolerance=command_line.options.abs_angle_tol)
def run(args, command_name="phenix.reflection_statistics", additional_miller_arrays=[]): print("Command line arguments:", end=' ') for arg in args: print(arg, end=' ') print() print() command_line = (option_parser( usage=command_name + " [options] reflection_file [...]", description="Example: %s data1.mtz data2.sca" % command_name ).enable_symmetry_comprehensive().option( None, "--weak_symmetry", action="store_true", default=False, help="symmetry on command line is weaker than symmetry found in files" ).option( None, "--quick", action="store_true", help="Do not compute statistics between pairs of data arrays" ).enable_resolutions().option( None, "--bins", action="store", type="int", dest="n_bins", default=10, help="Number of bins", metavar="INT" ).option( None, "--bins_twinning_test", action="store", type="int", dest="n_bins_twinning_test", default=None, help="Number of bins for twinning test", metavar="INT" ).option( None, "--bins_second_moments", action="store", type="int", dest="n_bins_second_moments", default=None, help="Number of bins for second moments of intensities", metavar="INT" ).option( None, "--lattice_symmetry_max_delta", action="store", type="float", default=3., help="angular tolerance in degrees used in the determination" " of the lattice symmetry" ).option( None, "--completeness_as_non_anomalous_or_anomalous", action="store_true", help="analyze completeness as is, without conversion to non-anomalous") ).process(args=args) if (len(command_line.args) == 0 and len(additional_miller_arrays) == 0): command_line.parser.show_help() return active_miller_arrays = [] completeness_as_non_anomalous = ( not command_line.options.completeness_as_non_anomalous_or_anomalous) n_f_sq_as_f = 0 for file_name in command_line.args: reflection_file = reflection_file_reader.any_reflection_file( file_name=file_name) miller_arrays = None if (reflection_file.file_type() is not None): try: miller_arrays = reflection_file.as_miller_arrays( crystal_symmetry=command_line.symmetry, force_symmetry=not command_line.options.weak_symmetry, merge_equivalents=False) except Sorry as KeyboardInterrupt: raise except Exception: pass if (miller_arrays is None): print("Warning: unknown file format:", file_name, file=sys.stderr) print(file=sys.stderr) sys.stderr.flush() else: n = _process_miller_arrays( command_line=command_line, input_miller_arrays=miller_arrays, active_miller_arrays=active_miller_arrays) if (n < 0): return n_f_sq_as_f += n if (additional_miller_arrays is not None): n = _process_miller_arrays( command_line=command_line, input_miller_arrays=additional_miller_arrays, active_miller_arrays=active_miller_arrays) if (n < 0): return n_f_sq_as_f += n if (n_f_sq_as_f > 0): if (n_f_sq_as_f == 1): print( "Note: Intensity array has been converted to an amplitude array." ) else: print( "Note: Intensity arrays have been converted to amplitude arrays." ) print() if (len(active_miller_arrays) > 2 and not command_line.options.quick): print("Array indices (for quick searching):") for i_0, input_0 in enumerate(active_miller_arrays): print(" %2d:" % (i_0 + 1), input_0.info()) print() print("Useful search patterns are:") print(" Summary i") print(" CC Obs i j") print(" CC Ano i j") print(" i and j are the indices shown above.") print() n_bins = command_line.options.n_bins array_caches = [] for i_0, input_0 in enumerate(active_miller_arrays): print("Summary", i_0 + 1) print() cache_0 = array_cache( input=input_0, n_bins=n_bins, lattice_symmetry_max_delta=\ command_line.options.lattice_symmetry_max_delta, completeness_as_non_anomalous=completeness_as_non_anomalous) cache_0.show_possible_twin_laws() cache_0.show_completeness() cache_0.show_patterson_peaks() if (not cache_0.input.space_group().is_centric()): cache_0.show_perfect_merohedral_twinning_test( n_bins=command_line.options.n_bins_twinning_test) else: cache_0.show_second_moments_of_intensities( n_bins=command_line.options.n_bins_second_moments) if (cache_0.input.anomalous_flag()): print("Anomalous signal of %s:" % str(cache_0.input.info())) print(cache_0.input.anomalous_signal.__doc__) anom_signal = cache_0.input.anomalous_signal(use_binning=True) anom_signal.show() print() cache_0.show_measurability() for i_1, cache_1 in enumerate(array_caches): unique_reindexing_operators = cache_1.unique_reindexing_operators( other=cache_0, relative_length_tolerance=0.05, absolute_angle_tolerance=5) if (len(unique_reindexing_operators) == 0): print("Incompatible unit cells:") print(" %2d:" % (i_1 + 1), cache_1.input.info()) print(" %2d:" % (i_0 + 1), cache_0.input.info()) print("No comparison.") print() else: ccs = flex.double() for cb_op in unique_reindexing_operators: similar_array_0 = cache_0.observations \ .change_basis(cb_op) \ .map_to_asu() ccs.append( cache_1.observations.correlation( other=similar_array_0, assert_is_similar_symmetry=False).coefficient()) permutation = flex.sort_permutation(ccs, reverse=True) ccs = ccs.select(permutation) unique_reindexing_operators = flex.select( unique_reindexing_operators, permutation=permutation) for i_cb_op, cb_op, cc in zip(count(), unique_reindexing_operators, ccs): combined_cb_op = cache_1.combined_cb_op(other=cache_0, cb_op=cb_op) if (not combined_cb_op.c().is_unit_mx()): reindexing_note = " after reindexing %d using %s" % ( i_0 + 1, combined_cb_op.as_hkl()) else: reindexing_note = "" print("CC Obs %d %d %6.3f %s" % (i_1 + 1, i_0 + 1, cc, combined_cb_op.as_hkl())) print("Correlation of:") print(" %2d:" % (i_1 + 1), cache_1.input.info()) print(" %2d:" % (i_0 + 1), cache_0.input.info()) print("Overall correlation: %6.3f%s" % (cc, reindexing_note)) show_in_bins = False if (i_cb_op == 0 or (cc >= 0.3 and cc >= ccs[0] - 0.2)): show_in_bins = True similar_array_0 = cache_0.observations \ .change_basis(cb_op) \ .map_to_asu() cache_1.setup_common_binner(cache_0, n_bins=n_bins) correlation = cache_1.observations.correlation( other=similar_array_0, use_binning=True, assert_is_similar_symmetry=False) correlation.show() print() if (cache_0.anom_diffs is not None and cache_1.anom_diffs is not None): similar_anom_diffs_0 = cache_0.anom_diffs \ .change_basis(cb_op) \ .map_to_asu() correlation = cache_1.anom_diffs.correlation( other=similar_anom_diffs_0, assert_is_similar_symmetry=False) print("CC Ano %d %d %6.3f %s" % (i_1 + 1, i_0 + 1, correlation.coefficient(), combined_cb_op.as_hkl())) print("Anomalous difference correlation of:") print(" %2d:" % (i_1 + 1), cache_1.input.info()) print(" %2d:" % (i_0 + 1), cache_0.input.info()) print( "Overall anomalous difference correlation: %6.3f%s" % (correlation.coefficient(), reindexing_note)) if (show_in_bins): correlation = cache_1.anom_diffs.correlation( other=similar_anom_diffs_0, use_binning=True, assert_is_similar_symmetry=False) correlation.show() print() if (not command_line.options.quick): array_caches.append(cache_0) print("=" * 79) print()
def run(args, command_name="phenix.pdb.hierarchy"): if (len(args) == 0): args = ["--help"] command_line = (option_parser(usage="%s file..." % command_name).option( None, "--details", action="store", type="string", default=None, help="level of detail", metavar="|".join(pdb.hierarchy.level_ids) ).option( None, "--residue_groups_max_show", action="store", type="int", default=10, help="maximum number of residue groups to be listed along with" " errors or warnings", metavar="INT" ).option( None, "--duplicate_atom_labels_max_show", action="store", type="int", default=10, help="maximum number of groups of duplicate atom labels to be listed", metavar="INT" ).option( None, "--prefix", action="store", type="string", default="", help="prefix for all output lines", metavar="STRING" ).option( None, "--write_pdb_file", action="store", type="string", default=None, help="write hierarchy as PDB coordinate section to file", metavar="FILE" ).option( None, "--set_element_simple", action="store_true", default=False, help="sets or tidies ATOM record element columns (77-78) if necessary" " before writing PDB file" ).option( None, "--reset_serial_first_value", action="store", type="int", default=None, help="resets atom serial numbers before writing PDB file", metavar="INT" ).option( None, "--interleaved_conf", action="store", type="int", default=0, help="interleave alt. conf. when writing PDB file; possible choices are:" " 0 (not interleaved)," " 1 (interleaved atom names but not resnames)," " 2 (fully interleaved)", metavar="INT").option( None, "--no_anisou", action="store_true", default=False, help="suppress ANISOU records when writing PDB file" ).option( None, "--no_sigatm", action="store_true", default=False, help="suppress SIGATM records when writing PDB file" ).option( None, "--no_cryst", action="store_true", default=False, help="suppress crystallographic records (e.g. CRYST1 and SCALEn)" " when writing PDB file")).process(args=args) co = command_line.options for file_name in command_line.args: if (not os.path.isfile(file_name)): continue pdb_objs = execute( file_name=file_name, prefix=co.prefix, residue_groups_max_show=co.residue_groups_max_show, duplicate_atom_labels_max_show=co.duplicate_atom_labels_max_show, level_id=co.details) if (co.write_pdb_file is not None): if (co.set_element_simple): pdb_objs.hierarchy.atoms( ).set_chemical_element_simple_if_necessary() open_append = False if (not co.no_cryst): s = pdb_objs.input.crystallographic_section() if (s.size() != 0): print("\n".join(s), file=open(co.write_pdb_file, "w")) open_append = True pdb_objs.hierarchy.write_pdb_file( file_name=co.write_pdb_file, open_append=open_append, append_end=True, interleaved_conf=co.interleaved_conf, atoms_reset_serial_first_value=co.reset_serial_first_value, sigatm=not co.no_sigatm, anisou=not co.no_anisou, siguij=not co.no_anisou) print(co.prefix.rstrip())