Ejemplo n.º 1
0
 def show_ncs_groups(self, out = None):
   if(out is None): out = sys.stdout
   pr = "REMARK   3  "
   print >>out,pr+"NCS DETAILS."
   print >>out,pr+" NUMBER OF NCS GROUPS : %-6d"%len(self.ncs_groups)
   for i_group, ncs_group in enumerate(self.ncs_groups):
     print >>out,pr+" NCS GROUP : %-6d"%(i_group+1)
     selection_strings = ncs_group.group.selection_strings
     for i_op,pair,mx,rms in zip(
         count(1),
         ncs_group.group.selection_pairs,
         ncs_group.matrices,
         ncs_group.rms):
       print >> out,pr+"  NCS OPERATOR : %-d" % i_op
       lines = line_breaker(selection_strings[0], width=34)
       for i_line, line in enumerate(lines):
         if(i_line == 0):
           print >> out, pr+"   REFERENCE SELECTION: %s"%line
         else:
           print >> out, pr+"                      : %s"%line
       lines = line_breaker(selection_strings[i_op], width=34)
       for i_line, line in enumerate(lines):
         if(i_line == 0):
           print >> out, pr+"   SELECTION          : %s"%line
         else:
           print >> out, pr+"                      : %s"%line
       print >> out,pr+"   ATOM PAIRS NUMBER  : %-d" % len(pair[0])
       print >> out,pr+"   RMSD               : %-10.3f" % rms
Ejemplo n.º 2
0
 def as_pdb(self, sites_cart, out):
     result = out
     ncs_groups = self.extract_ncs_groups(sites_cart=sites_cart)
     pr = "REMARK   3  "
     print >> result, pr + "NCS DETAILS."
     print >> result, pr + " NUMBER OF NCS GROUPS : %-6d" % len(ncs_groups)
     for i_group, ncs_group in enumerate(ncs_groups):
         print >> result, pr + " NCS GROUP : %-6d" % (i_group + 1)
         selection_strings = ncs_group.group.selection_strings
         for i_op, pair, mx, rms in zip(count(1),
                                        ncs_group.group.selection_pairs,
                                        ncs_group.matrices, ncs_group.rms):
             print >> result, pr + "  NCS OPERATOR : %-d" % i_op
             lines = line_breaker(selection_strings[0], width=34)
             for i_line, line in enumerate(lines):
                 if (i_line == 0):
                     print >> result, pr + "   REFERENCE SELECTION: %s" % line
                 else:
                     print >> result, pr + "                      : %s" % line
             lines = line_breaker(selection_strings[i_op], width=34)
             for i_line, line in enumerate(lines):
                 if (i_line == 0):
                     print >> result, pr + "   SELECTION          : %s" % line
                 else:
                     print >> result, pr + "                      : %s" % line
             print >> result, pr + "   ATOM PAIRS NUMBER  : %-d" % len(
                 pair[0])
             print >> result, pr + "   RMSD               : %-10.3f" % rms
     return result.getvalue()
Ejemplo n.º 3
0
 def as_pdb(self, sites_cart, out):
     result = out
     pr = "REMARK   3  "
     print(pr + "NCS DETAILS.", file=result)
     print(pr + " NUMBER OF NCS GROUPS : %-6d" % self.get_n_groups(),
           file=result)
     for i_group, group in enumerate(self.groups_list):
         print(pr + " NCS GROUP : %-6d" % (i_group + 1), file=result)
         selection_strings = group.selection_strings
         for i_op, pair, mx, rms in zip(count(1), group.selection_pairs,
                                        group.matrices, group.rms):
             print(pr + "  NCS OPERATOR : %-d" % i_op, file=result)
             lines = line_breaker(selection_strings[0], width=34)
             for i_line, line in enumerate(lines):
                 if (i_line == 0):
                     print(pr + "   REFERENCE SELECTION: %s" % line,
                           file=result)
                 else:
                     print(pr + "                      : %s" % line,
                           file=result)
             lines = line_breaker(selection_strings[i_op], width=34)
             for i_line, line in enumerate(lines):
                 if (i_line == 0):
                     print(pr + "   SELECTION          : %s" % line,
                           file=result)
                 else:
                     print(pr + "                      : %s" % line,
                           file=result)
             print(pr + "   ATOM PAIRS NUMBER  : %-d" % len(pair[0]),
                   file=result)
             print(pr + "   RMSD               : %-10.3f" % rms,
                   file=result)
     return result.getvalue()
