예제 #1
0
  def save_oper(self):
     # decide if there is anything to save:

     have_oper=True
     for item in (self._trans,self._rota_matrix,self._center):
       if not item:
          have_oper=False
     if self._rota_matrix and len(self._rota_matrix)!=3:
          raise Sorry("Cannot interpret this NCS file (rotations not understood)")
     if self._trans and len(self._trans)!=3:
          raise Sorry("Cannot interpret this NCS file (translations not understood)")
     have_something=False
     if have_oper or self._rmsd or self._residues_in_common:
       have_something=True
     if not have_something: return
     self._n_ncs_oper+=1
     if have_oper:
       from scitbx import matrix
       self._ncs_trans_orth.append(matrix.col(self._trans))
       self._ncs_rota_matr.append(matrix.sqr(
         self._rota_matrix[0]+self._rota_matrix[1]+self._rota_matrix[2] ))
       self._ncs_center_orth.append(matrix.col(self._center))
     else:
       self._ncs_trans_orth.append(None)
       self._ncs_rota_matr.append(None)
       self._ncs_center_orth.append(None)
     self._rmsd_list.append(self._rmsd)
     self._residues_in_common_list.append(self._residues_in_common)
     self._list_of_resseq_list.append(self._resseq_list)
     self._group.append(self._chain)

     self.init_oper()
예제 #2
0
 def show_summary(self, log=None):
   if(self.epsfac is None): return None
   if(log is None): log = sys.stdout
   for i, ncs_pair in enumerate(self.ncs_pairs):
     print >> log, "tNCS group: %d"%i
     angle = matrix.sqr(ncs_pair.r).rotation_angle()
     t = ",".join([("%6.3f"%t_).strip() for t_ in ncs_pair.t]).strip()
     t_cart = ",".join([("%6.3f"%t_).strip()
       for t_ in self.unit_cell.orthogonalize(ncs_pair.t)]).strip()
     r = ",".join([("%8.6f"%r_).strip() for r_ in ncs_pair.r]).strip()
     print >> log, "  Translation (fractional): (%s)"%t
     print >> log, "  Translation (Cartesian):  (%s)"%t_cart
     print >> log, "  Rotation (deg): %-5.2f"%angle
     print >> log, "  Rotation matrix: (%s)"%r
     print >> log, "  Radius: %-6.1f"%ncs_pair.radius
     print >> log, "  Radius (estimate): %-6.1f"%ncs_pair.radius_estimate
     print >> log, "  fracscat:", ncs_pair.fracscat
   print >> log, "tNCS eps factor: min,max,mean: %6.4f %6.4f %6.4f"%\
     self.epsfac.min_max_mean().as_tuple()
예제 #3
0
 def show_summary(self, log=None):
     if (self.epsfac is None): return None
     if (log is None): log = sys.stdout
     for i, ncs_pair in enumerate(self.ncs_pairs):
         print >> log, "tNCS pair: %d" % i
         print >> log, "  Group ID:", ncs_pair.id
         angle = matrix.sqr(ncs_pair.r).rotation_angle()
         t = ",".join([("%6.3f" % t_).strip() for t_ in ncs_pair.t]).strip()
         t_cart = ",".join([
             ("%6.3f" % t_).strip()
             for t_ in self.unit_cell.orthogonalize(ncs_pair.t)
         ]).strip()
         r = ",".join([("%8.6f" % r_).strip() for r_ in ncs_pair.r]).strip()
         print >> log, "  Translation (fractional): (%s)" % t
         print >> log, "  Translation (Cartesian):  (%s)" % t_cart
         print >> log, "  Rotation (deg): %-5.2f" % angle
         print >> log, "  Rotation matrix: (%s)" % r
         print >> log, "  Radius: %-6.3f" % ncs_pair.radius
         print >> log, "  Radius (estimate): %-6.1f" % ncs_pair.radius_estimate
         print >> log, "  fracscat:", ncs_pair.fracscat
     print >> log, "tNCS eps factor: min,max,mean: %6.4f %6.4f %6.4f"%\
       self.epsfac.min_max_mean().as_tuple()
