Example #1
0
def exercise_space_group_contains():
    g = sgtbx.space_group("P 2")
    for s in ["x,y,z", "-x,-y,z", "-x+1,-y-2,z+3"]:
        assert g.contains(sgtbx.rt_mx(s))
    for s in ["x,y,-z", "x+1/2,y,z"]:
        assert not g.contains(sgtbx.rt_mx(s))
    for symbols in sgtbx.space_group_symbol_iterator():
        g = sgtbx.space_group(symbols.hall())
        for s in g:
            assert g.contains(s)
    rnd = flex.mersenne_twister(seed=0)
    n_c = 0
    n_nc = 0
    for symbol in sgtbx.bravais_types.centric:
        g = sgtbx.space_group_info(symbol=symbol,
                                   space_group_t_den=144).group()
        for s in g.change_basis(
                sgtbx.change_of_basis_op("x+1/12,y-1/12,z+1/12")):
            if (rnd.random_double() < 0.9): continue  # avoid long runtime
            gc = sgtbx.space_group(g)
            gc.expand_smx(s)
            if (gc.order_z() == g.order_z()):
                assert g.contains(s)
                n_c += 1
            else:
                assert not g.contains(s)
                n_nc += 1
    assert n_c == 11, n_c
    assert n_nc == 53, n_nc
def exercise_space_group_contains():
  g = sgtbx.space_group("P 2")
  for s in ["x,y,z", "-x,-y,z", "-x+1,-y-2,z+3"]:
    assert g.contains(sgtbx.rt_mx(s))
  for s in ["x,y,-z", "x+1/2,y,z"]:
    assert not g.contains(sgtbx.rt_mx(s))
  for symbols in sgtbx.space_group_symbol_iterator():
    g = sgtbx.space_group(symbols.hall())
    for s in g:
      assert g.contains(s)
  rnd = flex.mersenne_twister(seed=0)
  n_c = 0
  n_nc = 0
  for symbol in sgtbx.bravais_types.centric:
    g = sgtbx.space_group_info(symbol=symbol, space_group_t_den=144).group()
    for s in g.change_basis(sgtbx.change_of_basis_op("x+1/12,y-1/12,z+1/12")):
      if (rnd.random_double() < 0.9): continue # avoid long runtime
      gc = sgtbx.space_group(g)
      gc.expand_smx(s)
      if (gc.order_z() == g.order_z()):
        assert g.contains(s)
        n_c += 1
      else:
        assert not g.contains(s)
        n_nc += 1
  assert n_c == 11, n_c
  assert n_nc == 53, n_nc
def generate_enantiomorph_unique_spacegroups(pointgroup):
    '''Generate an enantiomorph unique list of chiral spacegroups which
    share a pointgroup with this pointgroup.'''

    sg = space_group(space_group_symbols(pointgroup).hall())
    pg = sg.build_derived_patterson_group()

    eu_list = []

    for j in space_group_symbol_iterator():
        sg_test = space_group(j)

        if not sg_test.is_chiral():
            continue

        pg_test = sg_test.build_derived_patterson_group()
        if pg_test == pg:
            enantiomorph = sg_test.change_basis(
                sg_test.type().change_of_hand_op())
            if not sg_test in eu_list and not \
               enantiomorph in eu_list:
                eu_list.append(sg_test)

    return [
        sg_test.type().lookup_symbol().replace(' ', '') \
        for sg_test in eu_list]
Example #4
0
    def __init__(self, f_in_p1, **kwds):
        isinstance(f_in_p1, miller.array)
        assert f_in_p1.space_group().type().hall_symbol() == ' P 1'
        self.f_in_p1 = f_in_p1
        adopt_optional_init_args(self, kwds)

        self.search_parameters = maptbx.peak_search_parameters(
            peak_search_level=3,
            interpolate=True,
            min_distance_sym_equiv=0.25,
        )

        self.space_group = sgtbx.space_group('P 1', t_den=sg_t_den)
        self.origin = None
        self.symmetry_pool = []

        self.find_centring_translations()

        if self.space_group.order_z() > 1:
            f_in_centered = self.f_in_p1.customized_copy(
                space_group_info=sgtbx.space_group_info(group=self.space_group)
            ).eliminate_sys_absent().merge_equivalents().array()
            self.cb_op_to_primitive = \
                f_in_centered.change_of_basis_op_to_primitive_setting()
            self.f_in_p1 = f_in_centered.change_basis(self.cb_op_to_primitive)
            self.space_group = self.f_in_p1.space_group()
        else:
            self.cb_op_to_primitive = sgtbx.change_of_basis_op()

        self.f_in_p1 = self.f_in_p1.generate_bijvoet_mates()
        self.find_space_group()
        self.space_group = sgtbx.space_group(
            self.space_group.type().hall_symbol(), t_den=sgtbx.sg_t_den)
        self.space_group_info = sgtbx.space_group_info(group=self.space_group)
  def __init__(self, f_in_p1, **kwds):
    isinstance(f_in_p1, miller.array)
    assert f_in_p1.space_group().type().hall_symbol() == ' P 1'
    self.f_in_p1 = f_in_p1
    adopt_optional_init_args(self, kwds)

    self.search_parameters = maptbx.peak_search_parameters(
      peak_search_level=3,
      interpolate=True,
      min_distance_sym_equiv=0.25,
    )

    self.space_group = sgtbx.space_group('P 1', t_den=sg_t_den)
    self.origin = None
    self.symmetry_pool = []

    self.find_centring_translations()

    if self.space_group.order_z() > 1:
      f_in_centered = self.f_in_p1.customized_copy(
        space_group_info=sgtbx.space_group_info(group=self.space_group)
        ).eliminate_sys_absent().merge_equivalents().array()
      self.cb_op_to_primitive = \
          f_in_centered.change_of_basis_op_to_primitive_setting()
      self.f_in_p1 = f_in_centered.change_basis(self.cb_op_to_primitive)
      self.space_group = self.f_in_p1.space_group()
    else:
      self.cb_op_to_primitive = sgtbx.change_of_basis_op()

    self.f_in_p1 = self.f_in_p1.generate_bijvoet_mates()
    self.find_space_group()
    self.space_group = sgtbx.space_group(self.space_group.type().hall_symbol(),
                                         t_den=sgtbx.sg_t_den)
    self.space_group_info = sgtbx.space_group_info(group=self.space_group)
Example #6
0
def exercise():
    from dials.algorithms.indexing import compare_orientation_matrices
    from dxtbx.model import Crystal
    from cctbx import sgtbx
    from scitbx import matrix
    from scitbx.math import euler_angles as euler

    # try and see if we can get back the original rotation matrix and euler angles
    real_space_a = matrix.col((10, 0, 0))
    real_space_b = matrix.col((0, 10, 10))
    real_space_c = matrix.col((0, 0, 10))
    euler_angles = (1.3, 5.6, 7.8)
    R = matrix.sqr(
        euler.xyz_matrix(euler_angles[0], euler_angles[1], euler_angles[2]))
    crystal_a = Crystal(real_space_a,
                        real_space_b,
                        real_space_c,
                        space_group=sgtbx.space_group('P 1'))
    crystal_b = Crystal(R * real_space_a,
                        R * real_space_b,
                        R * real_space_c,
                        space_group=sgtbx.space_group('P 1'))
    assert approx_equal(
        matrix.sqr(crystal_b.get_U()) *
        matrix.sqr(crystal_a.get_U()).transpose(), R)
    best_R_ab, best_axis, best_angle, best_cb_op = \
      compare_orientation_matrices.difference_rotation_matrix_axis_angle(
        crystal_a,
        crystal_b)
    best_euler_angles = euler.xyz_angles(best_R_ab)
    assert approx_equal(best_euler_angles, euler_angles)
    assert best_cb_op.is_identity_op()
    assert approx_equal(best_R_ab, R)

    # now see if we can deconvolute the original euler angles after applying
    # a change of basis to one of the crystals
    crystal_a = Crystal(real_space_a,
                        real_space_b,
                        real_space_c,
                        space_group=sgtbx.space_group('I 2 3'))
    crystal_b = Crystal(R * real_space_a,
                        R * real_space_b,
                        R * real_space_c,
                        space_group=sgtbx.space_group('I 2 3'))
    cb_op = sgtbx.change_of_basis_op('z,x,y')
    crystal_b = crystal_b.change_basis(cb_op)
    best_R_ab, best_axis, best_angle, best_cb_op = \
      compare_orientation_matrices.difference_rotation_matrix_axis_angle(
        crystal_a,
        crystal_b)
    best_euler_angles = euler.xyz_angles(best_R_ab)
    assert approx_equal(best_euler_angles, euler_angles)
    assert best_cb_op.c() == cb_op.inverse().c()
    assert approx_equal(best_R_ab, R)