Ejemplo n.º 4
0
 def show_ncs_groups(self, out = None):
   if(out is None): out = sys.stdout
   pr = "REMARK   3  "
   print >>out,pr+"NCS DETAILS."
   print >>out,pr+" NUMBER OF NCS GROUPS : %-6d"%len(self.ncs_groups)
   for i_group, ncs_group in enumerate(self.ncs_groups):
     print >>out,pr+" NCS GROUP : %-6d"%(i_group+1)
     selection_strings = ncs_group.group.selection_strings
     for i_op,pair,mx,rms in zip(
         count(1),
         ncs_group.group.selection_pairs,
         ncs_group.matrices,
         ncs_group.rms):
       print >> out,pr+"  NCS OPERATOR : %-d" % i_op
       lines = line_breaker(selection_strings[0], width=34)
       for i_line, line in enumerate(lines):
         if(i_line == 0):
           print >> out, pr+"   REFERENCE SELECTION: %s"%line
         else:
           print >> out, pr+"                      : %s"%line
       lines = line_breaker(selection_strings[i_op], width=34)
       for i_line, line in enumerate(lines):
         if(i_line == 0):
           print >> out, pr+"   SELECTION          : %s"%line
         else:
           print >> out, pr+"                      : %s"%line
       print >> out,pr+"   ATOM PAIRS NUMBER  : %-d" % len(pair[0])
       print >> out,pr+"   RMSD               : %-10.3f" % rms
Ejemplo n.º 5
0
 def write_def(self, f):
     special = special_wrappers.get(self.function_name, None)
     if (special is not None and special[1] is not None):
         print(special[1], file=f)
         return
     return_opaque = self.return_type in opaque_pointers
     def_args = (self.function_name, self.wrapper_function_name())
     self.write_no_opaque_pointers_guard_if(f=f)
     self.write_version_guard_if(f=f)
     if (len(self.args) == 0):
         if (not return_opaque):
             print('    def("%s", %s);' % def_args, file=f)
         else:
             print('    def("%s", %s,' % def_args, file=f)
             print("      return_value_policy<return_opaque_pointer>());",
                   file=f)
     else:
         assert not return_opaque
         print('    def("%s", %s, (' % def_args, file=f)
         s = ""
         for arg in self.args:
             s += ', arg("%s")' % arg.name
         s = s[2:] + "));"
         for line in line_breaker(s, 73):
             print("      " + line, file=f)
     self.write_version_guard_endif(f=f)
     self.write_no_opaque_pointers_guard_endif(f=f)
 def write_def(self, f):
   special = special_wrappers.get(self.function_name, None)
   if (special is not None and special[1] is not None):
     print >> f, special[1]
     return
   return_opaque = self.return_type in opaque_pointers
   def_args = (self.function_name, self.wrapper_function_name())
   self.write_no_opaque_pointers_guard_if(f=f)
   self.write_version_guard_if(f=f)
   if (len(self.args) == 0):
     if (not return_opaque):
       print >> f, '    def("%s", %s);' % def_args
     else:
       print >> f, '    def("%s", %s,' % def_args
       print >> f, "      return_value_policy<return_opaque_pointer>());"
   else:
     assert not return_opaque
     print >> f, '    def("%s", %s, (' % def_args
     s = ""
     for arg in self.args:
       s += ', arg("%s")' % arg.name
     s = s[2:] + "));"
     for line in line_breaker(s, 73):
       print >> f, "      "+line
   self.write_version_guard_endif(f=f)
   self.write_no_opaque_pointers_guard_endif(f=f)
Ejemplo n.º 7
0
 def warn (self, message) :
   self.__call__(message="warn", data=message, accumulate=True, cached=True)
   if (self._log is not None) :
     log = self._log
   else :
     log = sys.stdout
   msg = "WARNING: %s\n" % message
   print >> log, ""
   for line in str_utils.line_breaker(msg, 72) :
     print >> log, "  " + line
Ejemplo n.º 8
0
 def warn (self, message) :
   if (not isinstance(message, (six.text_type, six.binary_type))) :
     message = to_unicode(message)
   self.__call__(message="warn", data=message, accumulate=True, cached=True)
   if (self._log is not None) :
     log = self._log
   else :
     log = sys.stdout
   msg = "WARNING: %s\n" % message
   print("", file=log)
   for line in str_utils.line_breaker(msg, 72) :
     print("  " + line, file=log)
Ejemplo n.º 9
0
def show_citation(article, out=None, max_width=79, format='default'):
    if format == 'default':
        output = format_citation(article)
    elif format == 'iucr':
        output = format_citation_iucr(article)
    elif format == 'cell':
        output = format_citation_cell(article)
    if max_width is None or max_width < 1:
        print(to_unicode(output), file=out)
    else:
        for line in str_utils.line_breaker(output, max_width):
            print(to_unicode(line), file=out)
    print(to_unicode(''), file=out)
Ejemplo n.º 10
0
 def warn(self, message):
     self.__call__(message="warn",
                   data=message,
                   accumulate=True,
                   cached=True)
     if (self._log is not None):
         log = self._log
     else:
         log = sys.stdout
     msg = "WARNING: %s\n" % message
     print >> log, ""
     for line in str_utils.line_breaker(msg, 72):
         print >> log, "  " + line
