def exercise_match_bijvoet_mates(): h0 = flex.miller_index(((1,2,3), (-1,-2,-3), (2,3,4), (-2,-3,-4), (3,4,5))) d0 = flex.double((1,2,3,4,5)) bm = miller.match_bijvoet_mates( sgtbx.space_group_type(), h0) bm = miller.match_bijvoet_mates( sgtbx.reciprocal_space_asu(sgtbx.space_group_type()), h0) bm = miller.match_bijvoet_mates( h0) assert tuple(bm.pairs()) == ((0,1), (2,3)) assert tuple(bm.singles("+")) == (4,) assert tuple(bm.singles("-")) == () assert bm.n_singles() != 0 assert tuple(bm.pairs_hemisphere_selection("+")) == (0, 2) assert tuple(bm.pairs_hemisphere_selection("-")) == (1, 3) assert tuple(bm.singles_hemisphere_selection("+")) == (4,) assert tuple(bm.singles_hemisphere_selection("-")) == () assert tuple(bm.miller_indices_in_hemisphere("+")) == ((1,2,3), (2,3,4)) assert tuple(bm.miller_indices_in_hemisphere("-")) == ((-1,-2,-3),(-2,-3,-4)) assert approx_equal(tuple(bm.minus(d0)), (-1, -1)) assert approx_equal(tuple(bm.additive_sigmas(d0)), [math.sqrt(x*x+y*y) for x,y in ((1,2), (3,4))]) assert approx_equal(tuple(bm.average(d0)), (3/2., 7/2.)) h0.append((1,2,3)) try: miller.match_bijvoet_mates(h0) except Exception: pass else: raise Exception_expected
def exercise_asu(): sg_type = sgtbx.space_group_type("P 41") asu = sgtbx.reciprocal_space_asu(sg_type) miller_indices = flex.miller_index(((1, 2, 3), (3, 5, 0))) for h in miller_indices: h_eq = miller.sym_equiv_indices(sg_type.group(), h) for i_eq in xrange(h_eq.multiplicity(False)): h_i = h_eq(i_eq) for anomalous_flag in (False, True): a = miller.asym_index(sg_type.group(), asu, h_i.h()) assert a.h() == h o = a.one_column(anomalous_flag) assert o.i_column() == 0 t = a.two_column(anomalous_flag) assert t.h() == h assert (o.h() != h) == (t.i_column() == 1) assert not anomalous_flag or (t.i_column() != 0) == h_i.friedel_flag() assert anomalous_flag or t.i_column() == 0 miller.map_to_asu(sg_type, False, miller_indices) data = flex.double((0, 0)) miller.map_to_asu(sg_type, False, miller_indices, data) miller.map_to_asu(sg_type, False, miller_indices, data, False) miller.map_to_asu(sg_type, False, miller_indices, data, True) data = flex.complex_double((0, 0)) miller.map_to_asu(sg_type, False, miller_indices, data) data = flex.hendrickson_lattman(((1, 2, 3, 4), (2, 3, 4, 5))) miller.map_to_asu(sg_type, False, miller_indices, data) for sg_symbol in ("P 41", "P 31 1 2"): exercise_map_to_asu(sg_symbol) # sg_type = sgtbx.space_group_type("P 2") miller_indices = flex.miller_index(((1, 2, 3), (-1, -2, -3))) assert not miller.is_unique_set_under_symmetry( space_group_type=sg_type, anomalous_flag=False, miller_indices=miller_indices) assert miller.is_unique_set_under_symmetry(space_group_type=sg_type, anomalous_flag=True, miller_indices=miller_indices) assert list( miller.unique_under_symmetry_selection( space_group_type=sg_type, anomalous_flag=False, miller_indices=miller_indices)) == [0] assert list( miller.unique_under_symmetry_selection( space_group_type=sg_type, anomalous_flag=True, miller_indices=miller_indices)) == [0, 1]
def exercise_asu(): sg_type = sgtbx.space_group_type("P 41") asu = sgtbx.reciprocal_space_asu(sg_type) miller_indices = flex.miller_index(((1,2,3), (3,5,0))) for h in miller_indices: h_eq = miller.sym_equiv_indices(sg_type.group(), h) for i_eq in xrange(h_eq.multiplicity(False)): h_i = h_eq(i_eq) for anomalous_flag in (False,True): a = miller.asym_index(sg_type.group(), asu, h_i.h()) assert a.h() == h o = a.one_column(anomalous_flag) assert o.i_column() == 0 t = a.two_column(anomalous_flag) assert t.h() == h assert (o.h() != h) == (t.i_column() == 1) assert not anomalous_flag or (t.i_column() != 0) == h_i.friedel_flag() assert anomalous_flag or t.i_column() == 0 miller.map_to_asu(sg_type, False, miller_indices) data = flex.double((0,0)) miller.map_to_asu(sg_type, False, miller_indices, data) miller.map_to_asu(sg_type, False, miller_indices, data, False) miller.map_to_asu(sg_type, False, miller_indices, data, True) data = flex.complex_double((0,0)) miller.map_to_asu(sg_type, False, miller_indices, data) data = flex.hendrickson_lattman(((1,2,3,4),(2,3,4,5))) miller.map_to_asu(sg_type, False, miller_indices, data) for sg_symbol in ("P 41", "P 31 1 2"): exercise_map_to_asu(sg_symbol) # sg_type = sgtbx.space_group_type("P 2") miller_indices = flex.miller_index(((1,2,3), (-1,-2,-3))) assert not miller.is_unique_set_under_symmetry( space_group_type=sg_type, anomalous_flag=False, miller_indices=miller_indices) assert miller.is_unique_set_under_symmetry( space_group_type=sg_type, anomalous_flag=True, miller_indices=miller_indices) assert list(miller.unique_under_symmetry_selection( space_group_type=sg_type, anomalous_flag=False, miller_indices=miller_indices)) == [0] assert list(miller.unique_under_symmetry_selection( space_group_type=sg_type, anomalous_flag=True, miller_indices=miller_indices)) == [0,1]
def read_pointless_xml(pointless_xml_file): """Read through the pointless xml output, return as a list of spacegroup numbers in order of likelihood, corresponding to the pointgroup of the data.""" dom = xml.dom.minidom.parse(pointless_xml_file) scorelist = dom.getElementsByTagName("LaueGroupScoreList")[0] scores = scorelist.getElementsByTagName("LaueGroupScore") results = [] for s in scores: lauegroup = str( s.getElementsByTagName("LaueGroupName") [0].childNodes[0].data).strip() if lauegroup[0] == "H": lauegroup = "R%s" % lauegroup[1:] pointgroup = (sgtbx.space_group_type( lauegroup).group().build_derived_acentric_group().type().number()) netzc = float(s.getElementsByTagName("NetZCC")[0].childNodes[0].data) # record this as a possible lattice... if it's Z score # is positive, anyway - except this does kinda bias towards # those lattices which have all symops => no Z-. lattice = lauegroup_to_lattice(lauegroup) if netzc >= 0.0: results.append((lattice, pointgroup)) return results
def loop_over_super_cells(max_index, all_subgroups, subgroup): assert subgroup.n_ltr() == 1 for ia in xrange(1,max_index+1): for ib in xrange(1,max_index+1): for ic in xrange(1,max_index+1): cb_op = sgtbx.change_of_basis_op("x/%d,y/%d,z/%d" % (ia,ib,ic)) try: scsubgroup = subgroup.change_basis(cb_op=cb_op) except RuntimeError, e: if (str(e).endswith( "Unsuitable value for rational rotation matrix.")): all_subgroups["incompatible_rotation_denominator"] += 1 elif (str(e).endswith( "Unsuitable value for rational translation vector.")): all_subgroups["incompatible_translation_denominator"] += 1 else: raise RuntimeError else: 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 subsubgroup = remove_lattice_translations(scsubgroup) uhm = sgtbx.space_group_type(group=subsubgroup) \ .universal_hermann_mauguin_symbol() all_subgroups[uhm] += 1
def exercise_map_to_asu(sg_symbol): sg_type = sgtbx.space_group_type(sg_symbol) index_abs_range = (4,4,4) for anomalous_flag in (False,True): m = miller.index_generator( sg_type, anomalous_flag, index_abs_range).to_array() a = flex.double() p = flex.double() c = flex.hendrickson_lattman() for i in xrange(m.size()): a.append(random.random()) p.append(random.random() * 2) c.append([random.random() for j in xrange(4)]) f = flex.polar(a, p) p = [p, p*(180/math.pi)] m_random = flex.miller_index() p_random = [flex.double(), flex.double()] c_random = flex.hendrickson_lattman() f_random = flex.complex_double() for i,h_asym in enumerate(m): h_eq = miller.sym_equiv_indices(sg_type.group(), h_asym) i_eq = random.randrange(h_eq.multiplicity(anomalous_flag)) h_i = h_eq(i_eq) m_random.append(h_i.h()) for deg in (False,True): p_random[deg].append(h_i.phase_eq(p[deg][i], deg)) f_random.append(h_i.complex_eq(f[i])) c_random.append(h_i.hendrickson_lattman_eq(c[i])) m_random_copy = m_random.deep_copy() miller.map_to_asu(sg_type, anomalous_flag, m_random_copy) for i,h_asym in enumerate(m): assert h_asym == m_random_copy[i] m_random_copy = m_random.deep_copy() miller.map_to_asu(sg_type, anomalous_flag, m_random_copy, f_random) for i,h_asym in enumerate(m): assert h_asym == m_random_copy[i] for i,f_asym in enumerate(f): assert abs(f_asym - f_random[i]) < 1.e-6 m_random_copy = m_random.deep_copy() a_random = a.deep_copy() miller.map_to_asu(sg_type, anomalous_flag, m_random_copy, a_random) for i,h_asym in enumerate(m): assert h_asym == m_random_copy[i] for i,a_asym in enumerate(a): assert a_asym == a_random[i] for deg in (False,True): m_random_copy = m_random.deep_copy() miller.map_to_asu( sg_type, anomalous_flag, m_random_copy, p_random[deg], deg) for i,h_asym in enumerate(m): assert h_asym == m_random_copy[i] for i,p_asym in enumerate(p[deg]): assert scitbx.math.phase_error(p_asym, p_random[deg][i], deg) < 1.e-5 m_random_copy = m_random.deep_copy() miller.map_to_asu(sg_type, anomalous_flag, m_random_copy, c_random) for i,h_asym in enumerate(m): assert h_asym == m_random_copy[i] for i,c_asym in enumerate(c): for j in xrange(4): assert abs(c_asym[j] - c_random[i][j]) < 1.e-5
def loop_over_super_cells(max_index, all_subgroups, subgroup): assert subgroup.n_ltr() == 1 for ia in range(1, max_index + 1): for ib in range(1, max_index + 1): for ic in range(1, max_index + 1): cb_op = sgtbx.change_of_basis_op("x/%d,y/%d,z/%d" % (ia, ib, ic)) try: scsubgroup = subgroup.change_basis(cb_op=cb_op) except RuntimeError as e: if (str(e).endswith( "Unsuitable value for rational rotation matrix.")): all_subgroups["incompatible_rotation_denominator"] += 1 elif (str(e).endswith( "Unsuitable value for rational translation vector." )): all_subgroups[ "incompatible_translation_denominator"] += 1 else: raise RuntimeError else: 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 subsubgroup = remove_lattice_translations(scsubgroup) uhm = sgtbx.space_group_type(group=subsubgroup) \ .universal_hermann_mauguin_symbol() all_subgroups[uhm] += 1
def exercise_map_to_asu(sg_symbol): sg_type = sgtbx.space_group_type(sg_symbol) index_abs_range = (4,4,4) for anomalous_flag in (False,True): m = miller.index_generator( sg_type, anomalous_flag, index_abs_range).to_array() a = flex.double() p = flex.double() c = flex.hendrickson_lattman() for i in range(m.size()): a.append(random.random()) p.append(random.random() * 2) c.append([random.random() for j in range(4)]) f = flex.polar(a, p) p = [p, p*(180/math.pi)] m_random = flex.miller_index() p_random = [flex.double(), flex.double()] c_random = flex.hendrickson_lattman() f_random = flex.complex_double() for i,h_asym in enumerate(m): h_eq = miller.sym_equiv_indices(sg_type.group(), h_asym) i_eq = random.randrange(h_eq.multiplicity(anomalous_flag)) h_i = h_eq(i_eq) m_random.append(h_i.h()) for deg in (False,True): p_random[deg].append(h_i.phase_eq(p[deg][i], deg)) f_random.append(h_i.complex_eq(f[i])) c_random.append(h_i.hendrickson_lattman_eq(c[i])) m_random_copy = m_random.deep_copy() miller.map_to_asu(sg_type, anomalous_flag, m_random_copy) for i,h_asym in enumerate(m): assert h_asym == m_random_copy[i] m_random_copy = m_random.deep_copy() miller.map_to_asu(sg_type, anomalous_flag, m_random_copy, f_random) for i,h_asym in enumerate(m): assert h_asym == m_random_copy[i] for i,f_asym in enumerate(f): assert abs(f_asym - f_random[i]) < 1.e-6 m_random_copy = m_random.deep_copy() a_random = a.deep_copy() miller.map_to_asu(sg_type, anomalous_flag, m_random_copy, a_random) for i,h_asym in enumerate(m): assert h_asym == m_random_copy[i] for i,a_asym in enumerate(a): assert a_asym == a_random[i] for deg in (False,True): m_random_copy = m_random.deep_copy() miller.map_to_asu( sg_type, anomalous_flag, m_random_copy, p_random[deg], deg) for i,h_asym in enumerate(m): assert h_asym == m_random_copy[i] for i,p_asym in enumerate(p[deg]): assert scitbx.math.phase_error(p_asym, p_random[deg][i], deg) < 1.e-5 m_random_copy = m_random.deep_copy() miller.map_to_asu(sg_type, anomalous_flag, m_random_copy, c_random) for i,h_asym in enumerate(m): assert h_asym == m_random_copy[i] for i,c_asym in enumerate(c): for j in range(4): assert abs(c_asym[j] - c_random[i][j]) < 1.e-5
def read_pointless_xml(pointless_xml_file): '''Read through the pointless xml output, return as a list of spacegroup numbers in order of likelihood, corresponding to the pointgroup of the data.''' dom = xml.dom.minidom.parse(pointless_xml_file) best = dom.getElementsByTagName('BestSolution')[0] pointgroup = best.getElementsByTagName( 'GroupName')[0].childNodes[0].data confidence = float(best.getElementsByTagName( 'Confidence')[0].childNodes[0].data) totalprob = float(best.getElementsByTagName( 'TotalProb')[0].childNodes[0].data) reindex_matrix = map(float, best.getElementsByTagName( 'ReindexMatrix')[0].childNodes[0].data.split()) reindex_operator = best.getElementsByTagName( 'ReindexOperator')[0].childNodes[0].data.strip() scorelist = dom.getElementsByTagName('LaueGroupScoreList')[0] scores = scorelist.getElementsByTagName('LaueGroupScore') results = [] for s in scores: number = int(s.getElementsByTagName( 'number')[0].childNodes[0].data) lauegroup = str(s.getElementsByTagName( 'LaueGroupName')[0].childNodes[0].data).strip() if lauegroup[0] == 'H': if version == 2: try: lauegroup = 'R%s' % lauegroup[1:] except: pass else: lauegroup = 'R{}'.format(lauegroup[1:]) pointgroup = sgtbx.space_group_type(lauegroup).group( ).build_derived_acentric_group().type().number() reindex = s.getElementsByTagName( 'ReindexOperator')[0].childNodes[0].data netzc = float(s.getElementsByTagName( 'NetZCC')[0].childNodes[0].data) likelihood = float(s.getElementsByTagName( 'Likelihood')[0].childNodes[0].data) r_merge = float(s.getElementsByTagName( 'R')[0].childNodes[0].data) delta = float(s.getElementsByTagName( 'CellDelta')[0].childNodes[0].data) # record this as a possible lattice... if it's Z score # is positive, anyway - except this does kinda bias towards # those lattices which have all symops => no Z-. lattice = lauegroup_to_lattice(lauegroup) if netzc >= 0.0: results.append((lattice, pointgroup)) return results
def compare_ccp4_and_sgtbx(syminfo_data): for s in sgtbx.space_group_symbol_iterator(): sg = sgtbx.space_group(s.hall()) sg_type = sgtbx.space_group_type(sg) asu = sgtbx.reciprocal_space_asu(sg_type) sgtbx_hklasu = asu.reference_as_string().replace('==', '=') ccp4_hklasu = syminfo_data[s.number()] assert sgtbx_hklasu == ccp4_hklasu assert sgtbx_hklasu in hklasu_strings
def exercise_index_generator(): uc = uctbx.unit_cell((11, 11, 13, 90, 90, 120)) sg_type = sgtbx.space_group_type("P 3 1 2") for anomalous_flag in (False, True): mig = miller.index_generator(uc, sg_type, anomalous_flag, 8) assert mig.unit_cell().is_similar_to(uc) assert mig.space_group_type().group() == sg_type.group() assert mig.anomalous_flag() == anomalous_flag assert mig.asu().reference_as_string( ) == "h>=k and k>=0 and (k>0 or l>=0)" assert mig.next() == (0, 0, 1) if (not anomalous_flag): assert tuple(mig.to_array()) == ((1, 0, 0), ) else: assert tuple(mig.to_array()) == ((1, 0, 0), (-1, 0, 0)) assert tuple(miller.index_generator(uc, sg_type, False, 8)) \ == ((0,0,1), (1, 0, 0)) index_abs_range = (4, 4, 4) for sg_symbol in ("P 31 1 2", "P 31 2 1"): sg_type = sgtbx.space_group_type(sg_symbol) for anomalous_flag in (False, True): miller_indices = miller.index_generator(sg_type, anomalous_flag, index_abs_range) miller_dict = {} for h in miller_indices: miller_dict[h] = 0 sg = sg_type.group() h = [0, 0, 0] for h[0] in range(-index_abs_range[0], index_abs_range[0] + 1): for h[1] in range(-index_abs_range[1], index_abs_range[1] + 1): for h[2] in range(-index_abs_range[2], index_abs_range[2] + 1): if (sg.is_sys_absent(h) or h == [0, 0, 0]): continue h_eq = miller.sym_equiv_indices(sg, h) found_h_asu = 0 for i_eq in xrange(h_eq.multiplicity(anomalous_flag)): h_i = h_eq(i_eq).h() if (h_i in miller_dict): assert found_h_asu == 0 found_h_asu = 1 assert found_h_asu != 0
def get_space_group_type_from_xparm(handle): """Get the space group tyoe object from an xparm file handle Params: handle The file handle Returns: The space group type object """ from cctbx import sgtbx return sgtbx.space_group_type(sgtbx.space_group( sgtbx.space_group_symbols(handle.space_group).hall()))
def exercise_index_generator(): uc = uctbx.unit_cell((11,11,13,90,90,120)) sg_type = sgtbx.space_group_type("P 3 1 2") for anomalous_flag in (False,True): mig = miller.index_generator(uc, sg_type, anomalous_flag, 8) assert mig.unit_cell().is_similar_to(uc) assert mig.space_group_type().group() == sg_type.group() assert mig.anomalous_flag() == anomalous_flag assert mig.asu().reference_as_string() == "h>=k and k>=0 and (k>0 or l>=0)" assert mig.next() == (0,0,1) if (not anomalous_flag): assert tuple(mig.to_array()) == ((1, 0, 0),) else: assert tuple(mig.to_array()) == ((1, 0, 0), (-1, 0, 0)) assert tuple(miller.index_generator(uc, sg_type, False, 8)) \ == ((0,0,1), (1, 0, 0)) index_abs_range = (4,4,4) for sg_symbol in ("P 31 1 2", "P 31 2 1"): sg_type = sgtbx.space_group_type(sg_symbol) for anomalous_flag in (False,True): miller_indices = miller.index_generator( sg_type, anomalous_flag, index_abs_range) miller_dict = {} for h in miller_indices: miller_dict[h] = 0 sg = sg_type.group() h = [0,0,0] for h[0] in range(-index_abs_range[0], index_abs_range[0]+1): for h[1] in range(-index_abs_range[1], index_abs_range[1]+1): for h[2] in range(-index_abs_range[2], index_abs_range[2]+1): if (sg.is_sys_absent(h) or h == [0,0,0]): continue h_eq = miller.sym_equiv_indices(sg, h) found_h_asu = 0 for i_eq in xrange(h_eq.multiplicity(anomalous_flag)): h_i = h_eq(i_eq).h() if (h_i in miller_dict): assert found_h_asu == 0 found_h_asu = 1 assert found_h_asu != 0
def generate_indices(cell, spgr, dmin=1.0, ret='index'): """http://cci.lbl.gov/cctbx_sources/cctbx/miller/index_generator.h""" dmin = dmin-0.0000000000001 # because resolution_limit is < and not <= anomalous_flag = False symm = make_symmetry(cell, spgr) unit_cell = uctbx.unit_cell(cell) sg_type = space_group_type(spgr) # input hkl or resolution(d_min) mig = index_generator( unit_cell, sg_type, anomalous_flag=anomalous_flag, resolution_limit=dmin) indices = mig.to_array() if ret == 'index': # suitable for df index return indices else: return miller.array(miller.set(crystal_symmetry=symm, indices=indices, anomalous_flag=anomalous_flag))
def generate_indices(cell, spgr, dmin=1.0, ret='index'): """http://cci.lbl.gov/cctbx_sources/cctbx/miller/index_generator.h""" dmin = dmin - 0.0000000000001 # because resolution_limit is < and not <= anomalous_flag = False symm = make_symmetry(cell, spgr) unit_cell = uctbx.unit_cell(cell) sg_type = space_group_type(spgr) # input hkl or resolution(d_min) mig = index_generator(unit_cell, sg_type, anomalous_flag=anomalous_flag, resolution_limit=dmin) indices = mig.to_array() if ret == 'index': # suitable for df index return indices else: return miller.array( miller.set(crystal_symmetry=symm, indices=indices, anomalous_flag=anomalous_flag))
def _make_cctbx_args(sg_string): return { 'sg_type': sgtbx.space_group_type(sg_string), 'uctbx_unit_cell': uctbx.unit_cell, 'miller_index_generator': miller.index_generator }
def exercise_bins(): uc = uctbx.unit_cell((11,11,13,90,90,120)) sg_type = sgtbx.space_group_type("P 3 2 1") anomalous_flag = False d_min = 1 m = miller.index_generator(uc, sg_type, anomalous_flag, d_min).to_array() f = flex.double() for i in range(m.size()): f.append(random.random()) n_bins = 10 b = miller.binning(uc, n_bins, 0, d_min) b = miller.binning(uc, n_bins, 0, d_min, 1.e-6) b = miller.binning(uc, n_bins, m) b = miller.binning(uc, n_bins, m, 0) b = miller.binning(uc, n_bins, m, 0, d_min) b = miller.binning(uc, n_bins, m, 0, d_min, 1.e-6) assert b.d_max() == -1 assert approx_equal(b.d_min(), d_min) assert b.bin_d_range(0) == (-1,-1) assert approx_equal(b.bin_d_range(1), (-1,2.1544336)) assert approx_equal(b.bin_d_range(b.n_bins_all()-1), (1,-1)) d_star_sq = 0.5 r = b.bin_d_range(b.get_i_bin(d_star_sq)) d = 1/math.sqrt(d_star_sq) assert r[1] <= d <= r[0] h = (3,4,5) r = b.bin_d_range(b.get_i_bin(h)) assert r[1] <= uc.d(h) <= r[0] # a quick test to excercise d-spacings on fractional Miller indices: assert approx_equal( uc.d((3,4,5)), uc.d_frac((3.001,4,5)), eps=0.001) binning1 = miller.binning(uc, n_bins, m) assert binning1.unit_cell().is_similar_to(uc) assert binning1.n_bins_used() == n_bins assert binning1.limits().size() == n_bins + 1 assert binning1.n_bins_all() == n_bins + 2 s = pickle.dumps(binning1) l = pickle.loads(s) assert str(l.unit_cell()) == "(11, 11, 13, 90, 90, 120)" assert approx_equal(l.limits(), binning1.limits()) # binner1 = miller.ext.binner(binning1, m) assert binner1.miller_indices().id() == m.id() assert binner1.count(binner1.i_bin_d_too_large()) == 0 assert binner1.count(binner1.i_bin_d_too_small()) == 0 counts = binner1.counts() for i_bin in binner1.range_all(): assert binner1.count(i_bin) == counts[i_bin] assert binner1.selection(i_bin).count(True) == counts[i_bin] assert list(binner1.range_all()) == list(range(binner1.n_bins_all())) assert list(binner1.range_used()) == list(range(1, binner1.n_bins_used()+1)) binning2 = miller.binning(uc, n_bins - 2, binning1.bin_d_min(2), binning1.bin_d_min(n_bins)) binner2 = miller.ext.binner(binning2, m) assert tuple(binner1.counts())[1:-1] == tuple(binner2.counts()) array_indices = flex.size_t(range(m.size())) perm_array_indices1 = flex.size_t() perm_array_indices2 = flex.size_t() for i_bin in binner1.range_all(): perm_array_indices1.extend(array_indices.select(binner1.selection(i_bin))) perm_array_indices2.extend(binner1.array_indices(i_bin)) assert perm_array_indices1.size() == m.size() assert perm_array_indices2.size() == m.size() assert tuple(perm_array_indices1) == tuple(perm_array_indices2) b = miller.ext.binner(miller.binning(uc, n_bins, m, 0, d_min), m) assert approx_equal(b.bin_centers(1), (0.23207956, 0.52448148, 0.62711856, 0.70311998, 0.7652538, 0.818567, 0.86566877, 0.90811134, 0.94690405, 0.98274518)) assert approx_equal(b.bin_centers(2), (0.10772184, 0.27871961, 0.39506823, 0.49551249, 0.58642261, 0.67067026, 0.74987684, 0.82507452, 0.89697271, 0.96608584)) assert approx_equal(b.bin_centers(3), (0.050000075, 0.15000023, 0.25000038, 0.35000053, 0.45000068, 0.55000083, 0.65000098, 0.75000113, 0.85000128, 0.95000143)) v = flex.double(range(b.n_bins_used())) i = b.interpolate(v, 0) for i_bin in b.range_used(): assert i.select(b.selection(i_bin)).all_eq(v[i_bin-1]) dss = uc.d_star_sq(m) for d_star_power in (1,2,3): j = b.interpolate(v, d_star_power) x = flex.pow(dss, (d_star_power/2.)) r = flex.linear_correlation(x, j) assert r.is_well_defined() assert approx_equal( r.coefficient(), (0.946401,0.990764,1.0)[d_star_power-1], eps=1.e-4, multiplier=None) # s = pickle.dumps(binner2) l = pickle.loads(s) assert str(l.unit_cell()) == "(11, 11, 13, 90, 90, 120)" assert approx_equal(l.limits(), binner2.limits()) assert l.miller_indices().all_eq(binner2.miller_indices()) assert l.bin_indices().all_eq(binner2.bin_indices()) # limits = flex.random_double(size=10) bng = miller.binning(uc, limits) assert bng.unit_cell().is_similar_to(uc) assert approx_equal(bng.limits(), limits)
def get_output(self): result = 'Crystal: %s\n' % self._name if self._aa_sequence: result += 'Sequence: %s\n' % self._aa_sequence.get_sequence() for wavelength in self._wavelengths.keys(): result += self._wavelengths[wavelength].get_output() scaler = self._get_scaler() if scaler.get_scaler_finish_done(): for wname, xwav in self._wavelengths.iteritems(): for xsweep in xwav.get_sweeps(): idxr = xsweep._get_indexer() if PhilIndex.params.xia2.settings.show_template: result += '%s\n' %banner('Autoindexing %s (%s)' %( idxr.get_indexer_sweep_name(), idxr.get_template())) else: result += '%s\n' %banner( 'Autoindexing %s' %idxr.get_indexer_sweep_name()) result += '%s\n' %idxr.show_indexer_solutions() intgr = xsweep._get_integrater() if PhilIndex.params.xia2.settings.show_template: result += '%s\n' %banner('Integrating %s (%s)' %( intgr.get_integrater_sweep_name(), intgr.get_template())) else: result += '%s\n' %banner( 'Integrating %s' %intgr.get_integrater_sweep_name()) result += '%s\n' % intgr.show_per_image_statistics() result += '%s\n' %banner('Scaling %s' %self.get_name()) for (dname, sname), (limit, suggested) in scaler.get_scaler_resolution_limits().iteritems(): if suggested is None or limit == suggested: result += 'Resolution limit for %s/%s: %5.2f\n' %(dname, sname, limit) else: result += 'Resolution limit for %s/%s: %5.2f (%5.2f suggested)\n' %(dname, sname, limit, suggested) # this is now deprecated - be explicit in what you are # asking for... reflections_all = self.get_scaled_merged_reflections() statistics_all = self._get_scaler().get_scaler_statistics() # print some of these statistics, perhaps? for key in statistics_all.keys(): result += format_statistics(statistics_all[key], caption='For %s/%s/%s' % key) # then print out some "derived" information based on the # scaling - this is presented through the Scaler interface # explicitly... cell = self._get_scaler().get_scaler_cell() cell_esd = self._get_scaler().get_scaler_cell_esd() spacegroups = self._get_scaler().get_scaler_likely_spacegroups() spacegroup = spacegroups[0] resolution = self._get_scaler().get_scaler_highest_resolution() from cctbx import sgtbx sg = sgtbx.space_group_type(str(spacegroup)) spacegroup = sg.lookup_symbol() CIF.set_spacegroup(sg) mmCIF.set_spacegroup(sg) if len(self._wavelengths) == 1: CIF.set_wavelengths([w.get_wavelength() for w in self._wavelengths.itervalues()]) mmCIF.set_wavelengths([w.get_wavelength() for w in self._wavelengths.itervalues()]) else: for wavelength in self._wavelengths.keys(): full_wave_name = '%s_%s_%s' % (self._project._name, self._name, wavelength) CIF.get_block(full_wave_name)['_diffrn_radiation_wavelength'] = \ self._wavelengths[wavelength].get_wavelength() mmCIF.get_block(full_wave_name)['_diffrn_radiation_wavelength'] = \ self._wavelengths[wavelength].get_wavelength() CIF.set_wavelengths({name: wave.get_wavelength() for name, wave in self._wavelengths.iteritems()}) mmCIF.set_wavelengths({name: wave.get_wavelength() for name, wave in self._wavelengths.iteritems()}) result += 'Assuming spacegroup: %s\n' % spacegroup if len(spacegroups) > 1: result += 'Other likely alternatives are:\n' for sg in spacegroups[1:]: result += '%s\n' % sg if cell_esd: from libtbx.utils import format_float_with_standard_uncertainty def match_formatting(dimA, dimB): def conditional_split(s): return (s[:s.index('.')],s[s.index('.'):]) if '.' in s else (s, '') A, B = conditional_split(dimA), conditional_split(dimB) maxlen = (max(len(A[0]), len(B[0])), max(len(A[1]), len(B[1]))) return ( A[0].rjust(maxlen[0])+A[1].ljust(maxlen[1]), B[0].rjust(maxlen[0])+B[1].ljust(maxlen[1]) ) formatted_cell_esds = tuple(format_float_with_standard_uncertainty(v, sd) for v, sd in zip(cell, cell_esd)) formatted_rows = (formatted_cell_esds[0:3], formatted_cell_esds[3:6]) formatted_rows = zip(*(match_formatting(l, a) for l, a in zip(*formatted_rows))) result += 'Unit cell (with estimated std devs):\n' result += '%s %s %s\n%s %s %s\n' % (formatted_rows[0] + formatted_rows[1]) else: result += 'Unit cell:\n' result += '%7.3f %7.3f %7.3f\n%7.3f %7.3f %7.3f\n' % tuple(cell) # now, use this information and the sequence (if provided) # and also matthews_coef (should I be using this directly, here?) # to compute a likely number of molecules in the ASU and also # the solvent content... if self._aa_sequence: residues = self._aa_sequence.get_sequence() if residues: nres = len(residues) # first compute the number of molecules using the K&R # method nmol = compute_nmol(cell[0], cell[1], cell[2], cell[3], cell[4], cell[5], spacegroup, resolution, nres) # then compute the solvent fraction solvent = compute_solvent(cell[0], cell[1], cell[2], cell[3], cell[4], cell[5], spacegroup, nmol, nres) result += 'Likely number of molecules in ASU: %d\n' % nmol result += 'Giving solvent fraction: %4.2f\n' % solvent self._nmol = nmol if type(reflections_all) == type({}): for format in reflections_all.keys(): result += '%s format:\n' % format reflections = reflections_all[format] if type(reflections) == type({}): for wavelength in reflections.keys(): target = FileHandler.get_data_file( reflections[wavelength]) result += 'Scaled reflections (%s): %s\n' % \ (wavelength, target) else: target = FileHandler.get_data_file( reflections) result += 'Scaled reflections: %s\n' % target CIF.write_cif() mmCIF.write_cif() return result
def exercise_bins(): uc = uctbx.unit_cell((11,11,13,90,90,120)) sg_type = sgtbx.space_group_type("P 3 2 1") anomalous_flag = False d_min = 1 m = miller.index_generator(uc, sg_type, anomalous_flag, d_min).to_array() f = flex.double() for i in xrange(m.size()): f.append(random.random()) n_bins = 10 b = miller.binning(uc, n_bins, 0, d_min) b = miller.binning(uc, n_bins, 0, d_min, 1.e-6) b = miller.binning(uc, n_bins, m) b = miller.binning(uc, n_bins, m, 0) b = miller.binning(uc, n_bins, m, 0, d_min) b = miller.binning(uc, n_bins, m, 0, d_min, 1.e-6) assert b.d_max() == -1 assert approx_equal(b.d_min(), d_min) assert b.bin_d_range(0) == (-1,-1) assert approx_equal(b.bin_d_range(1), (-1,2.1544336)) assert approx_equal(b.bin_d_range(b.n_bins_all()-1), (1,-1)) d_star_sq = 0.5 r = b.bin_d_range(b.get_i_bin(d_star_sq)) d = 1/math.sqrt(d_star_sq) assert r[1] <= d <= r[0] h = (3,4,5) r = b.bin_d_range(b.get_i_bin(h)) assert r[1] <= uc.d(h) <= r[0] # a quick test to excercise d-spacings on fractional Miller indices: assert approx_equal( uc.d((3,4,5)), uc.d_frac((3.001,4,5)), eps=0.001) binning1 = miller.binning(uc, n_bins, m) assert binning1.unit_cell().is_similar_to(uc) assert binning1.n_bins_used() == n_bins assert binning1.limits().size() == n_bins + 1 assert binning1.n_bins_all() == n_bins + 2 s = pickle.dumps(binning1) l = pickle.loads(s) assert str(l.unit_cell()) == "(11, 11, 13, 90, 90, 120)" assert approx_equal(l.limits(), binning1.limits()) # binner1 = miller.ext.binner(binning1, m) assert binner1.miller_indices().id() == m.id() assert binner1.count(binner1.i_bin_d_too_large()) == 0 assert binner1.count(binner1.i_bin_d_too_small()) == 0 counts = binner1.counts() for i_bin in binner1.range_all(): assert binner1.count(i_bin) == counts[i_bin] assert binner1.selection(i_bin).count(True) == counts[i_bin] assert list(binner1.range_all()) == range(binner1.n_bins_all()) assert list(binner1.range_used()) == range(1, binner1.n_bins_used()+1) binning2 = miller.binning(uc, n_bins - 2, binning1.bin_d_min(2), binning1.bin_d_min(n_bins)) binner2 = miller.ext.binner(binning2, m) assert tuple(binner1.counts())[1:-1] == tuple(binner2.counts()) array_indices = flex.size_t(range(m.size())) perm_array_indices1 = flex.size_t() perm_array_indices2 = flex.size_t() for i_bin in binner1.range_all(): perm_array_indices1.extend(array_indices.select(binner1.selection(i_bin))) perm_array_indices2.extend(binner1.array_indices(i_bin)) assert perm_array_indices1.size() == m.size() assert perm_array_indices2.size() == m.size() assert tuple(perm_array_indices1) == tuple(perm_array_indices2) b = miller.ext.binner(miller.binning(uc, n_bins, m, 0, d_min), m) assert approx_equal(b.bin_centers(1), (0.23207956, 0.52448148, 0.62711856, 0.70311998, 0.7652538, 0.818567, 0.86566877, 0.90811134, 0.94690405, 0.98274518)) assert approx_equal(b.bin_centers(2), (0.10772184, 0.27871961, 0.39506823, 0.49551249, 0.58642261, 0.67067026, 0.74987684, 0.82507452, 0.89697271, 0.96608584)) assert approx_equal(b.bin_centers(3), (0.050000075, 0.15000023, 0.25000038, 0.35000053, 0.45000068, 0.55000083, 0.65000098, 0.75000113, 0.85000128, 0.95000143)) v = flex.double(xrange(b.n_bins_used())) i = b.interpolate(v, 0) for i_bin in b.range_used(): assert i.select(b.selection(i_bin)).all_eq(v[i_bin-1]) dss = uc.d_star_sq(m) for d_star_power in (1,2,3): j = b.interpolate(v, d_star_power) x = flex.pow(dss, (d_star_power/2.)) r = flex.linear_correlation(x, j) assert r.is_well_defined() assert approx_equal( r.coefficient(), (0.946401,0.990764,1.0)[d_star_power-1], eps=1.e-4, multiplier=None) # s = pickle.dumps(binner2) l = pickle.loads(s) assert str(l.unit_cell()) == "(11, 11, 13, 90, 90, 120)" assert approx_equal(l.limits(), binner2.limits()) assert l.miller_indices().all_eq(binner2.miller_indices()) assert l.bin_indices().all_eq(binner2.bin_indices()) # limits = flex.random_double(size=10) bng = miller.binning(uc, limits) assert bng.unit_cell().is_similar_to(uc) assert approx_equal(bng.limits(), limits)
def crystallographic_parameters_section(xproject): lines = [] for cname, xcryst in xproject.get_crystals().iteritems(): lines.append('\n') lines.append('Crystallographic parameters') lines.append('=' * len(lines[-1])) lines.append('\n') lines.append('Unit cell') lines.append('-' * len(lines[-1])) lines.append('\n') cell = xcryst.get_cell() headers = [u'a (Å)', u'b (Å)', u'c (Å)', u'α (°)', u'β (°)', u'γ (°)'] table = [['%.3f' %c for c in cell]] lines.append('\n') lines.append(tabulate(table, headers, tablefmt='grid')) lines.append('\n') lines.append('.. note:: The unit cell parameters are the average for all measurements.') lines.append('\n') from cctbx import sgtbx spacegroups = xcryst.get_likely_spacegroups() spacegroup = spacegroups[0] sg = sgtbx.space_group_type(str(spacegroup)) #spacegroup = sg.lookup_symbol() spacegroup = space_group_symbol_rst(sg) table.append(['Space group', spacegroup, '']) lines.append('Space group') lines.append('-' * len(lines[-1])) lines.append('\n') lines.append('Space group: %s' %spacegroup) lines.append('\n') lines.append('Other possibilities could be:') lines.append('\n') if len(spacegroups) > 1: for sg in spacegroups[1:]: sg = sgtbx.space_group_type(str(sg)) lines.append('* %s\n' %space_group_symbol_rst(sg)) lines.append('\n') lines.append('.. note:: The spacegroup was determined using pointless (see log file)') lines.append('\n') twinning_score = xcryst._get_scaler()._scalr_twinning_score twinning_conclusion = xcryst._get_scaler()._scalr_twinning_conclusion if twinning_score is not None and twinning_conclusion is not None: lines.append('Twinning analysis') lines.append('-' * len(lines[-1])) lines.append('\n') lines.append('Overall twinning score: %.2f' %twinning_score) lines.append('%s' %twinning_conclusion) lines.append('\n') lines.append( '.. note:: The twinning score is the value of <E4>/<I2> reported by') lines.append( ' sfcheck (see `documentation <http://www.ccp4.ac.uk/html/sfcheck.html#Twinning%20test>`_)') lines.append('\n') lines.append('Asymmetric unit contents') lines.append('-' * len(lines[-1])) lines.append('\n') lines.append('\n') lines.append('.. note:: No information on ASU contents (because no sequence information was supplied?)') lines.append('\n') return lines
def crystallographic_parameters_section(xproject): lines = [] for cname, xcryst in xproject.get_crystals().iteritems(): lines.append('\n') lines.append('Crystallographic parameters') lines.append('=' * len(lines[-1])) lines.append('\n') lines.append('Unit cell') lines.append('-' * len(lines[-1])) lines.append('\n') cell = xcryst.get_cell() headers = [u'a (Å)', u'b (Å)', u'c (Å)', u'α (°)', u'β (°)', u'γ (°)'] table = [['%.3f' % c for c in cell]] lines.append('\n') lines.append(tabulate(table, headers, tablefmt='grid')) lines.append('\n') lines.append( '.. note:: The unit cell parameters are the average for all measurements.' ) lines.append('\n') from cctbx import sgtbx spacegroups = xcryst.get_likely_spacegroups() spacegroup = spacegroups[0] sg = sgtbx.space_group_type(str(spacegroup)) #spacegroup = sg.lookup_symbol() spacegroup = space_group_symbol_rst(sg) table.append(['Space group', spacegroup, '']) lines.append('Space group') lines.append('-' * len(lines[-1])) lines.append('\n') lines.append('Space group: %s' % spacegroup) lines.append('\n') lines.append('Other possibilities could be:') lines.append('\n') if len(spacegroups) > 1: for sg in spacegroups[1:]: sg = sgtbx.space_group_type(str(sg)) lines.append('* %s\n' % space_group_symbol_rst(sg)) lines.append('\n') lines.append( '.. note:: The spacegroup was determined using pointless (see log file)' ) lines.append('\n') twinning_score = xcryst._get_scaler()._scalr_twinning_score twinning_conclusion = xcryst._get_scaler()._scalr_twinning_conclusion if twinning_score is not None and twinning_conclusion is not None: lines.append('Twinning analysis') lines.append('-' * len(lines[-1])) lines.append('\n') lines.append('Overall twinning score: %.2f' % twinning_score) lines.append('%s' % twinning_conclusion) lines.append('\n') lines.append( '.. note:: The twinning score is the value of <E4>/<I2> reported by' ) lines.append( ' sfcheck (see `documentation <http://www.ccp4.ac.uk/html/sfcheck.html#Twinning%20test>`_)' ) lines.append('\n') lines.append('Asymmetric unit contents') lines.append('-' * len(lines[-1])) lines.append('\n') lines.append('\n') lines.append( '.. note:: No information on ASU contents (because no sequence information was supplied?)' ) lines.append('\n') return lines
def make_sgtype(ibrav): symmorphic_sgs = [ 'F23', 'I23', 'P23', 'R3', 'P3', 'I4', 'P4', 'F222', 'I222', 'A222', 'B222', 'C222', 'P222', 'I2', 'C2', 'P2', 'P1' ] return sgtbx.space_group_type(symmorphic_sgs[ibrav])
def get_output(self): result = "Crystal: %s\n" % self._name if self._aa_sequence: result += "Sequence: %s\n" % self._aa_sequence.get_sequence() for wavelength in self._wavelengths.keys(): result += self._wavelengths[wavelength].get_output() scaler = self._get_scaler() if scaler.get_scaler_finish_done(): for wname, xwav in self._wavelengths.iteritems(): for xsweep in xwav.get_sweeps(): idxr = xsweep._get_indexer() if PhilIndex.params.xia2.settings.show_template: result += "%s\n" % banner( "Autoindexing %s (%s)" % (idxr.get_indexer_sweep_name(), idxr.get_template())) else: result += "%s\n" % banner( "Autoindexing %s" % idxr.get_indexer_sweep_name()) result += "%s\n" % idxr.show_indexer_solutions() intgr = xsweep._get_integrater() if PhilIndex.params.xia2.settings.show_template: result += "%s\n" % banner( "Integrating %s (%s)" % (intgr.get_integrater_sweep_name(), intgr.get_template())) else: result += "%s\n" % banner( "Integrating %s" % intgr.get_integrater_sweep_name()) result += "%s\n" % intgr.show_per_image_statistics() result += "%s\n" % banner("Scaling %s" % self.get_name()) for ( (dname, sname), (limit, suggested), ) in scaler.get_scaler_resolution_limits().iteritems(): if suggested is None or limit == suggested: result += "Resolution limit for %s/%s: %5.2f\n" % ( dname, sname, limit, ) else: result += ( "Resolution limit for %s/%s: %5.2f (%5.2f suggested)\n" % (dname, sname, limit, suggested)) # this is now deprecated - be explicit in what you are # asking for... reflections_all = self.get_scaled_merged_reflections() statistics_all = self._get_scaler().get_scaler_statistics() # print some of these statistics, perhaps? for key in statistics_all.keys(): result += format_statistics(statistics_all[key], caption="For %s/%s/%s" % key) # then print out some "derived" information based on the # scaling - this is presented through the Scaler interface # explicitly... cell = self._get_scaler().get_scaler_cell() cell_esd = self._get_scaler().get_scaler_cell_esd() spacegroups = self._get_scaler().get_scaler_likely_spacegroups() spacegroup = spacegroups[0] resolution = self._get_scaler().get_scaler_highest_resolution() from cctbx import sgtbx sg = sgtbx.space_group_type(str(spacegroup)) spacegroup = sg.lookup_symbol() CIF.set_spacegroup(sg) mmCIF.set_spacegroup(sg) if len(self._wavelengths) == 1: CIF.set_wavelengths( [w.get_wavelength() for w in self._wavelengths.itervalues()]) mmCIF.set_wavelengths( [w.get_wavelength() for w in self._wavelengths.itervalues()]) else: for wavelength in self._wavelengths.keys(): full_wave_name = "%s_%s_%s" % ( self._project._name, self._name, wavelength, ) CIF.get_block(full_wave_name)[ "_diffrn_radiation_wavelength"] = self._wavelengths[ wavelength].get_wavelength() mmCIF.get_block(full_wave_name)[ "_diffrn_radiation_wavelength"] = self._wavelengths[ wavelength].get_wavelength() CIF.set_wavelengths({ name: wave.get_wavelength() for name, wave in self._wavelengths.iteritems() }) mmCIF.set_wavelengths({ name: wave.get_wavelength() for name, wave in self._wavelengths.iteritems() }) result += "Assuming spacegroup: %s\n" % spacegroup if len(spacegroups) > 1: result += "Other likely alternatives are:\n" for sg in spacegroups[1:]: result += "%s\n" % sg if cell_esd: from libtbx.utils import format_float_with_standard_uncertainty def match_formatting(dimA, dimB): def conditional_split(s): return ((s[:s.index(".")], s[s.index("."):]) if "." in s else (s, "")) A, B = conditional_split(dimA), conditional_split(dimB) maxlen = (max(len(A[0]), len(B[0])), max(len(A[1]), len(B[1]))) return ( A[0].rjust(maxlen[0]) + A[1].ljust(maxlen[1]), B[0].rjust(maxlen[0]) + B[1].ljust(maxlen[1]), ) formatted_cell_esds = tuple( format_float_with_standard_uncertainty(v, sd) for v, sd in zip(cell, cell_esd)) formatted_rows = (formatted_cell_esds[0:3], formatted_cell_esds[3:6]) formatted_rows = zip(*(match_formatting(l, a) for l, a in zip(*formatted_rows))) result += "Unit cell (with estimated std devs):\n" result += "%s %s %s\n%s %s %s\n" % (formatted_rows[0] + formatted_rows[1]) else: result += "Unit cell:\n" result += "%7.3f %7.3f %7.3f\n%7.3f %7.3f %7.3f\n" % tuple(cell) # now, use this information and the sequence (if provided) # and also matthews_coef (should I be using this directly, here?) # to compute a likely number of molecules in the ASU and also # the solvent content... if self._aa_sequence: residues = self._aa_sequence.get_sequence() if residues: nres = len(residues) # first compute the number of molecules using the K&R # method nmol = compute_nmol( cell[0], cell[1], cell[2], cell[3], cell[4], cell[5], spacegroup, resolution, nres, ) # then compute the solvent fraction solvent = compute_solvent( cell[0], cell[1], cell[2], cell[3], cell[4], cell[5], spacegroup, nmol, nres, ) result += "Likely number of molecules in ASU: %d\n" % nmol result += "Giving solvent fraction: %4.2f\n" % solvent self._nmol = nmol if isinstance(reflections_all, type({})): for format in reflections_all.keys(): result += "%s format:\n" % format reflections = reflections_all[format] if isinstance(reflections, type({})): for wavelength in reflections.keys(): target = FileHandler.get_data_file( reflections[wavelength]) result += "Scaled reflections (%s): %s\n" % ( wavelength, target) else: target = FileHandler.get_data_file(reflections) result += "Scaled reflections: %s\n" % target CIF.write_cif() mmCIF.write_cif() return result
def derive_result_group_list(self, group_of_interest): # Get list of sub-spacegroups subgrs = subgroups.subgroups(group_of_interest).groups_parent_setting() # Order sub-groups sort_values = flex.double() for group in subgrs: order_z = group.order_z() space_group_number = sgtbx.space_group_type(group, False).number() assert 1 <= space_group_number <= 230 sort_values.append(order_z * 1000 + space_group_number) perm = flex.sort_permutation(sort_values, True) for i_subgr in perm: acentric_subgroup = subgrs[i_subgr] acentric_supergroup = metric_supergroup(acentric_subgroup) # Add centre of inversion to acentric lattice symmetry centric_group = sgtbx.space_group(acentric_subgroup) centric_group.expand_inv(sgtbx.tr_vec((0, 0, 0))) # Make symmetry object: unit-cell + space-group # The unit cell is potentially modified to be exactly compatible # with the space group symmetry. subsym = crystal.symmetry( unit_cell=self.minimum_symmetry.unit_cell(), space_group=centric_group, assert_is_compatible_unit_cell=False) supersym = crystal.symmetry( unit_cell=self.minimum_symmetry.unit_cell(), space_group=acentric_supergroup, assert_is_compatible_unit_cell=False) # Convert subgroup to reference setting cb_op_minimum_ref = subsym.space_group_info().type().cb_op() ref_subsym = subsym.change_basis(cb_op_minimum_ref) # Ignore unwanted groups if (self.bravais_types_only and not str( ref_subsym.space_group_info()) in bravais_types.centric): continue # Choose best setting for monoclinic and orthorhombic systems cb_op_best_cell = self.change_of_basis_op_to_best_cell(ref_subsym) best_subsym = ref_subsym.change_basis(cb_op_best_cell) # Total basis transformation cb_op_best_cell = change_of_basis_op(str(cb_op_best_cell), stop_chars='', r_den=144, t_den=144) cb_op_minimum_ref = change_of_basis_op(str(cb_op_minimum_ref), stop_chars='', r_den=144, t_den=144) self.cb_op_inp_minimum = change_of_basis_op(str( self.cb_op_inp_minimum), stop_chars='', r_den=144, t_den=144) cb_op_inp_best = cb_op_best_cell * cb_op_minimum_ref * self.cb_op_inp_minimum # Use identity change-of-basis operator if possible if (best_subsym.unit_cell().is_similar_to( self.input_symmetry.unit_cell())): cb_op_corr = cb_op_inp_best.inverse() try: best_subsym_corr = best_subsym.change_basis(cb_op_corr) except RuntimeError, e: if (str(e).find( "Unsuitable value for rational rotation matrix.") < 0): raise else: if (best_subsym_corr.space_group() == best_subsym.space_group()): cb_op_inp_best = cb_op_corr * cb_op_inp_best self.result_groups.append({ 'subsym': subsym, 'supersym': supersym, 'ref_subsym': ref_subsym, 'best_subsym': best_subsym, 'cb_op_inp_best': cb_op_inp_best, 'max_angular_difference': find_max_delta(reduced_cell=self.minimum_symmetry.unit_cell(), space_group=acentric_supergroup) })
def overview_section(xproject): lines = [] lines.append('xia2 Processing Report: %s' %xproject.get_name()) lines.append('#' * len(lines[-1])) lines.append('\n') xia2_status = 'normal termination' # XXX FIXME lines.append("xia2 version %s completed with status '%s'\n" %( Version.split()[-1], xia2_status)) lines.append('Read output from `<%s/>`_\n' %os.path.abspath(os.path.curdir)) columns = [] columns.append([ '', u'Wavelength (Å)', 'High resolution limit', 'Low resolution limit', 'Completeness', 'Multiplicity', 'CC-half', 'I/sigma', 'Rmerge(I)', #'See all statistics', ]) for cname, xcryst in xproject.get_crystals().iteritems(): statistics_all = xcryst.get_statistics() for wname in xcryst.get_wavelength_names(): statistics = statistics_all[(xproject.get_name(), cname, wname)] xwav = xcryst.get_xwavelength(wname) high_res = statistics['High resolution limit'] low_res = statistics['Low resolution limit'] column = [ wname, xwav.get_wavelength(), '%6.2f (%6.2f - %6.2f)' % (high_res[0], low_res[2], high_res[2]), '%6.2f (%6.2f - %6.2f)' % (low_res[0], high_res[2], low_res[2]), '%6.2f' % statistics['Completeness'][0], '%6.2f' % statistics['Multiplicity'][0], '%6.4f' % statistics['CC half'][0], '%6.2f' % statistics['I/sigma'][0], '%6.4f' % statistics['Rmerge(I)'][0], ] for c in ('Anomalous completeness', 'Anomalous multiplicity'): if c in statistics: column.append('%6.2f' % statistics[c][0]) if c not in columns[0]: columns[0].append(c) columns.append(column) table = [[c[i] for c in columns] for i in range(len(columns[0]))] cell = xcryst.get_cell() table.append(['','','']) table.append([u'Unit cell dimensions: a (Å)', '%.3f' %cell[0], '']) table.append([u'b (Å)', '%.3f' %cell[1], '']) table.append([u'c (Å)', '%.3f' %cell[2], '']) table.append([u'α (°)', '%.3f' %cell[3], '']) table.append([u'β (°)', '%.3f' %cell[4], '']) table.append([u'γ (°)', '%.3f' %cell[5], '']) from cctbx import sgtbx spacegroups = xcryst.get_likely_spacegroups() spacegroup = spacegroups[0] sg = sgtbx.space_group_type(str(spacegroup)) #spacegroup = sg.lookup_symbol() spacegroup = space_group_symbol_rst(sg) table.append(['','','']) table.append(['Space group', spacegroup, '']) twinning_score = xcryst._get_scaler()._scalr_twinning_score twinning_conclusion = xcryst._get_scaler()._scalr_twinning_conclusion if twinning_score is not None: table.append(['','','']) table.append(['Twinning score', '%.2f' %twinning_score, '']) if twinning_conclusion is not None: table.append(['', twinning_conclusion, '']) headers = table.pop(0) lines.append('\n') lines.append('.. class:: table-one') lines.append('\n') lines.append(tabulate(table, headers, tablefmt='grid')) lines.append('\n') #Spacegroup P 41 2 2 #Sfcheck twinning score 2.99 #Your data do not appear to be twinned #All crystallographic parameters.. lines.append('Contents of the rest of this document:') lines.append('\n') lines.append( '* `Reflection files output from xia2`_') lines.append( '* `Full statistics for each wavelength`_') lines.append( '* `Log files from individual stages`_') lines.append( '* `Integration status for images by wavelength and sweep`_') #lines.append( #'* `Lists of programs and citations`_') #lines.append('Inter-wavelength B and R-factor analysis') #lines.append('-' * len(lines[-1])) #lines.append('\n') return lines
def find_matching_symmetry(unit_cell, target_space_group, max_delta=5): cs = crystal.symmetry(unit_cell=unit_cell, space_group=sgtbx.space_group()) target_bravais_t = bravais_types.bravais_lattice( group=target_space_group.info().reference_setting().group()) best_subgroup = None best_angular_difference = 1e8 # code based on cctbx/sgtbx/lattice_symmetry.py but optimised to only # look at subgroups with the correct bravais type input_symmetry = cs # Get cell reduction operator cb_op_inp_minimum = input_symmetry.change_of_basis_op_to_minimum_cell() # New symmetry object with changed basis minimum_symmetry = input_symmetry.change_basis(cb_op_inp_minimum) # Get highest symmetry compatible with lattice lattice_group = sgtbx.lattice_symmetry_group( minimum_symmetry.unit_cell(), max_delta=max_delta, enforce_max_delta_for_generated_two_folds=True) # Get list of sub-spacegroups subgrs = subgroups.subgroups(lattice_group.info()).groups_parent_setting() # Order sub-groups sort_values = flex.double() for group in subgrs: order_z = group.order_z() space_group_number = sgtbx.space_group_type(group, False).number() assert 1 <= space_group_number <= 230 sort_values.append(order_z*1000+space_group_number) perm = flex.sort_permutation(sort_values, True) for i_subgr in perm: acentric_subgroup = subgrs[i_subgr] acentric_supergroup = metric_supergroup(acentric_subgroup) ## Add centre of inversion to acentric lattice symmetry #centric_group = sgtbx.space_group(acentric_subgroup) #centric_group.expand_inv(sgtbx.tr_vec((0,0,0))) # Make symmetry object: unit-cell + space-group # The unit cell is potentially modified to be exactly compatible # with the space group symmetry. subsym = crystal.symmetry( unit_cell=minimum_symmetry.unit_cell(), space_group=acentric_subgroup, assert_is_compatible_unit_cell=False) #supersym = crystal.symmetry( #unit_cell=minimum_symmetry.unit_cell(), #space_group=acentric_supergroup, #assert_is_compatible_unit_cell=False) # Convert subgroup to reference setting cb_op_minimum_ref = subsym.space_group_info().type().cb_op() ref_subsym = subsym.change_basis(cb_op_minimum_ref) # Ignore unwanted groups bravais_t = bravais_types.bravais_lattice( group=ref_subsym.space_group()) if bravais_t != target_bravais_t: continue # Choose best setting for monoclinic and orthorhombic systems cb_op_best_cell = ref_subsym.change_of_basis_op_to_best_cell( best_monoclinic_beta=True) best_subsym = ref_subsym.change_basis(cb_op_best_cell) # Total basis transformation cb_op_best_cell = change_of_basis_op(str(cb_op_best_cell),stop_chars='',r_den=144,t_den=144) cb_op_minimum_ref=change_of_basis_op(str(cb_op_minimum_ref),stop_chars='',r_den=144,t_den=144) cb_op_inp_minimum=change_of_basis_op(str(cb_op_inp_minimum),stop_chars='',r_den=144,t_den=144) cb_op_inp_best = cb_op_best_cell * cb_op_minimum_ref * cb_op_inp_minimum # Use identity change-of-basis operator if possible if (best_subsym.unit_cell().is_similar_to(input_symmetry.unit_cell())): cb_op_corr = cb_op_inp_best.inverse() try: best_subsym_corr = best_subsym.change_basis(cb_op_corr) except RuntimeError, e: if (str(e).find("Unsuitable value for rational rotation matrix.") < 0): raise else: if (best_subsym_corr.space_group() == best_subsym.space_group()): cb_op_inp_best = cb_op_corr * cb_op_inp_best max_angular_difference = find_max_delta( reduced_cell=minimum_symmetry.unit_cell(), space_group=acentric_supergroup) if max_angular_difference < best_angular_difference: #best_subgroup = subgroup best_angular_difference = max_angular_difference best_subgroup = {'subsym':subsym, #'supersym':supersym, 'ref_subsym':ref_subsym, 'best_subsym':best_subsym, 'cb_op_inp_best':cb_op_inp_best, 'max_angular_difference':max_angular_difference }
def derive_result_group_list_original_input(self,group_of_interest): # more-or-less a capitulation to code duplication. Don't want to copy code # from cctbx.sgtbx.lattice_symmetry but can't figure out a quick way around it. # Get list of sub-spacegroups subgrs = subgroups.subgroups(group_of_interest).groups_parent_setting() # Order sub-groups sort_values = flex.double() for group in subgrs: order_z = group.order_z() space_group_number = sgtbx.space_group_type(group, False).number() assert 1 <= space_group_number <= 230 sort_values.append(order_z*1000+space_group_number) perm = flex.sort_permutation(sort_values, True) for i_subgr in perm: acentric_subgroup = subgrs[i_subgr] acentric_supergroup = metric_supergroup(acentric_subgroup) # Add centre of inversion to acentric lattice symmetry centric_group = sgtbx.space_group(acentric_subgroup) # Make symmetry object: unit-cell + space-group # The unit cell is potentially modified to be exactly compatible # with the space group symmetry. subsym = crystal.symmetry( unit_cell=self.minimum_symmetry.unit_cell(), space_group=centric_group, assert_is_compatible_unit_cell=False) supersym = crystal.symmetry( unit_cell=self.minimum_symmetry.unit_cell(), space_group=acentric_supergroup, assert_is_compatible_unit_cell=False) # Convert subgroup to reference setting cb_op_minimum_ref = subsym.space_group_info().type().cb_op() ref_subsym = subsym.change_basis(cb_op_minimum_ref) # Ignore unwanted groups if (self.bravais_types_only and not str(ref_subsym.space_group_info()) in bravais_types.centric): continue # Choose best setting for monoclinic and orthorhombic systems cb_op_best_cell = self.change_of_basis_op_to_best_cell(ref_subsym) best_subsym = ref_subsym.change_basis(cb_op_best_cell) # Total basis transformation cb_op_best_cell = change_of_basis_op(str(cb_op_best_cell),stop_chars='',r_den=144,t_den=144) cb_op_minimum_ref=change_of_basis_op(str(cb_op_minimum_ref),stop_chars='',r_den=144,t_den=144) self.cb_op_inp_minimum=change_of_basis_op(str(self.cb_op_inp_minimum),stop_chars='',r_den=144,t_den=144) cb_op_inp_best = cb_op_best_cell * (cb_op_minimum_ref * self.cb_op_inp_minimum) # Use identity change-of-basis operator if possible if (best_subsym.unit_cell().is_similar_to(self.input_symmetry.unit_cell())): cb_op_corr = cb_op_inp_best.inverse() try: best_subsym_corr = best_subsym.change_basis(cb_op_corr) except RuntimeError, e: if (str(e).find("Unsuitable value for rational rotation matrix.") < 0): raise else: if (best_subsym_corr.space_group() == best_subsym.space_group()): cb_op_inp_best = cb_op_corr * cb_op_inp_best """Note: The following call does not work if n_ltr >1 for the space group""" if acentric_subgroup.n_ltr() == 1: m_a_d = find_max_delta( reduced_cell=self.minimum_symmetry.unit_cell(), space_group=acentric_subgroup) else: m_a_d = 0.0 self.result_groups.append({'subsym':subsym, 'supersym':supersym, 'ref_subsym':ref_subsym, 'best_subsym':best_subsym, 'cb_op_inp_best':cb_op_inp_best, 'max_angular_difference':m_a_d })
def find_matching_symmetry(unit_cell, target_space_group, max_delta=5): cs = crystal.symmetry(unit_cell=unit_cell, space_group=sgtbx.space_group()) target_bravais_t = bravais_types.bravais_lattice( group=target_space_group.info().reference_setting().group()) best_subgroup = None best_angular_difference = 1e8 # code based on cctbx/sgtbx/lattice_symmetry.py but optimised to only # look at subgroups with the correct bravais type input_symmetry = cs # Get cell reduction operator cb_op_inp_minimum = input_symmetry.change_of_basis_op_to_minimum_cell() # New symmetry object with changed basis minimum_symmetry = input_symmetry.change_basis(cb_op_inp_minimum) # Get highest symmetry compatible with lattice lattice_group = sgtbx.lattice_symmetry_group( minimum_symmetry.unit_cell(), max_delta=max_delta, enforce_max_delta_for_generated_two_folds=True) # Get list of sub-spacegroups subgrs = subgroups.subgroups(lattice_group.info()).groups_parent_setting() # Order sub-groups sort_values = flex.double() for group in subgrs: order_z = group.order_z() space_group_number = sgtbx.space_group_type(group, False).number() assert 1 <= space_group_number <= 230 sort_values.append(order_z * 1000 + space_group_number) perm = flex.sort_permutation(sort_values, True) for i_subgr in perm: acentric_subgroup = subgrs[i_subgr] acentric_supergroup = metric_supergroup(acentric_subgroup) ## Add centre of inversion to acentric lattice symmetry #centric_group = sgtbx.space_group(acentric_subgroup) #centric_group.expand_inv(sgtbx.tr_vec((0,0,0))) # Make symmetry object: unit-cell + space-group # The unit cell is potentially modified to be exactly compatible # with the space group symmetry. subsym = crystal.symmetry(unit_cell=minimum_symmetry.unit_cell(), space_group=acentric_subgroup, assert_is_compatible_unit_cell=False) #supersym = crystal.symmetry( #unit_cell=minimum_symmetry.unit_cell(), #space_group=acentric_supergroup, #assert_is_compatible_unit_cell=False) # Convert subgroup to reference setting cb_op_minimum_ref = subsym.space_group_info().type().cb_op() ref_subsym = subsym.change_basis(cb_op_minimum_ref) # Ignore unwanted groups bravais_t = bravais_types.bravais_lattice( group=ref_subsym.space_group()) if bravais_t != target_bravais_t: continue # Choose best setting for monoclinic and orthorhombic systems cb_op_best_cell = ref_subsym.change_of_basis_op_to_best_cell( best_monoclinic_beta=True) best_subsym = ref_subsym.change_basis(cb_op_best_cell) # Total basis transformation cb_op_best_cell = change_of_basis_op(str(cb_op_best_cell), stop_chars='', r_den=144, t_den=144) cb_op_minimum_ref = change_of_basis_op(str(cb_op_minimum_ref), stop_chars='', r_den=144, t_den=144) cb_op_inp_minimum = change_of_basis_op(str(cb_op_inp_minimum), stop_chars='', r_den=144, t_den=144) cb_op_inp_best = cb_op_best_cell * cb_op_minimum_ref * cb_op_inp_minimum # Use identity change-of-basis operator if possible if best_subsym.unit_cell().is_similar_to(input_symmetry.unit_cell()): cb_op_corr = cb_op_inp_best.inverse() try: best_subsym_corr = best_subsym.change_basis(cb_op_corr) except RuntimeError as e: if str(e).find( "Unsuitable value for rational rotation matrix.") < 0: raise else: if best_subsym_corr.space_group() == best_subsym.space_group(): cb_op_inp_best = cb_op_corr * cb_op_inp_best max_angular_difference = find_max_delta( reduced_cell=minimum_symmetry.unit_cell(), space_group=acentric_supergroup) if max_angular_difference < best_angular_difference: #best_subgroup = subgroup best_angular_difference = max_angular_difference best_subgroup = { 'subsym': subsym, #'supersym':supersym, 'ref_subsym': ref_subsym, 'best_subsym': best_subsym, 'cb_op_inp_best': cb_op_inp_best, 'max_angular_difference': max_angular_difference } if best_subgroup is not None: return best_subgroup
def overview_section(xproject): lines = [] lines.append('xia2 Processing Report: %s' % xproject.get_name()) lines.append('#' * len(lines[-1])) lines.append('\n') xia2_status = 'normal termination' # XXX FIXME lines.append("xia2 version %s completed with status '%s'\n" % (Version.split()[-1], xia2_status)) lines.append('Read output from `<%s/>`_\n' % os.path.abspath(os.path.curdir)) columns = [] columns.append([ '', u'Wavelength (Å)', 'High resolution limit', 'Low resolution limit', 'Completeness', 'Multiplicity', 'CC-half', 'I/sigma', 'Rmerge(I)', #'See all statistics', ]) for cname, xcryst in xproject.get_crystals().iteritems(): statistics_all = xcryst.get_statistics() for wname in xcryst.get_wavelength_names(): statistics = statistics_all[(xproject.get_name(), cname, wname)] xwav = xcryst.get_xwavelength(wname) high_res = statistics['High resolution limit'] low_res = statistics['Low resolution limit'] column = [ wname, xwav.get_wavelength(), '%6.2f (%6.2f - %6.2f)' % (high_res[0], low_res[2], high_res[2]), '%6.2f (%6.2f - %6.2f)' % (low_res[0], high_res[2], low_res[2]), '%6.2f' % statistics['Completeness'][0], '%6.2f' % statistics['Multiplicity'][0], '%6.4f' % statistics['CC half'][0], '%6.2f' % statistics['I/sigma'][0], '%6.4f' % statistics['Rmerge(I)'][0], ] for c in ('Anomalous completeness', 'Anomalous multiplicity'): if c in statistics: column.append('%6.2f' % statistics[c][0]) if c not in columns[0]: columns[0].append(c) columns.append(column) table = [[c[i] for c in columns] for i in range(len(columns[0]))] cell = xcryst.get_cell() table.append(['', '', '']) table.append([u'Unit cell dimensions: a (Å)', '%.3f' % cell[0], '']) table.append([u'b (Å)', '%.3f' % cell[1], '']) table.append([u'c (Å)', '%.3f' % cell[2], '']) table.append([u'α (°)', '%.3f' % cell[3], '']) table.append([u'β (°)', '%.3f' % cell[4], '']) table.append([u'γ (°)', '%.3f' % cell[5], '']) from cctbx import sgtbx spacegroups = xcryst.get_likely_spacegroups() spacegroup = spacegroups[0] sg = sgtbx.space_group_type(str(spacegroup)) #spacegroup = sg.lookup_symbol() spacegroup = space_group_symbol_rst(sg) table.append(['', '', '']) table.append(['Space group', spacegroup, '']) twinning_score = xcryst._get_scaler()._scalr_twinning_score twinning_conclusion = xcryst._get_scaler()._scalr_twinning_conclusion if twinning_score is not None: table.append(['', '', '']) table.append(['Twinning score', '%.2f' % twinning_score, '']) if twinning_conclusion is not None: table.append(['', twinning_conclusion, '']) headers = table.pop(0) lines.append('\n') lines.append('.. class:: table-one') lines.append('\n') lines.append(tabulate(table, headers, tablefmt='grid')) lines.append('\n') #Spacegroup P 41 2 2 #Sfcheck twinning score 2.99 #Your data do not appear to be twinned #All crystallographic parameters.. lines.append('Contents of the rest of this document:') lines.append('\n') lines.append('* `Reflection files output from xia2`_') lines.append('* `Full statistics for each wavelength`_') lines.append('* `Log files from individual stages`_') lines.append('* `Integration status for images by wavelength and sweep`_') #lines.append( #'* `Lists of programs and citations`_') #lines.append('Inter-wavelength B and R-factor analysis') #lines.append('-' * len(lines[-1])) #lines.append('\n') return lines