def exercise_compatible_symmetries():
    pg = sgtbx.space_group('P 2x')
    ops = [op.as_xyz() for op in pt.compatible_symmetries(pg)]
    assert ops == ['x,-y,-z', 'x+1/2,-y,-z']

    pg = sgtbx.space_group('P 2x 2y')
    ops = [op.as_xyz() for op in pt.compatible_symmetries(pg)]
    assert ops == [
        'x,-y,-z', 'x+1/2,-y,-z', '-x,y,-z', '-x,y+1/2,-z', '-x,-y,z',
        '-x,-y,z+1/2'
    ]

    pg = sgtbx.space_group('P 2x 3*')
    ops = [op.as_xyz() for op in pt.compatible_symmetries(pg)]
    assert 'x,-y,-z' in ops
    assert 'x+1/2,-y,-z' in ops

    assert '-x,y,-z' in ops
    assert '-x,y+1/2,-z' in ops

    assert '-x,-y,z' in ops
    assert '-x,-y,z+1/2' in ops

    assert 'z,x,y' in ops
    assert 'z+1/3,x+1/3,y+1/3' in ops

    assert 'y,z,x' in ops
    assert 'y+1/3,z+1/3,x+1/3' in ops

    assert 'z,-x,-y' in ops
    assert 'z+1/3,-x-1/3,-y+1/3' in ops

    assert '-y,z,-x' in ops
    assert '-y-1/3,z+1/3,-x+1/3' in ops

    assert '-y,-z,x' in ops
    assert '-y+1/3,-z-1/3,x+1/3' in ops

    assert 'y,-z,-x' in ops
    assert 'y-1/3,-z-1/3,-x+1/3' in ops

    assert '-z,-x,y' in ops
    assert '-z-1/3,-x+1/3,y+1/3' in ops

    assert '-z,x,-y' in ops
    assert '-z-1/3,x-1/3,-y+1/3' in ops

    pg = sgtbx.space_group('-P -2y')
    ops = [op.as_xyz() for op in pt.compatible_symmetries(pg)]
    assert ops == [
        'x,-y,z', 'x+1/2,-y,z', 'x,-y,z+1/2', 'x+1/2,-y,z+1/2', '-x,-y,-z',
        '-x,y,-z', '-x,y+1/2,-z'
    ]
def exercise():
  from dials.algorithms.indexing import compare_orientation_matrices
  from dxtbx.model.crystal import crystal_model
  from cctbx import sgtbx
  from scitbx import matrix
  from scitbx.math import euler_angles as euler

  # try and see if we can get back the original rotation matrix and euler angles
  real_space_a = matrix.col((10,0,0))
  real_space_b = matrix.col((0,10,10))
  real_space_c = matrix.col((0,0,10))
  euler_angles = (1.3, 5.6, 7.8)
  R = matrix.sqr(
    euler.xyz_matrix(euler_angles[0], euler_angles[1], euler_angles[2]))
  crystal_a = crystal_model(real_space_a,
                            real_space_b,
                            real_space_c,
                            space_group=sgtbx.space_group('P 1'))
  crystal_b = crystal_model(R * real_space_a,
                            R * real_space_b,
                            R * real_space_c,
                            space_group=sgtbx.space_group('P 1'))
  assert approx_equal(crystal_b.get_U() * crystal_a.get_U().transpose(), R)
  best_R_ab, best_axis, best_angle, best_cb_op = \
    compare_orientation_matrices.difference_rotation_matrix_axis_angle(
      crystal_a,
      crystal_b)
  best_euler_angles = euler.xyz_angles(best_R_ab)
  assert approx_equal(best_euler_angles, euler_angles)
  assert best_cb_op.is_identity_op()
  assert approx_equal(best_R_ab, R)

  # now see if we can deconvolute the original euler angles after applying
  # a change of basis to one of the crystals
  crystal_a = crystal_model(real_space_a,
                            real_space_b,
                            real_space_c,
                            space_group=sgtbx.space_group('I 2 3'))
  crystal_b = crystal_model(R * real_space_a,
                            R * real_space_b,
                            R * real_space_c,
                            space_group=sgtbx.space_group('I 2 3'))
  cb_op = sgtbx.change_of_basis_op('z,x,y')
  crystal_b = crystal_b.change_basis(cb_op)
  best_R_ab, best_axis, best_angle, best_cb_op = \
    compare_orientation_matrices.difference_rotation_matrix_axis_angle(
      crystal_a,
      crystal_b)
  best_euler_angles = euler.xyz_angles(best_R_ab)
  assert approx_equal(best_euler_angles, euler_angles)
  assert best_cb_op.c() == cb_op.inverse().c()
  assert approx_equal(best_R_ab, R)
def exercise_compatible_symmetries():
  pg = sgtbx.space_group('P 2x')
  ops = [ op.as_xyz() for op in pt.compatible_symmetries(pg) ]
  assert ops == [ 'x,-y,-z', 'x+1/2,-y,-z' ]

  pg = sgtbx.space_group('P 2x 2y')
  ops = [ op.as_xyz() for op in pt.compatible_symmetries(pg) ]
  assert ops == [ 'x,-y,-z', 'x+1/2,-y,-z',
                  '-x,y,-z', '-x,y+1/2,-z',
                  '-x,-y,z', '-x,-y,z+1/2' ]

  pg = sgtbx.space_group('P 2x 3*')
  ops = [ op.as_xyz() for op in pt.compatible_symmetries(pg) ]
  assert 'x,-y,-z' in ops
  assert 'x+1/2,-y,-z' in ops

  assert '-x,y,-z' in ops
  assert '-x,y+1/2,-z' in ops

  assert '-x,-y,z' in ops
  assert '-x,-y,z+1/2' in ops

  assert 'z,x,y' in ops
  assert 'z+1/3,x+1/3,y+1/3' in ops

  assert 'y,z,x' in ops
  assert 'y+1/3,z+1/3,x+1/3' in ops

  assert 'z,-x,-y' in ops
  assert 'z+1/3,-x-1/3,-y+1/3' in ops

  assert '-y,z,-x' in ops
  assert '-y-1/3,z+1/3,-x+1/3' in ops

  assert '-y,-z,x' in ops
  assert '-y+1/3,-z-1/3,x+1/3' in ops

  assert 'y,-z,-x' in ops
  assert 'y-1/3,-z-1/3,-x+1/3' in ops

  assert '-z,-x,y' in ops
  assert '-z-1/3,-x+1/3,y+1/3' in ops

  assert '-z,x,-y' in ops
  assert '-z-1/3,x-1/3,-y+1/3' in ops

  pg = sgtbx.space_group('-P -2y')
  ops = [ op.as_xyz() for op in pt.compatible_symmetries(pg) ]
  assert ops == ['x,-y,z', 'x+1/2,-y,z', 'x,-y,z+1/2', 'x+1/2,-y,z+1/2',
                 '-x,-y,-z', '-x,y,-z', '-x,y+1/2,-z']
Example #10
0
def main(filenames,
         map_file,
         npoints=192,
         max_resolution=6,
         reverse_phi=False):
    rec_range = 1 / max_resolution

    image = ImageFactory(filenames[0])
    panel = image.get_detector()[0]
    beam = image.get_beam()
    s0 = beam.get_s0()
    pixel_size = panel.get_pixel_size()

    xlim, ylim = image.get_raw_data().all()

    xy = recviewer.get_target_pixels(panel, s0, xlim, ylim, max_resolution)

    s1 = panel.get_lab_coord(xy * pixel_size[0])  # FIXME: assumed square pixel
    s1 = s1 / s1.norms() * (1 / beam.get_wavelength())  # / is not supported...
    S = s1 - s0

    grid = flex.double(flex.grid(npoints, npoints, npoints), 0)
    cnts = flex.int(flex.grid(npoints, npoints, npoints), 0)

    for filename in filenames:
        print "Processing image", filename
        try:
            fill_voxels(ImageFactory(filename), grid, cnts, S, xy, reverse_phi,
                        rec_range)
        except:
            print " Failed to process. Skipped this."

    recviewer.normalize_voxels(grid, cnts)

    uc = uctbx.unit_cell((npoints, npoints, npoints, 90, 90, 90))
    ccp4_map.write_ccp4_map(map_file, uc, sgtbx.space_group("P1"), (0, 0, 0),
                            grid.all(), grid,
                            flex.std_string(["cctbx.miller.fft_map"]))
    return
    from scitbx import fftpack
    fft = fftpack.complex_to_complex_3d(grid.all())
    grid_complex = flex.complex_double(reals=flex.pow2(grid),
                                       imags=flex.double(grid.size(), 0))
    grid_transformed = flex.abs(fft.backward(grid_complex))
    print flex.max(grid_transformed), flex.min(
        grid_transformed), grid_transformed.all()
    ccp4_map.write_ccp4_map(map_file, uc, sgtbx.space_group("P1"), (0, 0, 0),
                            grid.all(), grid_transformed,
                            flex.std_string(["cctbx.miller.fft_map"]))
Example #11
0
 def __init__(self, parent_group_info):
   self._p_groups = []
   self.z2p_op = parent_group_info.group().z2p_op()
   p_parent_group_info = parent_group_info.change_basis(self.z2p_op)
   p_parent_group = p_parent_group_info.group()
   assert p_parent_group.order_p() == p_parent_group.order_z()
   p_parent_group.make_tidy()
   for i_smx in xrange(p_parent_group.order_p()):
     group_i = sgtbx.space_group()
     group_i.expand_smx(p_parent_group(i_smx))
     for j_smx in xrange(i_smx,p_parent_group.order_p()):
       subgroup = sgtbx.space_group(group_i)
       subgroup.expand_smx(p_parent_group(j_smx))
       subgroup.make_tidy()
       self._add(subgroup)