Ejemplo n.º 11
0
def remark_3_tls(tlsos, selection_strings, out=None):
    if (out is None): out = sys.stdout
    if (len(selection_strings) == 0):
        assert len(tlsos) == 1
        selection_strings = [None]
    else:
        assert len(tlsos) == len(selection_strings)
    print >> out, "REMARK   3  TLS DETAILS."
    print >> out, "REMARK   3   NUMBER OF TLS GROUPS: %-6d" % len(tlsos)
    print >> out, "REMARK   3   ORIGIN: CENTER OF MASS"
    r3 = "REMARK   3   "
    counter = 0
    for tlso, selection_string in zip(tlsos, selection_strings):
        if (selection_string is None):
            selection_string = "all"
        counter += 1
        t = tlso.t
        l = tlso.l
        s = tlso.s
        o = tlso.origin
        print >> out, r3 + "TLS GROUP : %-6d" % (counter)
        lines = line_breaker(selection_string, width=45)
        for i_line, line in enumerate(lines):
            if (i_line == 0):
                print >> out, r3 + " SELECTION: %s" % line
            else:
                print >> out, r3 + "          : %s" % line
        print >> out, r3 + " ORIGIN FOR THE GROUP (A):%9.4f%9.4f%9.4f" % (
            o[0], o[1], o[2])
        print >> out, r3 + " T TENSOR                                            "
        print >> out, r3 + "   T11:%9.4f T22:%9.4f                       " % (
            t[0], t[1])
        print >> out, r3 + "   T33:%9.4f T12:%9.4f                       " % (
            t[2], t[3])
        print >> out, r3 + "   T13:%9.4f T23:%9.4f                       " % (
            t[4], t[5])
        print >> out, r3 + " L TENSOR                                            "
        print >> out, r3 + "   L11:%9.4f L22:%9.4f                       " % (
            l[0], l[1])
        print >> out, r3 + "   L33:%9.4f L12:%9.4f                       " % (
            l[2], l[3])
        print >> out, r3 + "   L13:%9.4f L23:%9.4f                       " % (
            l[4], l[5])
        print >> out, r3 + " S TENSOR                                            "
        print >> out, r3 + "   S11:%9.4f S12:%9.4f S13:%9.4f         " % (
            s[0], s[1], s[2])
        print >> out, r3 + "   S21:%9.4f S22:%9.4f S23:%9.4f         " % (
            s[3], s[4], s[5])
        print >> out, r3 + "   S31:%9.4f S32:%9.4f S33:%9.4f         " % (
            s[6], s[7], s[8])
Ejemplo n.º 12
0
 def format_call(self, return_directly, prefix):
     s = ""
     if (self.return_type != "void"):
         if (return_directly):
             s += "return "
         else:
             s += self.return_type + " result = "
     s += self.function_name + "("
     s += ", ".join([arg.name for arg in self.args])
     s += ");"
     result = []
     indent = ""
     for line in line_breaker(s, 70):
         result.append(prefix + indent + line)
         indent = "  "
     return result
 def format_call(self, return_directly, prefix):
   s = ""
   if (self.return_type != "void"):
     if (return_directly):
       s += "return "
     else:
       s += self.return_type + " result = "
   s += self.function_name+"("
   s += ", ".join([arg.name for arg in self.args])
   s += ");"
   result = []
   indent = ""
   for line in line_breaker(s, 70):
     result.append(prefix+indent+line)
     indent = "  "
   return result
Ejemplo n.º 14
0
 def show_anomalous_scatterer_groups(self, out = None):
   if(out is None): out = sys.stdout
   pr = "REMARK   3  "
   print >>out,pr+"ANOMALOUS SCATTERER GROUPS DETAILS."
   print >>out,pr+" NUMBER OF ANOMALOUS SCATTERER GROUPS : %-6d"%\
     len(self.anomalous_scatterer_groups)
   counter = 0
   for group in self.anomalous_scatterer_groups:
     counter += 1
     print >>out,pr+" ANOMALOUS SCATTERER GROUP : %-6d"%counter
     lines = line_breaker(group.selection_string, width=45)
     for i_line, line in enumerate(lines):
       if(i_line == 0):
         print >> out, pr+"  SELECTION: %s"%line
       else:
         print >> out, pr+"           : %s"%line
     print >>out,pr+"  fp  : %-15.4f"%group.f_prime
     print >>out,pr+"  fdp : %-15.4f"%group.f_double_prime
     out.flush()
Ejemplo n.º 15
0
 def show_anomalous_scatterer_groups(self, out = None):
   if(out is None): out = sys.stdout
   pr = "REMARK   3  "
   print >>out,pr+"ANOMALOUS SCATTERER GROUPS DETAILS."
   print >>out,pr+" NUMBER OF ANOMALOUS SCATTERER GROUPS : %-6d"%\
     len(self.anomalous_scatterer_groups)
   counter = 0
   for group in self.anomalous_scatterer_groups:
     counter += 1
     print >>out,pr+" ANOMALOUS SCATTERER GROUP : %-6d"%counter
     lines = line_breaker(group.selection_string, width=45)
     for i_line, line in enumerate(lines):
       if(i_line == 0):
         print >> out, pr+"  SELECTION: %s"%line
       else:
         print >> out, pr+"           : %s"%line
     print >>out,pr+"  fp  : %-15.4f"%group.f_prime
     print >>out,pr+"  fdp : %-15.4f"%group.f_double_prime
     out.flush()