예제 #4
0
파일: xmanip.py 프로젝트: dials/cctbx
def run(args, command_name="phenix.xmanip"):
    if (len(args) == 0 or "--help" in args or "--h" in args or "-h" in args):
        print_help(command_name=command_name)
    else:
        log = multi_out()
        if (not "--quiet" in args):
            log.register(label="stdout", file_object=sys.stdout)
        string_buffer = StringIO()
        string_buffer_plots = StringIO()
        log.register(label="log_buffer", file_object=string_buffer)

        phil_objects = []
        argument_interpreter = master_params.command_line_argument_interpreter(
            home_scope="map_coefs")

        print("#phil __OFF__", file=log)
        print("==========================", file=log)
        print("          XMANIP          ", file=log)
        print("reindexing and other tasks", file=log)
        print("==========================", file=log)
        print(file=log)

        for arg in args:
            command_line_params = None
            arg_is_processed = False
            # is it a file?
            if (os.path.isfile(arg)):  ## is this a file name?
                # check if it is a phil file
                try:
                    command_line_params = iotbx.phil.parse(file_name=arg)
                    if command_line_params is not None:
                        phil_objects.append(command_line_params)
                        arg_is_processed = True
                except KeyboardInterrupt:
                    raise
                except Exception:
                    pass
            else:
                try:
                    command_line_params = argument_interpreter.process(arg=arg)
                    if command_line_params is not None:
                        phil_objects.append(command_line_params)
                        arg_is_processed = True
                except KeyboardInterrupt:
                    raise
                except Exception:
                    pass

            if not arg_is_processed:
                print("##----------------------------------------------##",
                      file=log)
                print("## Unknown file or keyword:", arg, file=log)
                print("##----------------------------------------------##",
                      file=log)
                print(file=log)
                raise Sorry("Unknown file or keyword: %s" % arg)

        effective_params = master_params.fetch(sources=phil_objects)
        params = effective_params.extract()

        # now get the unit cell from the files
        hkl_xs = []
        pdb_xs = None

        #multiple file names are allowed
        for xray_data in params.xmanip.input.xray_data:
            if xray_data.file_name is not None:
                hkl_xs.append(
                    crystal_symmetry_from_any.extract_from(
                        file_name=xray_data.file_name))

        if params.xmanip.input.model.file_name is not None:
            pdb_xs = crystal_symmetry_from_any.extract_from(
                file_name=params.xmanip.input.model.file_name)

        phil_xs = crystal.symmetry(
            unit_cell=params.xmanip.input.unit_cell,
            space_group_info=params.xmanip.input.space_group)

        combined_xs = crystal.select_crystal_symmetry(None, phil_xs, [pdb_xs],
                                                      hkl_xs)
        if combined_xs is not None:
            # inject the unit cell and symmetry in the phil scope please
            params.xmanip.input.unit_cell = combined_xs.unit_cell()
            params.xmanip.input.space_group = \
              sgtbx.space_group_info( group = combined_xs.space_group() )

        print("#phil __ON__", file=log)
        new_params = master_params.format(python_object=params)
        new_params.show(out=log)
        print("#phil __END__", file=log)

        if params.xmanip.input.unit_cell is None:
            raise Sorry("unit cell not specified")
        if params.xmanip.input.space_group is None:
            raise Sorry("space group not specified")

        #-----------------------------------------------------------
        #
        # step 1: read in the reflection file
        #

        miller_arrays = []
        labels = []
        label_appendix = []
        write_it = []
        names = {}

        if len(params.xmanip.input.xray_data) > 0:

            phil_xs = crystal.symmetry(
                unit_cell=params.xmanip.input.unit_cell,
                space_group_info=params.xmanip.input.space_group)

            xray_data_server = reflection_file_utils.reflection_file_server(
                crystal_symmetry=phil_xs,
                force_symmetry=True,
                reflection_files=[])

            count = 0
            for xray_data in params.xmanip.input.xray_data:
                if xray_data.file_name is not None:
                    miller_array = None
                    miller_array = read_data(xray_data.file_name,
                                             xray_data.labels, phil_xs)
                    print(file=log)
                    print("Summary info of observed data", file=log)
                    print("=============================", file=log)
                    if miller_array is None:
                        raise Sorry("Failed to read data. see errors above")
                    miller_array.show_summary(f=log)
                    print(file=log)

                    miller_arrays.append(miller_array)
                    labels.append(miller_array.info().labels)
                    label_appendix.append(xray_data.label_appendix)

                    this_name = "COL_" + str(count)
                    if xray_data.name is not None:
                        this_name = xray_data.name
                    #check if this name is allready used
                    if this_name in names:
                        raise Sorry(
                            "Non unique dataset name. Please change the input script"
                        )
                    names.update({this_name: count})
                    count += 1

                    write_it.append(xray_data.write_out)

            output_label_root = construct_output_labels(labels, label_appendix)
            for ii in range(len(labels)):
                test = 0
                for jj in range(ii + 1, len(labels)):
                    for lab_name1, lab_name2 in zip(labels[ii], labels[jj]):
                        if lab_name1 == lab_name2:
                            test += 1
                    if test == 2:
                        print(
                            "\n***** You are trying to import the data with label(s) %s more then one time. ***** \n"
                            % (str(labels[ii])),
                            file=log)
            for ii in range(len(output_label_root)):
                for jj in range(ii + 1, len(output_label_root)):
                    if output_label_root[ii] == output_label_root[jj]:
                        if write_it[ii]:
                            if write_it[jj]:
                                print("Output label roots:", file=log)
                                print(output_label_root, file=log)
                                raise Sorry(
                                    "Output labels are not unique. Modify input."
                                )

        #----------------------------------------------------------------
        # Step 2: get an xray structure from the PDB file
        #
        pdb_model = None
        model = None
        if params.xmanip.input.model.file_name is not None:
            pdb_model = iotbx.pdb.input(
                file_name=params.xmanip.input.model.file_name)
            model = pdb_model.xray_structure_simple(crystal_symmetry=phil_xs)
            print("Atomic model summary", file=log)
            print("====================", file=log)
            model.show_summary(f=log)
            print(file=log)

        write_miller_array = False
        write_pdb_file = False
        # define some output holder thingamebobs
        new_miller_arrays = []
        new_model = None

        #manipulate miller arrays
        if params.xmanip.parameters.action == "manipulate_miller":
            write_miller_array = True
            new_miller = xmanip_tasks.manipulate_miller(
                names, miller_arrays, model,
                params.xmanip.parameters.manipulate_miller, log)
            miller_arrays.append(new_miller)
            # not very smart to rely here on a phil defintion defined in another file
            tmp_root = params.xmanip.parameters.manipulate_miller.output_label_root
            if tmp_root is None:
                tmp_root = "UNSPECIFIED"
            output_label_root.append(tmp_root)
            write_it.append(True)

        if params.xmanip.parameters.action == "reindex":
            write_miller_array = True
            #----------------------------------------------------------------
            # step 3: get the reindex laws
            phil_xs.show_summary()
            to_niggli = phil_xs.change_of_basis_op_to_niggli_cell()
            to_reference = phil_xs.change_of_basis_op_to_reference_setting()
            to_inverse = phil_xs.change_of_basis_op_to_inverse_hand()
            to_primitive = phil_xs.change_of_basis_op_to_primitive_setting()
            cb_op = None
            if (params.xmanip.parameters.reindex.standard_laws == "niggli"):
                cb_op = to_niggli
            if (params.xmanip.parameters.reindex.standard_laws ==
                    "reference_setting"):
                cb_op = to_reference
            if (params.xmanip.parameters.reindex.standard_laws == "invert"):
                cb_op = to_inverse
            if (params.xmanip.parameters.reindex.standard_laws ==
                    "user_supplied"):
                cb_op = sgtbx.change_of_basis_op(
                    params.xmanip.parameters.reindex.user_supplied_law)
            if (params.xmanip.parameters.reindex.standard_laws ==
                    "primitive_setting"):
                cb_op = to_primitive

            if cb_op is None:
                raise Sorry("No change of basis operation is supplied.")

            print("Supplied reindexing law:", file=log)
            print("========================", file=log)
            print("hkl notation: ", cb_op.as_hkl(), file=log)
            print("xyz notation: ", cb_op.as_xyz(), file=log)
            print("abc notation: ", cb_op.as_abc(), file=log)
            #----------------------------------------------------------------
            # step 4: do the reindexing
            #
            # step 4a: first do the miller array object
            #new_miller_arrays = []
            for miller_array in miller_arrays:
                new_miller_array = None
                if miller_array is not None:
                    new_miller_array = miller_array.change_basis(cb_op)
                    new_miller_arrays.append(new_miller_array)
            #
            # step 4b: the xray structure
            if pdb_model is not None:
                write_pdb_file = True
                new_model = model.change_basis(cb_op)

        if write_miller_array:
            if len(new_miller_arrays) == 0:
                new_miller_arrays = miller_arrays
            #----------------------------------------------------------------
            print(file=log)
            print("The data has been reindexed/manipulated", file=log)
            print("--------------------------------------", file=log)
            print(file=log)
            print("Writing output files....", file=log)

            mtz_dataset = None
            if len(new_miller_arrays) > 0:
                first = 0
                for item in range(len(write_it)):
                    if write_it[item]:
                        first = item
                        if new_miller_arrays[first] is not None:
                            break

                if new_miller_arrays[first] is not None:
                    tmp = new_miller_arrays[first].map_to_asu()
                    mtz_dataset = tmp.as_mtz_dataset(
                        column_root_label=output_label_root[first])

            if mtz_dataset is not None:
                for miller_array, new_root in zip(
                        new_miller_arrays[first + 1:],
                        output_label_root[first + 1:]):
                    if miller_array is not None:
                        mtz_dataset = mtz_dataset.add_miller_array(
                            miller_array=miller_array,
                            column_root_label=new_root)

                print("Writing mtz file with name %s" %
                      (params.xmanip.output.hklout),
                      file=log)
                mtz_dataset.mtz_object().write(
                    file_name=params.xmanip.output.hklout)

            #step 5b: write the new pdb file
            if new_model is not None:
                pdb_file = open(params.xmanip.output.xyzout, 'w')
                print("Wring pdb file to: %s" % (params.xmanip.output.xyzout),
                      file=log)
                write_as_pdb_file(input_pdb=pdb_model,
                                  input_xray_structure=new_model,
                                  out=pdb_file,
                                  chain_id_increment=0,
                                  additional_remark="Generated by %s" %
                                  command_name)

                pdb_file.close()
            if ([miller_array, new_model]).count(None) == 2:
                print(
                    "No input reflection of coordinate files have been given",
                    file=log)

        if params.xmanip.parameters.action == "manipulate_pdb":
            if params.xmanip.parameters.manipulate_pdb.task == "apply_operator":
                rt_mx = None
                if params.xmanip.parameters.manipulate_pdb.apply_operator.standard_operators == "user_supplied_operator":
                    rt_mx = sgtbx.rt_mx(
                        params.xmanip.parameters.manipulate_pdb.apply_operator.
                        user_supplied_operator,
                        t_den=12 * 8)
                    print("Applied operator : ", rt_mx.as_xyz(), file=log)
                if params.xmanip.parameters.manipulate_pdb.apply_operator.standard_operators == \
                     "user_supplied_cartesian_rotation_matrix":
                    rt = params.xmanip.parameters.manipulate_pdb.apply_operator.user_supplied_cartesian_rotation_matrix
                    tmp_r = None
                    tmp_t = None
                    if "," in rt.r:
                        tmp_r = rt.r.split(',')
                    else:
                        tmp_r = rt.r.split(' ')
                    if "," in rt.r:
                        tmp_t = rt.t.split(',')
                    else:
                        tmp_t = rt.t.split(' ')
                    tmp_tmp_r = []
                    tmp_tmp_t = []
                    for item in tmp_r:
                        tmp_tmp_r.append(float(item))
                    if len(tmp_tmp_r) != 9:
                        raise Sorry(
                            "Invalid rotation matrix. Please check input: %s" %
                            (rt.r))
                    for item in tmp_t:
                        tmp_tmp_t.append(float(item))
                    if len(tmp_tmp_t) != 3:
                        raise Sorry(
                            "Invalid translational vector. Please check input: %s"
                            % (rt.t))
                    tmp_tmp_t = (tmp_tmp_t)
                    rt_mx = quick_rt_mx(tmp_tmp_r, tmp_tmp_t)
                    print("User supplied cartesian matrix and vector: ",
                          file=log)
                    rt_mx.show()
                    o = matrix.sqr(
                        model.unit_cell().orthogonalization_matrix())
                    tmp_r = o.inverse() * rt_mx.r() * o
                    tmp_t = o.inverse() * matrix.col(list(rt_mx.t()))
                    print(file=log)
                    print("Operator in fractional coordinates: ", file=log)
                    rt_mx = quick_rt_mx(r=tmp_r.as_float(), t=list(tmp_t))
                    rt_mx.show(out=log)
                    print(file=log)

                if params.xmanip.parameters.manipulate_pdb.apply_operator.invert:
                    rt_mx = rt_mx.inverse()
                    print(file=log)
                    print("Taking inverse of given operator", file=log)
                    print(file=log)

                sites = model.sites_frac()
                new_sites = flex.vec3_double()
                for site in sites:
                    new_site = rt_mx.r() * matrix.col(site)
                    new_site = flex.double(new_site) + flex.double(
                        rt_mx.t().as_double())
                    new_sites.append(tuple(new_site))
                new_model = model.deep_copy_scatterers()

                new_model.set_sites_frac(new_sites)
                # write the new [pdb file please
                pdb_file = open(params.xmanip.output.xyzout, 'w')
                print("Wring pdb file to: %s" % (params.xmanip.output.xyzout),
                      file=log)
                if params.xmanip.parameters.manipulate_pdb.apply_operator.concatenate_model:
                    write_as_pdb_file(input_pdb=pdb_model,
                                      input_xray_structure=model,
                                      out=pdb_file,
                                      chain_id_increment=0,
                                      additional_remark=None,
                                      print_cryst_and_scale=True)

                write_as_pdb_file(
                    input_pdb=pdb_model,
                    input_xray_structure=new_model,
                    out=pdb_file,
                    chain_id_increment=params.xmanip.parameters.manipulate_pdb.
                    apply_operator.chain_id_increment,
                    additional_remark=None,
                    print_cryst_and_scale=False)

                pdb_file.close()

            if params.xmanip.parameters.manipulate_pdb.task == "set_b":
                #rest all the b values
                if params.xmanip.parameters.manipulate_pdb.set_b:
                    b_iso = params.xmanip.parameters.manipulate_pdb.b_iso
                    new_model = model.set_b_iso(value=b_iso)
                    print(file=log)
                    print("All B-values have been set to %5.3f" % (b_iso),
                          file=log)
                    print("Writing PDB file %s" %
                          (params.xmanip.output.xyzout),
                          file=log)
                    print(file=log)

                pdb_file = open(params.xmanip.output.xyzout, 'w')
                write_as_pdb_file(input_pdb=pdb_model,
                                  input_xray_structure=new_model,
                                  out=pdb_file,
                                  chain_id_increment=0,
                                  additional_remark=None,
                                  print_cryst_and_scale=True)
                pdb_file.close()

        #write the logfile
        logger = open(params.xmanip.output.logfile, 'w')
        print("Writing log file with name %s  " %
              (params.xmanip.output.logfile),
              file=log)
        print(string_buffer.getvalue()[0:len(string_buffer.getvalue()) - 1],
              file=logger)  #avoid a newline at the end ...
        logger.close()