Example #12
0
def test_compare_orientation_matrices():
    # try and see if we can get back the original rotation matrix and euler angles
    real_space_a = matrix.col((10, 0, 0))
    real_space_b = matrix.col((0, 10, 10))
    real_space_c = matrix.col((0, 0, 10))
    euler_angles = (1.3, 5.6, 7.8)
    R = matrix.sqr(
        euler.xyz_matrix(euler_angles[0], euler_angles[1], euler_angles[2]))
    crystal_a = Crystal(real_space_a,
                        real_space_b,
                        real_space_c,
                        space_group=sgtbx.space_group('P 1'))
    crystal_b = Crystal(R * real_space_a,
                        R * real_space_b,
                        R * real_space_c,
                        space_group=sgtbx.space_group('P 1'))
    assert (matrix.sqr(crystal_b.get_U()) *
            matrix.sqr(crystal_a.get_U()).transpose()).elems == pytest.approx(
                R.elems)
    best_R_ab, best_axis, best_angle, best_cb_op = \
      compare_orientation_matrices.difference_rotation_matrix_axis_angle(
        crystal_a,
        crystal_b)
    best_euler_angles = euler.xyz_angles(best_R_ab)
    assert best_euler_angles == pytest.approx(euler_angles)
    assert best_cb_op.is_identity_op()
    assert best_R_ab.elems == pytest.approx(R.elems)

    # now see if we can deconvolute the original euler angles after applying
    # a change of basis to one of the crystals
    crystal_a = Crystal(real_space_a,
                        real_space_b,
                        real_space_c,
                        space_group=sgtbx.space_group('I 2 3'))
    crystal_b = Crystal(R * real_space_a,
                        R * real_space_b,
                        R * real_space_c,
                        space_group=sgtbx.space_group('I 2 3'))
    cb_op = sgtbx.change_of_basis_op('z,x,y')
    crystal_b = crystal_b.change_basis(cb_op)
    best_R_ab, best_axis, best_angle, best_cb_op = \
      compare_orientation_matrices.difference_rotation_matrix_axis_angle(
        crystal_a,
        crystal_b)
    best_euler_angles = euler.xyz_angles(best_R_ab)
    assert best_euler_angles == pytest.approx(euler_angles)
    assert best_cb_op.c() == cb_op.inverse().c()
    assert best_R_ab.elems == pytest.approx(R.elems)
 def __init__(self, with_special_position_pivot):
   self.with_special_position_pivot = with_special_position_pivot
   self.uc = uctbx.unit_cell((1, 2, 3))
   self.sg = sgtbx.space_group("P 6")
   self.c0 = xray.scatterer("C0", site=(1e-5, 0., 0.1))
   self.site_symm = sgtbx.site_symmetry(self.uc, self.sg, self.c0.site)
   self.c0.flags.set_grad_site(True)
   self.c1 = xray.scatterer("C1", site=(0.09, 0.11, 0.))
   self.c1.flags.set_grad_site(True)
   self.h = xray.scatterer("H")
   self.reparam = constraints.ext.reparametrisation(self.uc)
   if with_special_position_pivot:
     x0 = self.reparam.add(constraints.special_position_site_parameter,
                           self.site_symm, self.c0)
   else:
     x0 = self.reparam.add(constraints.independent_site_parameter, self.c0)
   x1 = self.reparam.add(constraints.independent_site_parameter, self.c1)
   l = self.reparam.add(constraints.independent_scalar_parameter,
                        self.bond_length, variable=False)
   x_h = self.reparam.add(constraints.terminal_linear_ch_site,
                          pivot=x0,
                          pivot_neighbour=x1,
                          length=l,
                          hydrogen=self.h)
   self.reparam.finalise()
   self.x0, self.x1, self.x_h, self.l = [ x.index for x in (x0, x1, x_h, l) ]
   if self.with_special_position_pivot:
     self.y0 = x0.independent_params.index
def convert(file_object):
  """ Examplify the direct use of the tool from shelx.lexer

  In practice, one is strongly encouraged to make use of the tools
  from shelx.parsers: that is to say, for the task handled here,
  crystal_symmetry_parser (the code to follow just parrots
  the implementation of crystal_symmetry_parser).
  """
  space_group = None
  for command, line in shelx.command_stream(file=file_object):
    cmd, args = command[0], command[-1]
    if cmd == "LATT":
      assert space_group is None
      assert len(args) == 1
      space_group = sgtbx.space_group()
      n = int(args[0])
      if n > 0:
        space_group.expand_inv(sgtbx.tr_vec((0,0,0)))
      z = "*PIRFABC"[abs(n)]
      space_group.expand_conventional_centring_type(z)
    elif cmd == "SYMM":
      assert space_group is not None
      assert len(args) == 1
      s = sgtbx.rt_mx(args[0])
      space_group.expand_smx(s)
    elif cmd == "SFAC":
      return sgtbx.space_group_info(group=space_group)
 def __init__(self, file_name, header_only=False):
   self.file_name = os.path.normpath(file_name)
   f = open(file_name)
   line = f.readline()
   assert line[5] == " "
   n_sym_ops_from_file = int(line[:5].strip())
   assert n_sym_ops_from_file > 0
   self.space_group_symbol = line[6:].strip()
   self.space_group_from_ops = sgtbx.space_group()
   for i in xrange(n_sym_ops_from_file):
     line = f.readline().rstrip()
     assert len(line) == 27
     r = sgtbx.rot_mx([int(line[j*3:(j+1)*3]) for j in xrange(9)], 1)
     line = f.readline().rstrip()
     assert len(line) == 9
     t = sgtbx.tr_vec([int(line[j*3:(j+1)*3]) for j in xrange(3)], 12)
     self.space_group_from_ops.expand_smx(sgtbx.rt_mx(r, t))
   f.close()
   if (header_only):
     self.original_indices = None
     return
   all_arrays = scalepack_ext.no_merge_original_index_arrays(
     file_name, n_sym_ops_from_file*2+1)
   self.original_indices = all_arrays.original_indices()
   self.unique_indices = all_arrays.unique_indices()
   self.batch_numbers = all_arrays.batch_numbers()
   self.centric_tags = all_arrays.centric_tags()
   self.spindle_flags = all_arrays.spindle_flags()
   self.asymmetric_unit_indices = all_arrays.asymmetric_unit_indices()
   self.i_obs = all_arrays.i_obs()
   self.sigmas = all_arrays.sigmas()
Example #16
0
 def list(self):
   for symbols in sgtbx.space_group_symbol_iterator():
     sgi = sgtbx.space_group_info(group=sgtbx.space_group(
       space_group_symbols=symbols))
     if self.comparator(sgi):
       if (self.chiral is None) or (self.chiral == sgi.group().is_chiral()):
         yield sgi
Example #17
0
def run():
  settings = [0]
  for i in xrange(1, 231): settings.append({})

  list_cb_op = []
  for xyz in ("x,y,z", "z,x,y", "y,z,x"):
    list_cb_op.append(sgtbx.change_of_basis_op(sgtbx.rt_mx(xyz)))

  n_built = 0
  for i in sgtbx.space_group_symbol_iterator():
    hall_symbol = i.hall()
    for z in "PABCIRHF":
      hall_z = hall_symbol[0] + z + hall_symbol[2:]
      for cb_op in list_cb_op:
        group = sgtbx.space_group(hall_z).change_basis(cb_op)
        sg_type = group.type()
        settings[sg_type.number()][sg_type.lookup_symbol()] = 0
        n_built += 1
  print "# n_built =", n_built

  n_non_redundant = 0
  print "settings = ("
  for i in xrange(1, 231):
    print "#", i
    symbols = settings[i].keys()
    symbols.sort()
    for s in symbols:
      print "'" + s + "',"
      n_non_redundant += 1
  print ")"
  print "# n_non_redundant =", n_non_redundant
def exercise_f000():
  miller_indices = flex.miller_index([(0,0,0)])
  data = flex.complex_double([1-2j])
  n_real = [1,2,3]
  conjugate_flag = True
  for hall_symbol in ["P 1", "P 3", "R 3*"]:
    for is_centric in [False, True]:
      if (not is_centric):
        space_group = sgtbx.space_group(hall_symbol)
      else:
        space_group.expand_smx("-x,-y,-z")
      for anomalous_flag in [False, True]:
        if (not anomalous_flag):
          rfft = fftpack.real_to_complex_3d(n_real)
          n_complex = rfft.n_complex()
        else:
          cfft = fftpack.complex_to_complex_3d(n_real)
          n_complex = cfft.n()
        for treat_restricted in [False, True]:
          map = maptbx.structure_factors.to_map(
            space_group=space_group,
            anomalous_flag=anomalous_flag,
            miller_indices=miller_indices,
            structure_factors=data,
            n_real=n_real,
            map_grid=flex.grid(n_complex),
            conjugate_flag=conjugate_flag,
            treat_restricted=treat_restricted)
          if (treat_restricted):
            assert approx_equal(
              map.complex_map()[0], data[0])
          else:
            assert approx_equal(
              map.complex_map()[0], data[0]*space_group.order_p())
Example #19
0
 def remove_lattice_translations(g):
   result = sgtbx.space_group(
     hall_symbol="P1", t_den=subgroup.t_den())
   for i_inv in xrange(g.f_inv()):
     for i_smx in xrange(g.n_smx()):
       result.expand_smx(g(0, i_inv, i_smx))
   return result
def exercise():
  ma = miller.array(
    miller.set(crystal.symmetry(unit_cell=(5,5,5, 90, 90, 90),
                                space_group=sgtbx.space_group('P 2x')),
               indices=flex.miller_index(
                 [(1,0,0), (0,1,0), (0,0,1),
                  (-1,0,0), (0,-1,0), (0,0,-1),
                  (1,1,0), (1,0,1), (0,1,1),
                  (-1,-1,0), (-1,0,-1), (0,-1,-1),
                  (1,-1,0), (1,0,-1), (0,1,-1),
                  (-1,1,0), (-1,0,1), (0,-1,1),
                  (1,1,1), (-1,1,1), (1,-1,1), (1,1,-1),
                  (-1,-1,-1), (1,-1,-1), (-1,1,-1), (-1,-1,1)])),
    data=flex.complex_double(flex.random_double(26), flex.random_double(26)))
  f_at_h = dict(zip(ma.indices(), ma.data()))
  for op in ("-x, y+1/2, -z", "x+1/2, -y, z-1/2"):
    op = sgtbx.rt_mx(op)
    original, transformed = ma.common_sets(
      ma.change_basis(sgtbx.change_of_basis_op(op.inverse())))
    for h, f in original:
      assert f == f_at_h[h]
    for h, op_f in transformed:
      assert approx_equal(
        op_f,
        f_at_h[h*op.r()]*exp(1j*2*pi*row(h).dot(col(op.t().as_double()))))