Ejemplo n.º 16
0
 def show_torsion_ncs_groups(self, out = None):
   if(out is None): out = sys.stdout
   restraint_groups = self.ncs_manager.ncs_groups
   torsion_counts=self.ncs_manager.get_number_of_restraints_per_group(
     pdb_hierarchy=self.pdb_hierarchy)
   sites_cart = self.pdb_hierarchy.atoms().extract_xyz()
   self.ncs_manager.get_torsion_rmsd(sites_cart=sites_cart)
   pr = "REMARK   3  "
   print >>out,pr+"TORSION NCS DETAILS."
   print >>out,pr+" NUMBER OF NCS GROUPS : %-6d"%len(restraint_groups)
   for i_group, ncs_group in enumerate(restraint_groups):
     count = 0
     print >>out,pr+" NCS GROUP : %-6d"%(i_group+1)
     selection_strings = ncs_group
     for selection in selection_strings:
       lines = line_breaker(selection, width=34)
       for i_line, line in enumerate(lines):
         if (i_line == 0):
           print >> out, pr+"   SELECTION          : %s"%line
         else:
           print >> out, pr+"                      : %s"%line
       count += torsion_counts[selection]
     print >> out,pr+"   RESTRAINED TORSIONS: %-d" % count
     if self.ncs_manager.torsion_rmsd is not None:
       print >> out,pr+"   BELOW LIMIT RMSD   : %-10.3f" % \
         self.ncs_manager.torsion_rmsd
     if self.ncs_manager.all_torsion_rmsd is not None:
       print >> out,pr+"   ALL RESTRAINT RMSD : %-10.3f" % \
         self.ncs_manager.all_torsion_rmsd
   if self.ncs_manager.histogram_under_limit is not None:
     print >> out, pr + "  Histogram of differences under limit:"
     self.ncs_manager.histogram_under_limit.show(
       f=out,
       prefix=pr+"  ",
       format_cutoffs="%8.3f")
   if self.ncs_manager.histogram_over_limit is not None:
     print >> out, pr + "  Histogram of differences over limit:"
     self.ncs_manager.histogram_over_limit.show(
       f=out,
       prefix=pr+"  ",
       format_cutoffs="%8.3f")
Ejemplo n.º 17
0
 def show_torsion_ncs_groups(self, out = None):
   if(out is None): out = sys.stdout
   restraint_groups = self.ncs_manager.ncs_groups
   torsion_counts=self.ncs_manager.get_number_of_restraints_per_group(
     pdb_hierarchy=self.pdb_hierarchy)
   sites_cart = self.pdb_hierarchy.atoms().extract_xyz()
   self.ncs_manager.get_torsion_rmsd(sites_cart=sites_cart)
   pr = "REMARK   3  "
   print >>out,pr+"TORSION NCS DETAILS."
   print >>out,pr+" NUMBER OF NCS GROUPS : %-6d"%len(restraint_groups)
   for i_group, ncs_group in enumerate(restraint_groups):
     count = 0
     print >>out,pr+" NCS GROUP : %-6d"%(i_group+1)
     selection_strings = ncs_group
     for selection in selection_strings:
       lines = line_breaker(selection, width=34)
       for i_line, line in enumerate(lines):
         if (i_line == 0):
           print >> out, pr+"   SELECTION          : %s"%line
         else:
           print >> out, pr+"                      : %s"%line
       count += torsion_counts[selection]
     print >> out,pr+"   RESTRAINED TORSIONS: %-d" % count
     if self.ncs_manager.torsion_rmsd is not None:
       print >> out,pr+"   BELOW LIMIT RMSD   : %-10.3f" % \
         self.ncs_manager.torsion_rmsd
     if self.ncs_manager.all_torsion_rmsd is not None:
       print >> out,pr+"   ALL RESTRAINT RMSD : %-10.3f" % \
         self.ncs_manager.all_torsion_rmsd
   if self.ncs_manager.histogram_under_limit is not None:
     print >> out, pr + "  Histogram of differences under limit:"
     self.ncs_manager.histogram_under_limit.show(
       f=out,
       prefix=pr+"  ",
       format_cutoffs="%8.3f")
   if self.ncs_manager.histogram_over_limit is not None:
     print >> out, pr + "  Histogram of differences over limit:"
     self.ncs_manager.histogram_over_limit.show(
       f=out,
       prefix=pr+"  ",
       format_cutoffs="%8.3f")