예제 #5
0
파일: xmanip.py 프로젝트: dials/cctbx
 def __init__(self, r=[1, 0, 0, 0, 1, 0, 0, 0, 1], t=(0, 0, 0)):
     self.rm = matrix.sqr(r)
     self.tv = flex.double(t)
예제 #6
0
  def copy_rot_trans(self,list_of_matrices,list_of_translations,
      change_of_basis_operator=None,
      coordinate_offset=None,
      unit_cell=None,new_unit_cell=None):
    # if change_of_basis_operator is None, then return copy of what we have
    from copy import deepcopy
    from scitbx.math import  matrix
    new_list_of_matrices=[]
    new_list_of_translations=[]
    if change_of_basis_operator is not None:
      a=  matrix.sqr(new_unit_cell.orthogonalization_matrix()) \
        * change_of_basis_operator.c().as_rational().r \
        * matrix.sqr(unit_cell.fractionalization_matrix())
      a_inv=a.inverse()
    else:
      a=None
    for ncs_r,ncs_t in zip(list_of_matrices,list_of_translations):
      if change_of_basis_operator is None and coordinate_offset is None:
        new_list_of_matrices.append(deepcopy(ncs_r))
        new_list_of_translations.append(deepcopy(ncs_t))
      elif coordinate_offset is not None:
        # TT 2015-11-02 special case of below where cob is just a translation
        # R' =  R
        # T' =  T + t - R t
        new_list_of_matrices.append(deepcopy(ncs_r))  # these are the same
        from scitbx import matrix
        delta = ncs_r * coordinate_offset
        t_prime=matrix.col(ncs_t) + \
          matrix.col(coordinate_offset) - matrix.col(delta)
        new_list_of_translations.append(t_prime)

      else:
        # tt 2011-10-02
        # Formula for conversion of NCS rotation matrix and translation
        # relating two points in coordinate system to a second coordinate system
        # The change-of-basis operator is new_x = a x + t
        # The NCS operator is y = R x + T (in original coordinate system)
        # Then if NCS operator in new coordinate system is y' = R' x' + T':
        # R' = a R a_inv
        # T' = a T + t - a R a_inv t = transformed T minus R' * t
        #
        # Derivation:
        # x' and y' (values in new coordinate system) can be written:
        #   x'=a x + t
        #   y'=a y + t
        # Or rewriting:
        #   x= a_inv (x' - t)
        #   y= a_inv (y' - t)
        # Then as y = R x + T  (in original coordinate system), we can say:
        #   a_inv (y' - t) = R (a_inv (x' - t) ) + T
        # Or...
        #   y' = [a R a_inv] x' - [a R a_inv ] t + t + a t
        # So that:
        #   R' = a R a_inv
        #   T' = a T + t - a R a_inv t = transformed T minus R' * t

        # matrices are a ncs_r a_inv
        ncs_r_prime=a * ncs_r * a_inv
        new_list_of_matrices.append(ncs_r_prime)

        # translation vectors are partly a * ncs_t + t (the cob operator)
        frac=unit_cell.fractionalize(ncs_t)
        new_frac = change_of_basis_operator.c() * frac
        new_ncs_t=new_unit_cell.orthogonalize(new_frac)
        # translation vectors depend on the change of basis and the rotation
        # as well as the change-of-basis operator
        t_as_col=change_of_basis_operator.c().t().as_rational().as_float()
        # the basis translation in orig coordinate system
        cob_trans=unit_cell.orthogonalize(t_as_col)
        # correction for the basis translation in new coordinate system
        delta = ncs_r_prime * cob_trans
        t_prime=matrix.col(new_ncs_t) - matrix.col(delta)
        new_list_of_translations.append(t_prime)

    return new_list_of_matrices,new_list_of_translations