Example #21
0
def generate_table(complex_data, indices, numpy_args=False, anom=True):
    """

    :param complex_data: structure factors
    :param indices: miller indices in a list, Nx3
    :param numpy_args: are the complex data and indices numpy type, if not
        assume flex
    :param anom: return a miller array with +H and -H ?
    :return: dictionary whose keys are miller index tuple and values are structure fact
    """
    sg = sgtbx.space_group(" P 4nw 2abw")
    Symm = crystal.symmetry(unit_cell=(79, 79, 38, 90, 90, 90), space_group=sg)
    if numpy_args:
        assert type(indices) == tuple
        assert (type(indices[0]) == tuple)
        indices = flex.miller_index(indices)

    mil_set = miller.set(crystal_symmetry=Symm,
                         indices=indices,
                         anomalous_flag=anom)
    if numpy_args:
        complex_data = flex.complex_double(np.ascontiguousarray(complex_data))
    mil_ar = miller.array(mil_set, data=complex_data)

    mil_dict = {h: val for h, val in izip(mil_ar.indices(), mil_ar.data())}
    return mil_dict
Example #22
0
def to_crystal(filename):
  ''' Get the crystal model from the xparm file

  Params:
      filename The xparm/or integrate filename

  Return:
      The crystal model

  '''
  from rstbx.cftbx.coordinate_frame_converter import \
      coordinate_frame_converter
  from dxtbx.model.crystal import crystal_model
  from cctbx.sgtbx import space_group, space_group_symbols

  # Get the real space coordinate frame
  cfc = coordinate_frame_converter(filename)
  real_space_a = cfc.get('real_space_a')
  real_space_b = cfc.get('real_space_b')
  real_space_c = cfc.get('real_space_c')
  sg = cfc.get('space_group_number')
  space_group = space_group(space_group_symbols(sg).hall())
  mosaicity = cfc.get('mosaicity')

  # Return the crystal model
  return crystal_model(
      real_space_a=real_space_a,
      real_space_b=real_space_b,
      real_space_c=real_space_c,
      space_group=space_group,
      mosaicity=mosaicity)
Example #23
0
def anomalous_reflection_intensity_primitive_cell(space_group):
  assert space_group.n_ltr() == 1
  assert not space_group.is_centric()
  subgroup = sgtbx.space_group(space_group)
  subgroup.make_tidy()
  result = [subgroup]
  for s1 in space_group:
    assert s1.t().num() == (0,0,0)
    for s2 in space_group:
      subgroup = sgtbx.space_group()
      subgroup.expand_smx(s1)
      subgroup.expand_smx(s2)
      subgroup.make_tidy()
      if (not subgroup in result):
        result.append(subgroup)
  return result
def test_correct(space_group_symbol):

    sgi = sgtbx.space_group_info(space_group_symbol)
    cs = sgi.any_compatible_crystal_symmetry(volume=1000)
    ms = cs.build_miller_set(anomalous_flag=True, d_min=1).expand_to_p1()

    # the reciprocal matrix
    B = scitbx.matrix.sqr(cs.unit_cell().fractionalization_matrix()).transpose()
    crystal = Crystal(B, sgtbx.space_group())
    expts = ExperimentList([Experiment(crystal=crystal)])

    refl = flex.reflection_table()
    refl["miller_index"] = ms.indices()
    refl["rlp"] = B.elems * ms.indices().as_vec3_double()
    refl["imageset_id"] = flex.int(len(refl))
    refl["xyzobs.mm.value"] = flex.vec3_double(len(refl))

    non_primitive_basis.correct(expts, refl, assign_indices.AssignIndicesGlobal())

    cs_corrected = expts.crystals()[0].get_crystal_symmetry()
    assert cs_corrected.change_of_basis_op_to_primitive_setting().is_identity_op()
    assert (
        cs.change_of_basis_op_to_primitive_setting().apply(ms.indices())
        == refl["miller_index"]
    )
  def assemble_symops(self):
    t_den = self.sg_low.t_den()
    r_den = self.sg_low.r_den()

    # loop over all symops
    for item, symop in enumerate(self.symops):
      tmp_symops = []
      tmp_indices = []

      # multiply in the symop in the space group
      check_sg = sgtbx.space_group(self.sg_low)

      check_sg.expand_smx(symop.new_denominators(r_den, t_den))
      # Check if this SG is already in the list
      assert check_sg != self.sg_low
      if check_sg not in self.sg_groups:
        # add sg to list
        self.sg_groups.append(check_sg)
        tmp_symops.append(symop)
        tmp_indices.append(item)

        # check if the other symops generate the same sg please
        for check_item, check_op in enumerate(self.symops):
          if check_sg.contains(check_op.new_denominators(r_den,t_den)):
            # add symop to list if it is not in there yet
            if check_op not in tmp_symops:
              tmp_symops.append(check_op)
            # add index to list
            if check_item not in tmp_indices:
              tmp_indices.append(check_item)

        self.grouped_symops.append(tmp_symops)
        self.grouped_index.append(tmp_indices)
Example #26
0
 def compare_hall_symops_with_sgtbx(self, hall, existing_group=True):
     cctbx_sg = sgtbx.space_group(hall)
     cctbx_triplets = set(m.as_xyz() for m in cctbx_sg.all_ops(mod=1))
     gemmi_gops = gemmi.symops_from_hall(hall)
     self.assertEqual(len(gemmi_gops.sym_ops), cctbx_sg.order_p())
     self.assertEqual(len(gemmi_gops.cen_ops), cctbx_sg.n_ltr())
     self.assertEqual(len(gemmi_gops), cctbx_sg.order_z())
     self.assertEqual(gemmi_gops.is_centric(), cctbx_sg.is_centric())
     ctr = gemmi_gops.find_centering()
     self.assertEqual(ctr, cctbx_sg.conventional_centring_type_symbol())
     gemmi_triplets = set(m.triplet() for m in gemmi_gops)
     self.assertEqual(cctbx_triplets, gemmi_triplets)
     gemmi_sg = gemmi.find_spacegroup_by_ops(gemmi_gops)
     if existing_group:
         self.assertEqual(gemmi_sg.point_group_hm(),
                          cctbx_sg.point_group_type())
         self.assertEqual(gemmi_sg.crystal_system_str(),
                          cctbx_sg.crystal_system().lower())
         self.assertEqual(gemmi_sg.is_sohncke(), cctbx_sg.is_chiral())
         self.assertEqual(gemmi_sg.is_enantiomorphic(),
                          cctbx_sg.type().is_enantiomorphic())
         self.assertEqual(gemmi_sg.is_symmorphic(),
                          cctbx_sg.type().is_symmorphic())
         self.assertEqual(gemmi_sg.centring_type(), ctr)
     else:
         self.assertIsNone(gemmi_sg)
Example #27
0
    def reindex_old(self):
      self.set_executable(os.path.join(os.environ.get('CBIN', ''),
                                       'reindex'))
      self.check_hklin()
      self.check_hklout()

      if not self._spacegroup and not self._operator:
        raise RuntimeError, 'reindex requires spacegroup or operator'

      self.start()

      # look up the space group number to cope with complex symbols
      # that old fashioned CCP4 reindex does not understand...
      from cctbx.sgtbx import space_group, space_group_symbols
      sg_t = space_group(space_group_symbols(str(self._spacegroup))).type()

      if self._operator:
        self.input('reindex %s' % str(self._operator))
      if self._spacegroup:
        self.input('symmetry %d' % sg_t.number())
      self.close_wait()

      # check for errors

      try:
        self.check_for_errors()

      except RuntimeError, e:
        try:
          os.remove(self.get_hklout())
        except:
          pass

        raise e
Example #28
0
def reindex_experiments(experiments, cb_op, space_group=None):
    reindexed_experiments = copy.deepcopy(experiments)

    for crystal in reindexed_experiments.crystals():
        cryst_reindexed = copy.deepcopy(crystal)
        if space_group is not None:
            # See also https://github.com/cctbx/cctbx_project/issues/424
            cryst_reindexed.set_space_group(sgtbx.space_group("P 1"))
            cryst_reindexed = cryst_reindexed.change_basis(cb_op)
            cryst_reindexed.set_space_group(space_group)
            S = parameter_reduction.symmetrize_reduce_enlarge(
                cryst_reindexed.get_space_group()
            )
            S.set_orientation(cryst_reindexed.get_B())
            S.symmetrize()
            # Cache the scan-varying A matrices if applicable as these get lost
            # when we call crystal.set_B()
            A_varying = [
                cryst_reindexed.get_A_at_scan_point(i)
                for i in range(cryst_reindexed.num_scan_points)
            ]
            # Update the symmetrized B matrix
            cryst_reindexed.set_B(S.orientation.reciprocal_matrix())
            # Reapply the scan-varying A matrices
            cryst_reindexed.set_A_at_scan_points(A_varying)
        else:
            cryst_reindexed = cryst_reindexed.change_basis(cb_op)
        crystal.update(cryst_reindexed)

    return reindexed_experiments
Example #29
0
def test_symmetry_handler_c2_i2(crystal_symmetry):
    cs_ref = crystal_symmetry.as_reference_setting()
    cs_ref = cs_ref.change_basis(
        cs_ref.change_of_basis_op_to_best_cell(best_monoclinic_beta=False)
    )
    cs_best = cs_ref.best_cell()
    # best -> ref is different to cs_ref above
    cs_best_ref = cs_best.as_reference_setting()
    assert not cs_ref.is_similar_symmetry(cs_best_ref)

    B = scitbx.matrix.sqr(
        crystal_symmetry.unit_cell().fractionalization_matrix()
    ).transpose()
    cryst = Crystal(B, sgtbx.space_group())

    for cs in (crystal_symmetry, cs_ref, cs_best):
        print(cs)
        handler = symmetry.SymmetryHandler(space_group=cs.space_group())
        new_cryst, cb_op = handler.apply_symmetry(cryst)
        assert (
            new_cryst.change_basis(cb_op).get_crystal_symmetry().is_similar_symmetry(cs)
        )

    for cs in (crystal_symmetry, cs_ref, cs_best, cs_best_ref):
        print(cs)
        handler = symmetry.SymmetryHandler(
            unit_cell=cs.unit_cell(), space_group=cs.space_group()
        )
        new_cryst, cb_op = handler.apply_symmetry(cryst)
        assert (
            new_cryst.change_basis(cb_op).get_crystal_symmetry().is_similar_symmetry(cs)
        )