Ejemplo n.º 18
0
def remark_3_tls(tlsos, selection_strings, out = None):
  if(out is None): out = sys.stdout
  if (len(selection_strings) == 0):
    assert len(tlsos) == 1
    selection_strings = [None]
  else:
    assert len(tlsos) == len(selection_strings)
  print >> out, "REMARK   3  TLS DETAILS."
  print >> out, "REMARK   3   NUMBER OF TLS GROUPS: %-6d"%len(tlsos)
  print >> out, "REMARK   3   ORIGIN: CENTER OF MASS"
  r3 = "REMARK   3   "
  counter = 0
  for tlso, selection_string in zip(tlsos, selection_strings):
    if(selection_string is None):
      selection_string = "all"
    counter += 1
    t = tlso.t
    l = tlso.l
    s = tlso.s
    o = tlso.origin
    print >>out,r3+"TLS GROUP : %-6d"%(counter)
    lines = line_breaker(selection_string, width=45)
    for i_line, line in enumerate(lines):
      if(i_line == 0):
        print >> out, r3+" SELECTION: %s"%line
      else:
        print >> out, r3+"          : %s"%line
    print >>out,r3+" ORIGIN FOR THE GROUP (A):%9.4f%9.4f%9.4f"%(o[0],o[1],o[2])
    print >>out,r3+" T TENSOR                                            "
    print >>out,r3+"   T11:%9.4f T22:%9.4f                       "%(t[0], t[1])
    print >>out,r3+"   T33:%9.4f T12:%9.4f                       "%(t[2], t[3])
    print >>out,r3+"   T13:%9.4f T23:%9.4f                       "%(t[4], t[5])
    print >>out,r3+" L TENSOR                                            "
    print >>out,r3+"   L11:%9.4f L22:%9.4f                       "%(l[0], l[1])
    print >>out,r3+"   L33:%9.4f L12:%9.4f                       "%(l[2], l[3])
    print >>out,r3+"   L13:%9.4f L23:%9.4f                       "%(l[4], l[5])
    print >>out,r3+" S TENSOR                                            "
    print >>out,r3+"   S11:%9.4f S12:%9.4f S13:%9.4f         "%(s[0],s[1],s[2])
    print >>out,r3+"   S21:%9.4f S22:%9.4f S23:%9.4f         "%(s[3],s[4],s[5])
    print >>out,r3+"   S31:%9.4f S32:%9.4f S33:%9.4f         "%(s[6],s[7],s[8])