예제 #7
0
def run(args, command_name="phenix.xmanip"):
  if (len(args) == 0 or "--help" in args or "--h" in args or "-h" in args):
    print_help(command_name=command_name)
  else:
    log = multi_out()
    if (not "--quiet" in args):
      log.register(label="stdout", file_object=sys.stdout)
    string_buffer = StringIO()
    string_buffer_plots = StringIO()
    log.register(label="log_buffer", file_object=string_buffer)

    phil_objects = []
    argument_interpreter = master_params.command_line_argument_interpreter(
      home_scope="map_coefs")

    print >> log, "#phil __OFF__"
    print >> log, "=========================="
    print >> log, "          XMANIP          "
    print >> log, "reindexing and other tasks"
    print >> log, "=========================="
    print >> log


    for arg in args:
      command_line_params = None
      arg_is_processed = False
      # is it a file?
      if (os.path.isfile(arg)): ## is this a file name?
        # check if it is a phil file
        try:
          command_line_params = iotbx.phil.parse(file_name=arg)
          if command_line_params is not None:
            phil_objects.append(command_line_params)
            arg_is_processed = True
        except KeyboardInterrupt: raise
        except Exception : pass
      else:
        try:
          command_line_params = argument_interpreter.process(arg=arg)
          if command_line_params is not None:
            phil_objects.append(command_line_params)
            arg_is_processed = True
        except KeyboardInterrupt: raise
        except Exception : pass

      if not arg_is_processed:
        print >> log, "##----------------------------------------------##"
        print >> log, "## Unknown file or keyword:", arg
        print >> log, "##----------------------------------------------##"
        print >> log
        raise Sorry("Unknown file or keyword: %s" % arg)

    effective_params = master_params.fetch(sources=phil_objects)
    params = effective_params.extract()

    # now get the unit cell from the files
    hkl_xs = []
    pdb_xs = None

    #multiple file names are allowed
    for xray_data in params.xmanip.input.xray_data:
      if xray_data.file_name is not None:
        hkl_xs.append( crystal_symmetry_from_any.extract_from(
           file_name=xray_data.file_name) )

    if params.xmanip.input.model.file_name is not None:
      pdb_xs = crystal_symmetry_from_any.extract_from(
        file_name=params.xmanip.input.model.file_name)

    phil_xs = crystal.symmetry(
      unit_cell=params.xmanip.input.unit_cell,
      space_group_info=params.xmanip.input.space_group  )

    combined_xs = crystal.select_crystal_symmetry(
      None,phil_xs, [pdb_xs],hkl_xs)
    if combined_xs is not None:
      # inject the unit cell and symmetry in the phil scope please
      params.xmanip.input.unit_cell = combined_xs.unit_cell()
      params.xmanip.input.space_group = \
        sgtbx.space_group_info( group = combined_xs.space_group() )

    print >> log, "#phil __ON__"
    new_params =  master_params.format(python_object=params)
    new_params.show(out=log)
    print >> log, "#phil __END__"

    if params.xmanip.input.unit_cell is None:
      raise Sorry("unit cell not specified")
    if params.xmanip.input.space_group is None:
      raise Sorry("space group not specified")

    #-----------------------------------------------------------
    #
    # step 1: read in the reflection file
    #

    miller_arrays = []
    labels = []
    label_appendix = []
    write_it = []
    names = {}

    if len(params.xmanip.input.xray_data)>0:

      phil_xs = crystal.symmetry(
        unit_cell=params.xmanip.input.unit_cell,
        space_group_info=params.xmanip.input.space_group  )

      xray_data_server =  reflection_file_utils.reflection_file_server(
        crystal_symmetry = phil_xs,
        force_symmetry = True,
        reflection_files=[])

      count=0
      for xray_data in params.xmanip.input.xray_data:
        if xray_data.file_name is not None:
          miller_array = None
          miller_array = read_data(xray_data.file_name,
                                   xray_data.labels,
                                   phil_xs)
          print >> log
          print >> log, "Summary info of observed data"
          print >> log, "============================="
          if miller_array is None:
            raise Sorry("Failed to read data. see errors above" )
          miller_array.show_summary(f=log)
          print >> log

          miller_arrays.append( miller_array )
          labels.append( miller_array.info().labels )
          label_appendix.append( xray_data.label_appendix )

          this_name = "COL_"+str(count)
          if xray_data.name is not None:
            this_name = xray_data.name
          #check if this name is allready used
          if names.has_key( this_name ):
            raise Sorry( "Non unique dataset name. Please change the input script" )
          names.update( {this_name:count} )
          count += 1

          write_it.append( xray_data.write_out)

      output_label_root = construct_output_labels( labels, label_appendix )
      for ii in range(len(labels)):
        test=0
        for jj in range( ii+1,len(labels) ):
          for lab_name1, lab_name2 in zip(labels[ii],labels[jj]):
            if lab_name1==lab_name2:
              test+=1
          if test == 2:
            print >> log, "\n***** You are trying to import the data with label(s) %s more then one time. ***** \n"%(str(labels[ii]))
      for ii in range(len(output_label_root)):
        for jj in range(ii+1,len(output_label_root)):
          if output_label_root[ii]==output_label_root[jj]:
            if write_it[ii]:
              if write_it[jj]:
                print >> log, "Output label roots:"
                print >> log, output_label_root
                raise Sorry( "Output labels are not unique. Modify input." )



    #----------------------------------------------------------------
    # Step 2: get an xray structure from the PDB file
    #
    pdb_model = None
    model = None
    if params.xmanip.input.model.file_name is not None:
      pdb_model = iotbx.pdb.input(
        file_name=params.xmanip.input.model.file_name)
      model = pdb_model.xray_structure_simple(crystal_symmetry=phil_xs)
      print >> log, "Atomic model summary"
      print >> log, "===================="
      model.show_summary(f=log)
      print >> log


    write_miller_array = False
    write_pdb_file = False
    # define some output holder thingamebobs
    new_miller_arrays = []
    new_model = None

    #manipulate miller arrays
    if params.xmanip.parameters.action == "manipulate_miller":
      write_miller_array = True
      new_miller = xmanip_tasks.manipulate_miller(names,
                                                  miller_arrays,
                                                  model,
                                                  params.xmanip.parameters.manipulate_miller,
                                                  log )
      miller_arrays.append( new_miller )
      # not very smart to rely here on a phil defintion defined in another file
      tmp_root = params.xmanip.parameters.manipulate_miller.output_label_root
      if tmp_root is None:
        tmp_root = "UNSPECIFIED"
      output_label_root.append( tmp_root )
      write_it.append(True)




    if params.xmanip.parameters.action=="reindex":
      write_miller_array = True
      #----------------------------------------------------------------
      # step 3: get the reindex laws
      phil_xs.show_summary()
      to_niggli    = phil_xs.change_of_basis_op_to_niggli_cell()
      to_reference = phil_xs.change_of_basis_op_to_reference_setting()
      to_inverse   = phil_xs.change_of_basis_op_to_inverse_hand()
      to_primitive = phil_xs.change_of_basis_op_to_primitive_setting()
      cb_op = None
      if (params.xmanip.parameters.reindex.standard_laws == "niggli"):
        cb_op = to_niggli
      if (params.xmanip.parameters.reindex.standard_laws == "reference_setting"):
        cb_op = to_reference
      if (params.xmanip.parameters.reindex.standard_laws == "invert"):
        cb_op = to_inverse
      if (params.xmanip.parameters.reindex.standard_laws == "user_supplied"):
        cb_op = sgtbx.change_of_basis_op( params.xmanip.parameters.reindex.user_supplied_law )
      if (params.xmanip.parameters.reindex.standard_laws == "primitive_setting"):
        cb_op = to_primitive


      if cb_op is None:
        raise Sorry("No change of basis operation is supplied.")

      print >> log, "Supplied reindexing law:"
      print >> log, "========================"
      print >> log, "hkl notation: ", cb_op.as_hkl()
      print >> log, "xyz notation: ", cb_op.as_xyz()
      print >> log, "abc notation: ", cb_op.as_abc()
      #----------------------------------------------------------------
      # step 4: do the reindexing
      #
      # step 4a: first do the miller array object
      #new_miller_arrays = []
      for miller_array in miller_arrays:
        new_miller_array = None
        if miller_array is not None:
          new_miller_array = miller_array.change_basis( cb_op )
          new_miller_arrays.append( new_miller_array )
      #
      # step 4b: the xray structure
      if pdb_model is not None:
        write_pdb_file=True
        new_model = model.change_basis( cb_op )


    if write_miller_array:
      if len(new_miller_arrays)==0:
        new_miller_arrays = miller_arrays
      #----------------------------------------------------------------
      print >> log
      print >> log, "The data has been reindexed/manipulated"
      print >> log, "--------------------------------------"
      print >> log
      print >> log, "Writing output files...."

      mtz_dataset=None
      if len(new_miller_arrays)>0:
        first=0
        for item in range(len(write_it)):
          if write_it[item]:
            first=item
            if new_miller_arrays[ first ] is not None:
              break

        if new_miller_arrays[first] is not None:
          tmp = new_miller_arrays[first].map_to_asu()
          mtz_dataset = tmp.as_mtz_dataset(
            column_root_label=output_label_root[first])

      if mtz_dataset is not None:
        for miller_array, new_root in zip(new_miller_arrays[first+1:],
                                          output_label_root[first+1:]):
          if miller_array is not None:
            mtz_dataset = mtz_dataset.add_miller_array(
              miller_array = miller_array,
              column_root_label = new_root)

        print >> log, "Writing mtz file with name %s"%(params.xmanip.output.hklout)
        mtz_dataset.mtz_object().write(
          file_name=params.xmanip.output.hklout)

      #step 5b: write the new pdb file
      if new_model is not None:
        pdb_file = open( params.xmanip.output.xyzout, 'w')
        print >> log, "Wring pdb file to: %s"%(params.xmanip.output.xyzout)
        write_as_pdb_file(
          input_pdb = pdb_model,
          input_xray_structure = new_model,
          out = pdb_file,
          chain_id_increment= 0,
          additional_remark = "Generated by %s" % command_name)

        pdb_file.close()
      if ( [miller_array,new_model]).count(None)==2:
        print >>log, "No input reflection of coordinate files have been given"

    if params.xmanip.parameters.action=="manipulate_pdb":
      if params.xmanip.parameters.manipulate_pdb.task == "apply_operator":
        rt_mx = None
        if params.xmanip.parameters.manipulate_pdb.apply_operator.standard_operators == "user_supplied_operator":
          rt_mx = sgtbx.rt_mx(
            params.xmanip.parameters.manipulate_pdb.apply_operator.user_supplied_operator,t_den=12*8 )
          print >> log, "Applied operator : ", rt_mx.as_xyz()
        if params.xmanip.parameters.manipulate_pdb.apply_operator.standard_operators == \
             "user_supplied_cartesian_rotation_matrix":
          rt = params.xmanip.parameters.manipulate_pdb.apply_operator.user_supplied_cartesian_rotation_matrix
          tmp_r=None
          tmp_t=None
          if "," in rt.r:
            tmp_r = rt.r.split(',')
          else:
            tmp_r = rt.r.split(' ')
          if "," in rt.r:
            tmp_t = rt.t.split(',')
          else:
            tmp_t = rt.t.split(' ')
          tmp_tmp_r=[]
          tmp_tmp_t=[]
          for item in tmp_r:
            tmp_tmp_r.append( float(item) )
          if len(tmp_tmp_r)!=9:
            raise Sorry("Invalid rotation matrix. Please check input: %s"%(rt.r) )
          for item in tmp_t:
            tmp_tmp_t.append( float(item) )
          if len(tmp_tmp_t)!=3:
            raise Sorry("Invalid translational vector. Please check input: %s"%(rt.t) )
          tmp_tmp_t = (tmp_tmp_t)
          rt_mx = quick_rt_mx(tmp_tmp_r, tmp_tmp_t)
          print >> log, "User supplied cartesian matrix and vector: "
          rt_mx.show()
          o = matrix.sqr(model.unit_cell().orthogonalization_matrix())
          tmp_r = o.inverse()*rt_mx.r()*o
          tmp_t = o.inverse()*matrix.col(list(rt_mx.t()))
          print >> log
          print >> log, "Operator in fractional coordinates: "
          rt_mx = quick_rt_mx(r=tmp_r.as_float(), t=list(tmp_t))
          rt_mx.show(out=log)
          print >> log


        if params.xmanip.parameters.manipulate_pdb.apply_operator.invert:
          rt_mx = rt_mx.inverse()
          print >> log
          print >> log, "Taking inverse of given operator"
          print >> log

        sites = model.sites_frac()
        new_sites = flex.vec3_double()
        for site in sites:
          new_site = rt_mx.r()*matrix.col(site)
          new_site = flex.double(new_site)+flex.double( rt_mx.t().as_double() )
          new_sites.append( tuple(new_site) )
        new_model = model.deep_copy_scatterers()

        new_model.set_sites_frac( new_sites )
        # write the new [pdb file please
        pdb_file = open( params.xmanip.output.xyzout, 'w')
        print >> log, "Wring pdb file to: %s"%(params.xmanip.output.xyzout)
        if params.xmanip.parameters.manipulate_pdb.apply_operator.concatenate_model:
          write_as_pdb_file( input_pdb = pdb_model,
                             input_xray_structure = model,
                             out = pdb_file,
                             chain_id_increment = 0,
                             additional_remark = None,
                             print_cryst_and_scale=True )

        write_as_pdb_file( input_pdb = pdb_model,
                           input_xray_structure = new_model,
                           out = pdb_file,
                           chain_id_increment = params.xmanip.parameters.manipulate_pdb.apply_operator.chain_id_increment,
                           additional_remark = None,
                           print_cryst_and_scale=False )

        pdb_file.close()

      if params.xmanip.parameters.manipulate_pdb.task =="set_b":
        #rest all the b values
        if params.xmanip.parameters.manipulate_pdb.set_b:
          b_iso = params.xmanip.parameters.manipulate_pdb.b_iso
          new_model = model.set_b_iso( value = b_iso )
          print >> log
          print >> log, "All B-values have been set to %5.3f"%(b_iso)
          print >> log, "Writing PDB file %s"%(params.xmanip.output.xyzout)
          print >> log

        pdb_file = open( params.xmanip.output.xyzout, 'w')
        write_as_pdb_file( input_pdb = pdb_model,
                           input_xray_structure = new_model,
                           out = pdb_file,
                           chain_id_increment = 0,
                           additional_remark = None,
                           print_cryst_and_scale=True)
        pdb_file.close()

    #write the logfile
    logger = open( params.xmanip.output.logfile, 'w')
    print >> log, "Writing log file with name %s  "%(params.xmanip.output.logfile)
    print >> logger, string_buffer.getvalue()[0:len(string_buffer.getvalue())-1] #avoid a newline at the end ...
    logger.close()
예제 #8
0
 def __init__(self,
              r = [1,0,0,0,1,0,0,0,1] ,
              t = (0,0,0) ):
   self.rm = matrix.sqr(r)
   self.tv = flex.double(t)