Example #30
0
def exercise_generator_set():
    sgi = sgtbx.space_group_info('P1')
    sg_generator_set = sgtbx.any_generator_set(sgi.group())
    assert sg_generator_set.non_primitive_generators == ()

    sgi = sgtbx.space_group_info('P21')
    sg_generator_set = sgtbx.any_generator_set(sgi.group())
    assert (list(map(
        str, sg_generator_set.non_primitive_generators)) == ['-x,y+1/2,-z'])

    sgi = sgtbx.space_group_info('Pmmm')
    sg_generator_set = sgtbx.any_generator_set(sgi.group())
    assert (list(map(str, sg_generator_set.non_primitive_generators)) == [
        '-x,-y,-z', 'x,-y,-z', '-x,y,-z'
    ])

    for i in range(1, 231):
        sgi = sgtbx.space_group_info(number=i)
        sg = sgi.group()
        sg_gen = sgtbx.any_generator_set(sg)
        if sg.z2p_op().is_identity_op():
            assert sg_gen.non_primitive_generators == sg_gen.primitive_generators

    for i in range(1, 231):
        sgi = sgtbx.space_group_info(number=i)
        sg = sgi.group()
        sg_gen = sgtbx.any_generator_set(sg)
        sg1 = sgtbx.space_group("P1")
        for op in sg_gen.non_primitive_generators:
            sg1.expand_smx(op)
        for t in sg.ltr():
            sg1.expand_ltr(t)
        assert sg1.type().number() == sg.type().number()
Example #31
0
 def test_table(self):
     for sg in gemmi.spacegroup_table():
         if sg.ccp4 != 0:
             self.assertEqual(sg.ccp4 % 1000, sg.number)
         if sg.operations().is_centric():
             self.assertEqual(sg.laue_str(), sg.point_group_hm())
         else:
             self.assertNotEqual(sg.laue_str(), sg.point_group_hm())
         if sgtbx:
             hall = sg.hall.encode()
             cctbx_sg = sgtbx.space_group(hall)
             cctbx_info = sgtbx.space_group_info(group=cctbx_sg)
             self.assertEqual(sg.is_reference_setting(),
                              cctbx_info.is_reference_setting())
             #to_ref = cctbx_info.change_of_basis_op_to_reference_setting()
             #from_ref = '%s' % cob_to_ref.inverse().c()
             c2p_sg = gemmi.Op(cctbx_sg.z2p_op().c().inverse().as_xyz())
             self.assertEqual(sg.centred_to_primitive(), c2p_sg)
         ops = gemmi.get_spacegroup_reference_setting(sg.number).operations()
         ops.change_basis_forward(sg.basisop)
         self.assertEqual(ops, sg.operations())
     itb = gemmi.spacegroup_table_itb()
     if sgtbx:
         for s in sgtbx.space_group_symbol_iterator():
             self.assertEqual(s.hall().strip(), next(itb).hall)
         with self.assertRaises(StopIteration):
             next(itb)
Example #32
0
def map_sites_to_asu(spacegroup, pdb_in, pdb_out, invert=False):
    '''Map sites to asu of input spacegroup (as sites from shelxd claim
    P1 in CRYST1 record) inverting if necessary. N.B. if inverting sites
    also need to invert spacegroup.'''

    from cctbx.crystal import symmetry, direct_space_asu
    from iotbx.pdb import hierarchy
    from scitbx.array_family import flex

    sg = space_group(space_group_symbols(spacegroup).hall())
    coords = hierarchy.input(file_name=pdb_in)
    cs = coords.input.crystal_symmetry()
    uc = cs.unit_cell()
    cs2 = symmetry(unit_cell=uc, space_group=sg)
    xs = coords.xray_structure_simple().customized_copy(crystal_symmetry=cs2)

    if invert:
        xs = xs.change_hand()

    am = xs.crystal_symmetry().asu_mappings(0.0)
    xyz = xs.sites_cart()
    am.process_sites_cart(xyz)
    xyz = flex.vec3_double()
    for m in am.mappings():
        xyz.append(m[0].mapped_site())
    xs.set_sites_cart(xyz)

    open(pdb_out, 'w').write(xs.as_pdb_file())

    return
Example #33
0
def modify_ins_text(_ins_text, _spacegroup, _nsites, _rlimit):
    '''Update the text in a SHELXD .ins file to handle the correct number
    of sites and spacegroup symmetry operations.'''

    new_text = []

    symm = [
        op.as_xyz().upper()
        for op in space_group(space_group_symbols(_spacegroup).hall()).smx()
    ]

    for record in _ins_text:
        if 'SYMM' in record:
            if not symm:
                continue
            for op in symm:
                if op == 'X,Y,Z':
                    continue
                new_text.append(('SYMM %s' % op))
            symm = None
        elif 'FIND' in record:
            new_text.append(('FIND %d' % _nsites))
        elif 'SHEL' in record:
            new_text.append(('SHEL 999 %.1f' % _rlimit))
        else:
            new_text.append(record.strip())

    return new_text
Example #34
0
 def __init__(self, file_name, header_only=False):
   self.file_name = os.path.normpath(file_name)
   f = open(file_name)
   line = f.readline()
   assert line[5] == " "
   n_sym_ops_from_file = int(line[:5].strip())
   assert n_sym_ops_from_file > 0
   self.space_group_symbol = line[6:].strip()
   self.space_group_from_ops = sgtbx.space_group()
   for i in range(n_sym_ops_from_file):
     line = f.readline().rstrip()
     assert len(line) == 27
     r = sgtbx.rot_mx([int(line[j*3:(j+1)*3]) for j in range(9)], 1)
     line = f.readline().rstrip()
     assert len(line) == 9
     t = sgtbx.tr_vec([int(line[j*3:(j+1)*3]) for j in range(3)], 12)
     self.space_group_from_ops.expand_smx(sgtbx.rt_mx(r, t))
   f.close()
   if (header_only):
     self.original_indices = None
     return
   all_arrays = scalepack_ext.no_merge_original_index_arrays(
     file_name, n_sym_ops_from_file*2+1)
   self.original_indices = all_arrays.original_indices()
   self.unique_indices = all_arrays.unique_indices()
   self.batch_numbers = all_arrays.batch_numbers()
   self.centric_tags = all_arrays.centric_tags()
   self.spindle_flags = all_arrays.spindle_flags()
   self.asymmetric_unit_indices = all_arrays.asymmetric_unit_indices()
   self.i_obs = all_arrays.i_obs()
   self.sigmas = all_arrays.sigmas()
    def cosym(self):
        logger.debug("Running cosym analysis")
        cosym = DialsCosym()
        auto_logfiler(cosym)

        experiments_filename = self._data_manager.export_experiments("tmp.expt")
        reflections_filename = self._data_manager.export_reflections("tmp.refl")
        cosym.add_experiments_json(experiments_filename)
        cosym.add_reflections_file(reflections_filename)
        if self._params.symmetry.space_group is not None:
            cosym.set_space_group(self._params.symmetry.space_group.group())
        cosym.run()
        self._cosym_analysis = cosym.get_cosym_analysis()
        self._experiments_filename = cosym.get_reindexed_experiments()
        self._reflections_filename = cosym.get_reindexed_reflections()
        self._data_manager.experiments = load.experiment_list(
            self._experiments_filename, check_format=False
        )
        self._data_manager.reflections = flex.reflection_table.from_file(
            self._reflections_filename
        )

        if self._params.symmetry.space_group is None:
            best_solution = cosym.get_best_solution()
            best_space_group = sgtbx.space_group(
                str(best_solution["patterson_group"])
            ).build_derived_acentric_group()
            self._params.symmetry.space_group = best_space_group.info()
            logger.info(
                "Space group determined by dials.cosym: %s" % best_space_group.info()
            )

        return
def run(server_info, inp, status):
  print "<pre>"

  symbols_inp = None
  lookup_symbol = inp.sgsymbol
  if (lookup_symbol == ""): lookup_symbol = "P 1"
  if (inp.convention == "Hall"):
    hall_symbol = lookup_symbol
  else:
    symbols_inp = sgtbx.space_group_symbols(lookup_symbol, inp.convention)
    hall_symbol = symbols_inp.hall()
    if (symbols_inp.number() == 0):
      symbols_inp = None
      inp.convention = "Hall"
    else:
      print "Result of symbol lookup:"
      show_symbols(symbols_inp)
      print

  try:
    ps = sgtbx.parse_string(hall_symbol)
    sg = sgtbx.space_group(ps)
  except RuntimeError, e:
    print "--&gt;" + ps.string() + "&lt;--"
    print ("-" * (ps.where() + 3)) + "^"
    raise
  def generate_reflections(self):

    # Build a mock scan for a 3 degree sweep
    from dxtbx.model.scan import scan_factory
    sf = scan_factory()
    self.scan = sf.make_scan(image_range = (1,1),
                          exposure_times = 0.1,
                          oscillation = (0, 3.0),
                          epochs = range(1),
                          deg = True)
    sweep_range = self.scan.get_oscillation_range(deg=False)

    # Create a scans ExperimentList, only for generating reflections
    experiments = ExperimentList()
    experiments.append(Experiment(
          beam=self.beam, detector=self.detector, goniometer=self.gonio, scan=self.scan,
          crystal=self.crystal, imageset=None))

    # Create a ScansRayPredictor
    ray_predictor = ScansRayPredictor(experiments, sweep_range)

    # Generate rays - only to work out which hkls are predicted
    resolution = 2.0
    index_generator = IndexGenerator(self.crystal.get_unit_cell(),
                          space_group(space_group_symbols(1).hall()).type(),
                          resolution)
    indices = index_generator.to_array()
    rays = ray_predictor.predict(indices)

    # Make a standard reflection_table and copy in the ray data
    self.reflections = flex.reflection_table.empty_standard(len(rays))
    self.reflections.update(rays)

    return