Ejemplo n.º 19
0
def exercise():
    from libtbx.test_utils import show_diff, Exception_expected
    from six.moves import cPickle as pickle
    #
    from libtbx.str_utils import split_keeping_spaces
    assert split_keeping_spaces(s="") == []
    assert split_keeping_spaces(s=" ") == [" "]
    assert split_keeping_spaces(s="a") == ["a"]
    assert split_keeping_spaces(s="abc") == ["abc"]
    assert split_keeping_spaces(s=" a") == [" ", "a"]
    assert split_keeping_spaces(s="  a") == ["  ", "a"]
    assert split_keeping_spaces(s="  abc") == ["  ", "abc"]
    assert split_keeping_spaces(s="  abc ") == ["  ", "abc", " "]
    assert split_keeping_spaces(s="  abc  ") == ["  ", "abc", "  "]
    assert split_keeping_spaces(s="a ") == ["a", " "]
    assert split_keeping_spaces(s="a  ") == ["a", "  "]
    assert split_keeping_spaces(s="abc  ") == ["abc", "  "]
    assert split_keeping_spaces(s="a b") == ["a", " ", "b"]
    assert split_keeping_spaces(s="a  b") == ["a", "  ", "b"]
    assert split_keeping_spaces(s="  a  b c   d ") == [
        "  ", "a", "  ", "b", " ", "c", "   ", "d", " "
    ]
    #
    from libtbx.str_utils import size_as_string_with_commas
    assert size_as_string_with_commas(0) == "0"
    assert size_as_string_with_commas(1) == "1"
    assert size_as_string_with_commas(-1) == "-1"
    assert size_as_string_with_commas(10) == "10"
    assert size_as_string_with_commas(100) == "100"
    assert size_as_string_with_commas(1000) == "1,000"
    assert size_as_string_with_commas(12345) == "12,345"
    assert size_as_string_with_commas(12345678) == "12,345,678"
    assert size_as_string_with_commas(-12345678) == "-12,345,678"
    #
    from libtbx.str_utils import show_string
    assert show_string("abc") == '"abc"'
    assert show_string("a'c") == '"a\'c"'
    assert show_string('a"c') == "'a\"c'"
    assert show_string('\'"c') == '"\'\\"c"'
    #
    from libtbx.str_utils import prefix_each_line
    assert prefix_each_line(prefix="^",
                            lines_as_one_string="""\
hello
world""") == """\
^hello
^world"""
    #
    from libtbx.str_utils import prefix_each_line_suffix
    assert prefix_each_line_suffix(prefix="^",
                                   lines_as_one_string="""\
hello
world""",
                                   suffix=" ") == """\
^hello
^world"""
    assert prefix_each_line_suffix(prefix="^",
                                   lines_as_one_string="""\
hello
world""",
                                   suffix=" ",
                                   rstrip=False) == """\
^hello%s
^world """ % " "
    #
    from libtbx.str_utils import show_sorted_by_counts
    from six.moves import cStringIO
    out = cStringIO()
    assert show_sorted_by_counts(label_count_pairs=[("b", 3), ("a", 3),
                                                    ("c", -2)],
                                 out=out,
                                 prefix="%")
    assert not show_diff(out.getvalue(), """\
%"a"  3
%"b"  3
%"c" -2
""")
    out = cStringIO()
    assert show_sorted_by_counts(label_count_pairs=[("b", -3), ("a", -3),
                                                    ("c", 2)],
                                 reverse=False,
                                 out=out,
                                 prefix="%",
                                 annotations=[None, "", "x"])
    assert not show_diff(out.getvalue(), """\
%"a" -3
%"b" -3
%"c"  2 x
""")
    #
    from libtbx.str_utils import line_breaker
    for string, expected_result in [
        ("", [""]), ("this is", ["this is"]), ("this is a", ["this is", "a"]),
        ("this is a sentence", ["this is", "a", "sentence"]),
        ("this is a longer sentence", ["this is", "a", "longer", "sentence"]),
        ("this is a very long sentence indeed",
         ["this is", "a very", "long", "sentence", "indeed"])
    ]:
        assert [block
                for block in line_breaker(string, width=7)] == expected_result
    #
    from libtbx.str_utils import StringIO
    out1 = cStringIO()
    out2 = StringIO()
    out3 = StringIO("Hello world!\n")
    print("Hello world!", file=out1)
    print("Hello world!", file=out2)
    try:
        print("Hello world!", file=out3)
    except AttributeError:
        pass
    else:
        raise Exception_expected
    out4 = pickle.loads(pickle.dumps(out2))
    out5 = pickle.loads(pickle.dumps(out3))
    assert out4.getvalue() == out1.getvalue() == out2.getvalue(
    ) == out5.getvalue()
    #
    from libtbx.str_utils import reformat_terminal_text
    txt1 = """
This is some
terminal-formatted
text which needs
to be reset.
"""
    assert (reformat_terminal_text(txt1) ==
            "This is some terminal-formatted text which needs to be reset.")
    txt2 = """
  This is more
  terminal-formatted
  text which needs
  to be reset.
"""
    #
    from libtbx.str_utils import strip_lines, rstrip_lines
    lines = ["  This is more ", "  terminal-formatted ", "  text "]
    assert (
        strip_lines(txt2) ==
        "\nThis is more\nterminal-formatted\ntext which needs\nto be reset.")
    assert (
        rstrip_lines(txt2) ==
        "\n  This is more\n  terminal-formatted\n  text which needs\n  to be reset."
    )
    #
    from libtbx.str_utils import expandtabs_track_columns

    def check(s):
        es, js = expandtabs_track_columns(s=s)
        assert len(js) == len(s)
        assert es == s.expandtabs()
        sr = "".join([es[j] for j in js])
        assert sr == s.replace("\t", " ")

    check("")
    check("\t")
    check("\t\t")
    check("\ty")
    check("x\ty")
    check("x\ty\tz")
    check("\txy\t\tz")
    check("abcdefg\txy\t\tz")
    check("ab defgh\txyz\t\tu")
    #
    from libtbx.str_utils import format_value
    assert format_value("%.4f", 1.2345678) == "1.2346"
    assert format_value("%.4f", None) == "  None"
    assert format_value("%.4f", None, replace_none_with="---") == "   ---"
    #
    from libtbx.str_utils import make_header
    out = StringIO()
    make_header("Header 1", out=out)
    assert (out.getvalue() == """
=================================== Header 1 ==================================

""")
    out = StringIO()
    make_header("Header 2", out=out)
    assert (out.getvalue() == """
=================================== Header 2 ==================================

""")
    #
    import sys
    from libtbx.str_utils import string_representation
    iset = list(range(130)) + list(range(250, 256))
    for i in iset:
        s = chr(i)
        for j in iset:
            ss = s + chr(j)
            sr = string_representation(string=ss,
                                       preferred_quote="'",
                                       alternative_quote='"')
            if sys.hexversion < 0x03000000:
                assert sr == repr(ss)
            else:
                assert eval(sr) == ss
    from libtbx.str_utils import framed_output
    out = StringIO()
    box = framed_output(out, frame='#')
    print("Hello, world!", file=box)
    box.close()
    assert (out.getvalue() == """
#################
# Hello, world! #
#################
""")
    out = StringIO()
    box = framed_output(out,
                        frame='-',
                        width=80,
                        center=True,
                        title="Refinement stats")
    box.write("r_free = 0.1234")
    box.write("  ")
    box.write("r_work = 0.1567")
    box.close()
    assert (out.getvalue() == """
|--------------------------------Refinement stats------------------------------|
|                       r_free = 0.1234  r_work = 0.1567                       |
|------------------------------------------------------------------------------|
""")
    out = StringIO()
    box = framed_output(out,
                        frame='-',
                        width=72,
                        prefix="    ",
                        title="Validation summary")
    print("Overall MolProbity score: 2.56", file=box)
    box.add_separator()
    print("""\
Ramachandran favored:  97.5 %
             outliers:  2.5 %
Rotamer outliers:       5.9 %
Clashscore:            10.9""",
          file=box)
    assert (out.getvalue() == "")
    del box
    assert (out.getvalue() == """
    |-Validation summary---------------------------------------------------|
    | Overall MolProbity score: 2.56                                       |
    |----------------------------------------------------------------------|
    | Ramachandran favored:  97.5 %                                        |
    |              outliers:  2.5 %                                        |
    | Rotamer outliers:       5.9 %                                        |
    | Clashscore:            10.9                                          |
    |----------------------------------------------------------------------|
""")
    from libtbx.str_utils import print_message_in_box
    out = StringIO()
    print_message_in_box(
        message="This is some terminal-formatted text which needs to be reset.",
        out=out,
        width=32,
        center=True,
        prefix="  ",
        frame='*')
    assert (out.getvalue() == """
  ********************************
  *         This is some         *
  *   terminal-formatted text    *
  *   which needs to be reset.   *
  ********************************
""")
    from libtbx.str_utils import make_big_header
    out = StringIO()
    make_big_header("Section title", out=out)
    assert (out.getvalue() == """
################################################################################
#                                Section title                                 #
################################################################################
""")
Ejemplo n.º 20
0
def exercise():
  from libtbx.test_utils import show_diff, Exception_expected
  import cPickle
  #
  from libtbx.str_utils import split_keeping_spaces
  assert split_keeping_spaces(s="") == []
  assert split_keeping_spaces(s=" ") == [" "]
  assert split_keeping_spaces(s="a") == ["a"]
  assert split_keeping_spaces(s="abc") == ["abc"]
  assert split_keeping_spaces(s=" a") == [" ", "a"]
  assert split_keeping_spaces(s="  a") == ["  ", "a"]
  assert split_keeping_spaces(s="  abc") == ["  ", "abc"]
  assert split_keeping_spaces(s="  abc ") == ["  ", "abc", " "]
  assert split_keeping_spaces(s="  abc  ") == ["  ", "abc", "  "]
  assert split_keeping_spaces(s="a ") == ["a", " "]
  assert split_keeping_spaces(s="a  ") == ["a", "  "]
  assert split_keeping_spaces(s="abc  ") == ["abc", "  "]
  assert split_keeping_spaces(s="a b") == ["a", " ", "b"]
  assert split_keeping_spaces(s="a  b") == ["a", "  ", "b"]
  assert split_keeping_spaces(s="  a  b c   d ") == [
    "  ", "a", "  ", "b", " ", "c", "   ", "d", " "]
  #
  from libtbx.str_utils import size_as_string_with_commas
  assert size_as_string_with_commas(0) == "0"
  assert size_as_string_with_commas(1) == "1"
  assert size_as_string_with_commas(-1) == "-1"
  assert size_as_string_with_commas(10) == "10"
  assert size_as_string_with_commas(100) == "100"
  assert size_as_string_with_commas(1000) == "1,000"
  assert size_as_string_with_commas(12345) == "12,345"
  assert size_as_string_with_commas(12345678) == "12,345,678"
  assert size_as_string_with_commas(-12345678) == "-12,345,678"
  #
  from libtbx.str_utils import show_string
  assert show_string("abc") == '"abc"'
  assert show_string("a'c") == '"a\'c"'
  assert show_string('a"c') == "'a\"c'"
  assert show_string('\'"c') == '"\'\\"c"'
  #
  from libtbx.str_utils import prefix_each_line
  assert prefix_each_line(prefix="^", lines_as_one_string="""\
hello
world""") == """\
^hello
^world"""
  #
  from libtbx.str_utils import prefix_each_line_suffix
  assert prefix_each_line_suffix(prefix="^", lines_as_one_string="""\
hello
world""", suffix=" ") == """\
^hello
^world"""
  assert prefix_each_line_suffix(prefix="^", lines_as_one_string="""\
hello
world""", suffix=" ", rstrip=False) == """\
^hello%s
^world """ % " "
  #
  from libtbx.str_utils import show_sorted_by_counts
  import cStringIO
  out = cStringIO.StringIO()
  assert show_sorted_by_counts(
    label_count_pairs=[("b", 3), ("a", 3), ("c", -2)],
    out=out, prefix="%")
  assert not show_diff(out.getvalue(), """\
%"a"  3
%"b"  3
%"c" -2
""")
  out = cStringIO.StringIO()
  assert show_sorted_by_counts(
    label_count_pairs=[("b", -3), ("a", -3), ("c", 2)], reverse=False,
     out=out, prefix="%", annotations=[None, "", "x"])
  assert not show_diff(out.getvalue(), """\
%"c"  2 x
%"a" -3
%"b" -3
""")
  #
  from libtbx.str_utils import line_breaker
  for string, expected_result in [
    ("", [""]),
    ("this is", ["this is"]),
    ("this is a", ["this is", "a"]),
    ("this is a sentence", ["this is", "a", "sentence"]),
    ("this is a longer sentence", ["this is", "a", "longer", "sentence"]),
    ("this is a very long sentence indeed",
      ["this is", "a very", "long", "sentence", "indeed"])]:
    assert [block for block in line_breaker(string, width=7)]==expected_result
  #
  from libtbx.str_utils import StringIO
  out1 = cStringIO.StringIO()
  out2 = StringIO()
  out3 = StringIO("Hello world!\n")
  print >> out1, "Hello world!"
  print >> out2, "Hello world!"
  try :
      print >> out3, "Hello world!"
  except AttributeError :
    pass
  else :
    raise Exception_expected
  out4 = cPickle.loads(cPickle.dumps(out2))
  out5 = cPickle.loads(cPickle.dumps(out3))
  assert out4.getvalue()==out1.getvalue()==out2.getvalue()==out5.getvalue()
  #
  from libtbx.str_utils import reformat_terminal_text
  txt1 = """
This is some
terminal-formatted
text which needs
to be reset.
"""
  assert (reformat_terminal_text(txt1) ==
          "This is some terminal-formatted text which needs to be reset.")
  txt2 = """
  This is more
  terminal-formatted
  text which needs
  to be reset.
"""
  #
  from libtbx.str_utils import strip_lines, rstrip_lines
  lines = ["  This is more ", "  terminal-formatted ", "  text "]
  assert (strip_lines(txt2) ==
    "\nThis is more\nterminal-formatted\ntext which needs\nto be reset.")
  assert (rstrip_lines(txt2) ==
    "\n  This is more\n  terminal-formatted\n  text which needs\n  to be reset."
  )
  #
  from libtbx.str_utils import expandtabs_track_columns
  def check(s):
    es,js = expandtabs_track_columns(s=s)
    assert len(js) == len(s)
    assert es == s.expandtabs()
    sr = "".join([es[j] for j in js])
    assert sr == s.replace("\t", " ")
  check("")
  check("\t")
  check("\t\t")
  check("\ty")
  check("x\ty")
  check("x\ty\tz")
  check("\txy\t\tz")
  check("abcdefg\txy\t\tz")
  check("ab defgh\txyz\t\tu")
  #
  from libtbx.str_utils import format_value
  assert format_value("%.4f", 1.2345678) == "1.2346"
  assert format_value("%.4f", None) == "  None"
  assert format_value("%.4f", None, replace_none_with="---") == "   ---"
  #
  from libtbx.str_utils import make_header
  out = StringIO()
  make_header("Header 1", out=out)
  assert (out.getvalue() == """
=================================== Header 1 ==================================

""")
  out = StringIO()
  make_header("Header 2", out=out)
  assert (out.getvalue() == """
=================================== Header 2 ==================================

""")
  #
  from libtbx.str_utils import string_representation
  iset = range(130) + range(250,256)
  for i in iset:
    s = chr(i)
    for j in iset:
      ss = s + chr(j)
      assert string_representation(
        string=ss, preferred_quote="'", alternative_quote='"') == repr(ss)
  from libtbx.str_utils import framed_output
  out = StringIO()
  box = framed_output(out, frame='#')
  print >> box, "Hello, world!"
  box.close()
  assert (out.getvalue() == """
#################
# Hello, world! #
#################
""")
  out = StringIO()
  box = framed_output(out, frame='-', width=80, center=True,
    title="Refinement stats")
  box.write("r_free = 0.1234")
  box.write("  ")
  box.write("r_work = 0.1567")
  box.close()
  assert (out.getvalue() == """
|--------------------------------Refinement stats------------------------------|
|                       r_free = 0.1234  r_work = 0.1567                       |
|------------------------------------------------------------------------------|
""")
  out = StringIO()
  box = framed_output(out, frame='-', width=72, prefix="    ",
    title="Validation summary")
  print >> box, "Overall MolProbity score: 2.56"
  box.add_separator()
  print >> box, """\
Ramachandran favored:  97.5 %
             outliers:  2.5 %
Rotamer outliers:       5.9 %
Clashscore:            10.9"""
  assert (out.getvalue() == "")
  del box
  assert (out.getvalue() == """
    |-Validation summary---------------------------------------------------|
    | Overall MolProbity score: 2.56                                       |
    |----------------------------------------------------------------------|
    | Ramachandran favored:  97.5 %                                        |
    |              outliers:  2.5 %                                        |
    | Rotamer outliers:       5.9 %                                        |
    | Clashscore:            10.9                                          |
    |----------------------------------------------------------------------|
""")
  from libtbx.str_utils import print_message_in_box
  out = StringIO()
  print_message_in_box(
    message="This is some terminal-formatted text which needs to be reset.",
    out=out,
    width=32,
    center=True,
    prefix="  ",
    frame='*')
  assert (out.getvalue() == """
  ********************************
  *         This is some         *
  *   terminal-formatted text    *
  *   which needs to be reset.   *
  ********************************
""")