Example #38
0
def ref_gen_static(experiments):
    """Generate some reflections using the static predictor"""

    beam = experiments[0].beam
    crystal = experiments[0].crystal
    detector = experiments[0].detector
    scan = experiments[0].scan

    # All indices to the detector max resolution
    dmin = detector.get_max_resolution(beam.get_s0())
    index_generator = IndexGenerator(
        crystal.get_unit_cell(), space_group(space_group_symbols(1).hall()).type(), dmin
    )
    indices = index_generator.to_array()

    # Predict rays within the sequence range
    sequence_range = scan.get_oscillation_range(deg=False)
    ray_predictor = ScansRayPredictor(experiments, sequence_range)
    refs = ray_predictor(indices)

    # Take only those rays that intersect the detector
    intersects = ray_intersection(detector, refs)
    refs = refs.select(intersects)

    # Make a reflection predictor and re-predict for these reflections. The
    # result is the same, but we gain also the flags and xyzcal.px columns
    ref_predictor = ScansExperimentsPredictor(experiments)
    refs["id"] = flex.int(len(refs), 0)
    refs = ref_predictor(refs)

    return refs
def mock_cif():
    """Mock a cif file for testing loading data from a cif."""
    cif = Mock()
    cif.intensities = flex.double([1.0, 1.0])
    cif.indices = flex.miller_index([(1, 0, 0), (0, 0, 1)])
    cif.space_group = space_group("C 2y")
    return cif
Example #40
0
 def remove_lattice_translations(g):
     result = sgtbx.space_group(hall_symbol="P1",
                                t_den=subgroup.t_den())
     for i_inv in range(g.f_inv()):
         for i_smx in range(g.n_smx()):
             result.expand_smx(g(0, i_inv, i_smx))
     return result
 def __init__(self, with_special_position_pivot):
     self.with_special_position_pivot = with_special_position_pivot
     self.uc = uctbx.unit_cell((1, 2, 3))
     self.sg = sgtbx.space_group("P 6")
     self.c0 = xray.scatterer("C0", site=(1e-5, 0., 0.1))
     self.site_symm = sgtbx.site_symmetry(self.uc, self.sg, self.c0.site)
     self.c0.flags.set_grad_site(True)
     self.c1 = xray.scatterer("C1", site=(0.09, 0.11, 0.))
     self.c1.flags.set_grad_site(True)
     self.h = xray.scatterer("H")
     self.reparam = constraints.ext.reparametrisation(self.uc)
     if with_special_position_pivot:
         x0 = self.reparam.add(constraints.special_position_site_parameter,
                               self.site_symm, self.c0)
     else:
         x0 = self.reparam.add(constraints.independent_site_parameter,
                               self.c0)
     x1 = self.reparam.add(constraints.independent_site_parameter, self.c1)
     l = self.reparam.add(constraints.independent_scalar_parameter,
                          self.bond_length,
                          variable=False)
     x_h = self.reparam.add(constraints.terminal_linear_ch_site,
                            pivot=x0,
                            pivot_neighbour=x1,
                            length=l,
                            hydrogen=self.h)
     self.reparam.finalise()
     self.x0, self.x1, self.x_h, self.l = [
         x.index for x in (x0, x1, x_h, l)
     ]
     if self.with_special_position_pivot:
         self.y0 = x0.independent_params.index
def exercise_expand():
  sg = sgtbx.space_group("P 41 (1,-1,0)")
  h = flex.miller_index(((3,1,-2), (1,-2,0)))
  assert tuple(sg.is_centric(h)) == (0, 1)
  p1 = miller.expand_to_p1_iselection(
    space_group=sg, anomalous_flag=False, indices=h, build_iselection=False)
  p1_i0 = ((-3,-1,2), (-1, 3,2),(3,1,2),(1,-3,2),(1,-2, 0),(2,1,0))
  assert tuple(p1.indices) == p1_i0
  assert p1.iselection.size() == 0
  p1 = miller.expand_to_p1_iselection(
    space_group=sg, anomalous_flag=True, indices=h, build_iselection=False)
  assert tuple(p1.indices) \
      == ((3,1,-2), (1,-3,-2), (-3,-1,-2), (-1,3,-2),
          (1,-2,0), (-2,-1,0), (-1,2,0), (2,1,0))
  p1 = miller.expand_to_p1_iselection(
    space_group=sg, anomalous_flag=False, indices=h, build_iselection=True)
  assert tuple(p1.indices) == p1_i0
  assert tuple(p1.iselection) == (0,0,0,0,1,1)
  a = flex.double((1,2))
  p = flex.double((10,90))
  p1 = miller.expand_to_p1_phases(
    space_group=sg, anomalous_flag=False, indices=h, data=p, deg=True)
  assert approx_equal(tuple(p1.data), (-10,110,110,-10, 90,30))
  p1 = miller.expand_to_p1_phases(
    space_group=sg, anomalous_flag=True, indices=h, data=p, deg=True)
  assert approx_equal(tuple(p1.data), (10,-110,-110,10, 90,-30,-90,30))
  p = flex.double([x * math.pi/180 for x in p])
  v = [x * math.pi/180 for x in p1.data]
  p1 = miller.expand_to_p1_phases(
    space_group=sg, anomalous_flag=True, indices=h, data=p, deg=False)
  assert approx_equal(tuple(p1.data), v)
  f = flex.polar(a, p)
  p1 = miller.expand_to_p1_complex(
    space_group=sg, anomalous_flag=True, indices=h, data=f)
  assert approx_equal(tuple(flex.abs(p1.data)), (1,1,1,1,2,2,2,2))
  assert approx_equal(tuple(flex.arg(p1.data)), v)
  hl = flex.hendrickson_lattman([(1,2,3,4), (5,6,7,8)])
  p1 = miller.expand_to_p1_hendrickson_lattman(
    space_group=sg, anomalous_flag=True, indices=h, data=hl)
  assert approx_equal(p1.data, [
    [1,2,3,4],
    [1.232051,-1.866025,-4.964102,0.5980762],
    [1.232051,-1.866025,-4.964102,0.5980762],
    [1,2,3,4],
    [5,6,7,8],
    [2.696152,-7.330127,-10.4282,2.062178],
    [-5,-6,7,8],
    [7.696152,-1.330127,3.428203,-10.06218]])
  b = flex.bool([True,False])
  p1 = miller.expand_to_p1_iselection(
    space_group=sg, anomalous_flag=True, indices=h, build_iselection=True)
  assert b.select(p1.iselection).all_eq(
    flex.bool([True, True, True, True, False, False, False, False]))
  i = flex.int([13,17])
  p1 = miller.expand_to_p1_iselection(
    space_group=sg, anomalous_flag=True, indices=h, build_iselection=True)
  assert i.select(p1.iselection).all_eq(flex.int([13,13,13,13,17,17,17,17]))
  #
  assert approx_equal(miller.statistical_mean(sg, False, h, a), 4/3.)
  assert approx_equal(miller.statistical_mean(sg, True, h, a), 3/2.)
Example #43
0
def run():
  for space_group_symbol in ("P-1",
                             "P2/m",
                             "C2/m",
                             "Pmmm",
                             "Cmmm",
                             "Fmmm",
                             "Immm",
                             "P4/mmm",
                             "I4/mmm",
                             "R-3m",
                             "P6/mmm",
                             "Pm-3m",
                             "Im-3m",
                             "Fm-3m"):
    centric_info = sgtbx.space_group_info(space_group_symbol)
    non_centric = sgtbx.space_group()
    for i_ltr in xrange(centric_info.group().n_ltr()):
      for i_smx in xrange(centric_info.group().n_smx()):
        s = centric_info.group()(i_ltr,0,i_smx)
        non_centric.expand_smx(s)
    assert non_centric.f_inv() == 1
    assert non_centric.order_z() * 2 == centric_info.group().order_z()
    non_centric_info = sgtbx.space_group_info(group=non_centric)
    centric_stats = subgroup_stats(centric_info)
    non_centric_stats = subgroup_stats(non_centric_info)
    assert len(centric_stats.subgroups) >= 2*len(non_centric_stats.subgroups)
    assert centric_stats.n_non_centric >= non_centric_stats.n_non_centric
    assert centric_stats.n_chiral == non_centric_stats.n_chiral
    assert non_centric_stats.n_non_centric == len(non_centric_stats.subgroups)
    assert non_centric_stats.n_non_centric == non_centric_stats.n_chiral
  print "OK"
Example #44
0
 def subgroups_table(d):
     header = (
         "Patterson group",
         "",
         "Likelihood",
         "NetZcc",
         "Zcc+",
         "Zcc-",
         "delta",
         "Reindex operator",
     )
     rows = [header]
     for score in d["subgroup_scores"]:
         rows.append((
             str(
                 sgtbx.space_group(
                     hall_symbol=str(score["patterson_group"])).info()),
             score["stars"],
             f"{score['likelihood']:.3f}",
             f"{score['z_cc_net']: .2f}",
             f"{score['z_cc_for']: .2f}",
             f"{score['z_cc_against']: .2f}",
             f"{score['max_angular_difference']:.1f}",
             str(sgtbx.change_of_basis_op(str(score["cb_op"]))),
         ))
     return rows
def exercise_generator_set():
  sgi = sgtbx.space_group_info('P1')
  sg_generator_set = sgtbx.any_generator_set(sgi.group())
  assert sg_generator_set.non_primitive_generators == ()

  sgi = sgtbx.space_group_info('P21')
  sg_generator_set = sgtbx.any_generator_set(sgi.group())
  assert (map(str, sg_generator_set.non_primitive_generators)
          == ['-x,y+1/2,-z'])

  sgi = sgtbx.space_group_info('Pmmm')
  sg_generator_set = sgtbx.any_generator_set(sgi.group())
  assert (map(str, sg_generator_set.non_primitive_generators)
          == ['-x,-y,-z', 'x,-y,-z', '-x,y,-z'])

  for i in xrange(1, 231):
    sgi = sgtbx.space_group_info(number=i)
    sg = sgi.group()
    sg_gen = sgtbx.any_generator_set(sg)
    if sg.z2p_op().is_identity_op():
      assert sg_gen.non_primitive_generators == sg_gen.primitive_generators

  for i in xrange(1, 231):
    sgi = sgtbx.space_group_info(number=i)
    sg = sgi.group()
    sg_gen = sgtbx.any_generator_set(sg)
    sg1 = sgtbx.space_group("P1")
    for op in sg_gen.non_primitive_generators:
      sg1.expand_smx(op)
    for t in sg.ltr():
        sg1.expand_ltr(t)
    assert sg1.type().number() == sg.type().number()
Example #46
0
def ref_gen_static(experiments):
  """Generate some reflections using the static predictor"""

  beam = experiments[0].beam
  crystal = experiments[0].crystal
  goniometer = experiments[0].goniometer
  detector = experiments[0].detector
  scan = experiments[0].scan

  # All indices to the detector max resolution
  dmin = detector.get_max_resolution(beam.get_s0())
  index_generator = IndexGenerator(crystal.get_unit_cell(),
                  space_group(space_group_symbols(1).hall()).type(), dmin)
  indices = index_generator.to_array()

  # Predict rays within the sweep range
  sweep_range = scan.get_oscillation_range(deg=False)
  ray_predictor = ScansRayPredictor(experiments, sweep_range)
  refs = ray_predictor(indices)

  # Take only those rays that intersect the detector
  intersects = ray_intersection(detector, refs)
  refs = refs.select(intersects)

  # Make a reflection predictor and re-predict for these reflections. The
  # result is the same, but we gain also the flags and xyzcal.px columns
  ref_predictor = ExperimentsPredictor(experiments)
  refs['id'] = flex.int(len(refs), 0)
  refs = ref_predictor(refs)

  return refs
Example #47
0
        def set_correct_lattice(self, lattice):
            """In a rerunning situation, set the correct lattice, which will
            assert a correct lauegroup based on the previous run of the
            program..."""

            if self._lattice_to_laue == {}:
                raise RuntimeError("no lattice to lauegroup mapping")

            if lattice not in self._lattice_to_laue:
                raise RuntimeError("lattice %s not possible" % lattice)
            self._input_laue_group = self._lattice_to_laue[lattice]

            with open(self._json, "rb") as f:
                d = json.load(f)
            for soln in d["subgroup_scores"]:
                patterson_group = sgtbx.space_group(
                    str(soln["patterson_group"]))
                if PhilIndex.params.xia2.settings.symmetry.chirality in (
                        None,
                        "chiral",
                ):
                    patterson_group = patterson_group.build_derived_acentric_group(
                    )

                if patterson_group == self._input_laue_group:
                    # set this as correct solution
                    self.set_best_solution(d, soln)
                    break
Example #48
0
def run(server_info, inp, status):
    print "<pre>"

    symbols_inp = None
    lookup_symbol = inp.sgsymbol
    if (lookup_symbol == ""): lookup_symbol = "P 1"
    if (inp.convention == "Hall"):
        hall_symbol = lookup_symbol
    else:
        symbols_inp = sgtbx.space_group_symbols(lookup_symbol, inp.convention)
        hall_symbol = symbols_inp.hall()
        if (symbols_inp.number() == 0):
            symbols_inp = None
            inp.convention = "Hall"
        else:
            print "Result of symbol lookup:"
            show_symbols(symbols_inp)
            print

    try:
        ps = sgtbx.parse_string(hall_symbol)
        sg = sgtbx.space_group(ps)
    except RuntimeError, e:
        print "--&gt;" + ps.string() + "&lt;--"
        print("-" * (ps.where() + 3)) + "^"
        raise
Example #49
0
def load_sfall(fname):
    """
    special script for loading the structure factor file generated in main()
    :param fname: file generated in the main method above.. 
    :return: mil_ar, energies
        mil_ar: dict of miller arrays (complex) 
        energies: array of xray energies in electron volts
        such that  mil_ar[0] is Fhkl at energy energies[0]
    """

    f = h5py.File(fname, "r")
    data = f["data"][()]
    indices = f["indices"][()]
    hall = f["hall_symbol"][()]
    ucell_param = f["ucell_tuple"][()]
    energies = f["energies"][()]
    sg = sgtbx.space_group(hall)
    Symm = crystal.symmetry(unit_cell=ucell_param, space_group=sg)
    indices_flex = tuple(map(tuple, indices))
    mil_idx = flex.miller_index(indices_flex)
    mil_set = miller.set(crystal_symmetry=Symm,
                         indices=mil_idx,
                         anomalous_flag=True)

    mil_ar = {}  # load a dict of "sfall at each energy"
    for i_chan, data_chan in enumerate(data):
        data_flex = flex.complex_double(np.ascontiguousarray(data_chan))
        mil_ar[i_chan] = miller.array(mil_set, data=data_flex)

    return mil_ar, energies
Example #50
0
def combine_symops_and_symbol(space_group_from_ops, space_group_symbol):
    space_group_symbol = space_group_symbol.replace(" ", "").upper()
    z = space_group_symbol[:1]
    if ("PABCIFRH".find(z) < 0):
        raise RuntimeError(
            "Cannot determine lattice centring type given space group symbol"
            " %s" % show_string(space_group_symbol))
    if (z == "P"):
        return sgtbx.space_group_info(group=space_group_from_ops)
    if (z == "H"):
        space_group_symbol = "R" + space_group_symbol[1:] + ":H"
        z = "R"
    elif (z == "R" and not space_group_symbol.endswith(":H")):
        if (space_group_symbol.endswith(":R")):
            z = None
        else:
            for s in space_group_from_ops:
                r_info = s.r().info()
                if (abs(r_info.type()) == 3):
                    if (r_info.ev() == (0, 0, 1)):
                        space_group_symbol = "R" + space_group_symbol[1:] + ":H"
                        break
                    elif (r_info.ev() == (1, 1, 1)):
                        space_group_symbol += ":R"
                        z = None
                        break
    space_group_exp = sgtbx.space_group(space_group_from_ops)
    if (z is not None):
        try:
            space_group_exp.expand_conventional_centring_type(z)
        except RuntimeError:
            space_group_exp = None
    if (space_group_exp is not None):
        try:
            space_group_from_symbol = sgtbx.space_group_info(
                symbol=space_group_symbol).group()
        except RuntimeError:
            space_group_from_symbol = None
    if (space_group_exp is None or space_group_from_symbol is None
            or space_group_exp != space_group_from_symbol):
        if space_group_from_symbol:
            warnings.warn(
                """
WARNING:
  Symmetry operations in input file are for space group %(space_group_exp)s
  However space group symbol is: %(space_group_symbol)s
  This may be a format error in the Scalepack file!
  Using %(space_group_symbol)s
""" % {
                    "space_group_exp": str(space_group_exp.info()),
                    "space_group_symbol": show_string(space_group_symbol),
                },
                UserWarning,
                stacklevel=10)
            space_group_exp = space_group_from_symbol
        else:
            raise RuntimeError(
                "Symmetry operations in unmerged SCALEPACK file incompatible with"
                " space group symbol %s" % show_string(space_group_symbol))
    return sgtbx.space_group_info(group=space_group_exp)
    def _export_experiments_reflections(self, experiments, reflections,
                                        result):
        from dxtbx.serialize import dump
        from rstbx.symmetry.constraints import parameter_reduction

        reindexed_experiments = copy.deepcopy(experiments)
        reindexed_reflections = flex.reflection_table()
        cb_op_inp_best = (result.best_solution.subgroup["cb_op_inp_best"] *
                          result.cb_op_inp_min)
        best_subsym = result.best_solution.subgroup["best_subsym"]
        for i, expt in enumerate(reindexed_experiments):
            expt.crystal = expt.crystal.change_basis(result.cb_op_inp_min)
            expt.crystal.set_space_group(sgtbx.space_group("P 1"))
            expt.crystal = expt.crystal.change_basis(
                result.best_solution.subgroup["cb_op_inp_best"])
            expt.crystal.set_space_group(
                best_subsym.space_group().build_derived_acentric_group())
            S = parameter_reduction.symmetrize_reduce_enlarge(
                expt.crystal.get_space_group())
            S.set_orientation(expt.crystal.get_B())
            S.symmetrize()
            expt.crystal.set_B(S.orientation.reciprocal_matrix())
            reindexed_refl = copy.deepcopy(reflections[i])
            reindexed_refl["miller_index"] = cb_op_inp_best.apply(
                reindexed_refl["miller_index"])
            reindexed_reflections.extend(reindexed_refl)
        logger.info("Saving reindexed experiments to %s" %
                    self._params.output.experiments)
        dump.experiment_list(reindexed_experiments,
                             self._params.output.experiments)
        logger.info(
            "Saving %s reindexed reflections to %s" %
            (len(reindexed_reflections), self._params.output.reflections))
        reindexed_reflections.as_file(self._params.output.reflections)
def combine_symops_and_symbol(space_group_from_ops, space_group_symbol):
  space_group_symbol = space_group_symbol.replace(" ","").upper()
  z = space_group_symbol[:1]
  if ("PABCIFRH".find(z) < 0):
    raise RuntimeError(
      "Cannot determine lattice centring type given space group symbol"
      " %s" % show_string(space_group_symbol))
  if (z == "P"):
    return sgtbx.space_group_info(group=space_group_from_ops)
  if (z == "H"):
    space_group_symbol = "R" + space_group_symbol[1:] + ":H"
    z = "R"
  elif (z == "R" and not space_group_symbol.endswith(":H")):
    if (space_group_symbol.endswith(":R")):
      z = None
    else:
      for s in space_group_from_ops:
        r_info = s.r().info()
        if (abs(r_info.type()) == 3):
          if (r_info.ev() == (0,0,1)):
            space_group_symbol = "R" + space_group_symbol[1:] + ":H"
            break
          elif (r_info.ev() == (1,1,1)):
            space_group_symbol += ":R"
            z = None
            break
  space_group_exp = sgtbx.space_group(space_group_from_ops)
  if (z is not None):
    try:
      space_group_exp.expand_conventional_centring_type(z)
    except RuntimeError:
      space_group_exp = None
  if (space_group_exp is not None):
    try:
      space_group_from_symbol = sgtbx.space_group_info(
        symbol=space_group_symbol).group()
    except RuntimeError:
      space_group_from_symbol = None
  if (   space_group_exp is None
      or space_group_from_symbol is None
      or space_group_exp != space_group_from_symbol):
    if space_group_from_symbol:
      warnings.warn("""
WARNING:
  Symmetry operations in input file are for space group %(space_group_exp)s
  However space group symbol is: %(space_group_symbol)s
  This may be a format error in the Scalepack file!
  Using %(space_group_symbol)s
""" % {"space_group_exp" : str(space_group_exp.info()),
       "space_group_symbol" : show_string(space_group_symbol), },
        UserWarning, stacklevel=10)
      space_group_exp = space_group_from_symbol
    else:
      raise RuntimeError(
      "Symmetry operations in unmerged SCALEPACK file incompatible with"
      " space group symbol %s"
        % show_string(space_group_symbol))
  return sgtbx.space_group_info(group=space_group_exp)
Example #53
0
def run(args):
  if (len(args) != 2):
    raise Usage("""\
cctbx.python space_subgroups.py max_index space_group_symbol
  Example: cctbx.python space_subgroups.py 2 P41212""")
  #
  max_index = int(args[0])
  print "max_index:", max_index
  assert max_index >= 1
  print
  space_group_t_den = 144
  sginfo = sgtbx.space_group_info(
    symbol=args[1], space_group_t_den=space_group_t_den)
  sginfo.show_summary()
  print
  cb_op_to_p = sginfo.change_of_basis_op_to_primitive_setting()
  sginfo_p = sginfo.change_basis(cb_op=cb_op_to_p)
  if (sginfo_p.group() != sginfo.group()):
    print "Primitive setting:"
    sginfo_p.show_summary()
    print
  #
  all_subgroups = dict_with_default_0()
  sg_p = sginfo_p.group()
  sg_p_a = sg_p.build_derived_acentric_group()
  if (sg_p.is_centric()):
    inv_mx = sg_p(0, 1, 0).t()
  else:
    inv_mx = None
  for symx1 in sg_p_a:
    subgr1 = sgtbx.space_group(hall_symbol="P1", t_den=space_group_t_den)
    subgr1.expand_smx(symx1)
    for symx2 in sg_p_a:
      subgr2 = sgtbx.space_group(subgr1)
      subgr2.expand_smx(symx2)
      loop_over_super_cells(
        max_index=max_index, all_subgroups=all_subgroups, subgroup=subgr2)
      if (inv_mx is not None):
        subgr3 = sgtbx.space_group(subgr2)
        subgr3.expand_inv(inv_mx)
        loop_over_super_cells(
          max_index=max_index, all_subgroups=all_subgroups, subgroup=subgr3)
  #
  show_sorted_by_counts(label_count_pairs=all_subgroups.items())
Example #54
0
def main(filenames, map_file, npoints=192, max_resolution=6, reverse_phi=False):
    rec_range = 1 / max_resolution

    image = ImageFactory(filenames[0])
    panel = image.get_detector()[0]
    beam = image.get_beam()
    s0 = beam.get_s0()
    pixel_size = panel.get_pixel_size()
    
    xlim, ylim = image.get_raw_data().all()
    
    xy = recviewer.get_target_pixels(panel, s0, xlim, ylim, max_resolution)
    
    s1 = panel.get_lab_coord(xy * pixel_size[0]) # FIXME: assumed square pixel
    s1 = s1 / s1.norms() * (1 / beam.get_wavelength()) # / is not supported...
    S = s1 - s0
    
    grid = flex.double(flex.grid(npoints, npoints, npoints), 0)
    cnts = flex.int(flex.grid(npoints, npoints, npoints), 0)
    
    for filename in filenames:
        print "Processing image", filename
        try:
            fill_voxels(ImageFactory(filename), grid, cnts, S, xy, reverse_phi, rec_range)
        except:
            print " Failed to process. Skipped this."
        
    recviewer.normalize_voxels(grid, cnts)
    
    uc = uctbx.unit_cell((npoints, npoints, npoints, 90, 90, 90))
    ccp4_map.write_ccp4_map(map_file, uc, sgtbx.space_group("P1"), 
                            (0, 0, 0), grid.all(), grid, 
                            flex.std_string(["cctbx.miller.fft_map"]))
    return
    from scitbx import fftpack
    fft = fftpack.complex_to_complex_3d(grid.all())
    grid_complex = flex.complex_double(
                            reals=flex.pow2(grid),
                            imags=flex.double(grid.size(), 0))
    grid_transformed = flex.abs(fft.backward(grid_complex))
    print flex.max(grid_transformed), flex.min(grid_transformed), grid_transformed.all()
    ccp4_map.write_ccp4_map(map_file, uc, sgtbx.space_group("P1"), 
                            (0, 0, 0), grid.all(), grid_transformed,
                            flex.std_string(["cctbx.miller.fft_map"]))
Example #55
0
def is_centred(space_group_number):
  '''Test if space group # corresponds to a centred space group.'''

  sg_hall = sgtbx.space_group_symbols(space_group_number).hall()
  sg = sgtbx.space_group(sg_hall)

  if (sg.n_ltr() - 1):
    return True

  return False
Example #56
0
    def save_CIF(self, fpath):
        """Saving model into cif file"""
     
        cif_object = model.cif()
        cif_block = model.block()
        cif_object["BEA"] = cif_block
        space_group = sgtbx.space_group(self.iucr_structure.space_group())

        #unit cell:
        cell_pars = self.iucr_structure.unit_cell().parameters()

        cif_block["_cell_length_a"] = cell_pars[0]
        cif_block["_cell_length_b"] = cell_pars[1]
        cif_block["_cell_length_c"] = cell_pars[2]
        cif_block["_cell_angle_alpha"] = cell_pars[3]
        cif_block["_cell_angle_beta"] = cell_pars[4]
        cif_block["_cell_angle_gamma"] = cell_pars[5]

        space_group_type = self.iucr_structure.space_group_info().type()
        cif_block["_symmetry_cell_setting"] = \
                                    space_group.crystal_system().lower()
        cif_block["_symmetry_Int_Tables_number"] = space_group_type.number()
        cif_block["_symmetry_space_group_name_H-M"] = \
                                        space_group_type.lookup_symbol()
        #cif_block["_space_group.name_Hall"] = space_group_type.hall_symbol()

        symop_loop = model.loop(
            header = ("_symmetry_equiv_pos_as_xyz",)
                            )
        for symop_id, symop in enumerate(space_group):
            symop_loop.add_row(("'{}'".format(symop.as_xyz()),))

        struct_loop = model.loop(
            header = ("_atom_site_label",
                    "_atom_site_type_symbol",
                    "_atom_site_fract_x",
                    "_atom_site_fract_y",
                    "_atom_site_fract_z",
                    "_atom_site_U_iso_or_equiv"))

        for scatterer in self.iucr_structure.scatterers():
            struct_loop.add_row(
                        (scatterer.label,
                        scatterer.scattering_type,
                        scatterer.site[0],
                        scatterer.site[1],
                        scatterer.site[2],
                        scatterer.u_iso))
                        
    
        cif_block.add_loop(symop_loop)
        cif_block.add_loop(struct_loop)
        
        with open(fpath,'w') as fobj:
            fobj.write(cif_object.__str__())
Example #57
0
 def browse(self):
   for self.symbol in sgtbx.space_group_symbol_iterator():
     self.sg = sgtbx.space_group(self.symbol.hall()).make_tidy()
     self.z2p_op = self.sg.z2p_op()
     self.sg_p = self.sg.change_basis(self.z2p_op)
     self.on_new_space_group()
     for self.op in self.sg_p:
       self.rot_info = self.op.r().info()
       self.tr_info = sgtbx.translation_part_info(self.op)
       if self.tr_info.origin_shift().is_zero(): continue
       self.on_new_symmetry()
Example #58
0
def symopSymList(sgNr):
    """For a S.G. Returns list of symmetry operations in symbolic form"""
    sg_hall = sgtbx.space_group_symbols(sgNr).hall()
    sg = sgtbx.space_group(sg_hall)
    print "\nGENERATING LIST OF SYMMETRY OPERATIONS FOR S.G. %d..." % (sgNr)
    symop_list = []
    sg_order = sg.order_z()
    for i in range(0, sg_order):
        symop_list.append(sg(i).as_xyz())
    print "A LIST OF %d SYMMETRY OPERATIONS WAS CREATED!\n" % (sg_order)
    return symop_list