コード例 #1
0
 def load_reflections_file(self,
                           file_name,
                           set_array=True,
                           data_only=False):
     file_name = to_str(file_name)
     if (file_name != ""):
         from iotbx.reflection_file_reader import any_reflection_file
         self.viewer.isnewfile = True
         #self.params.NGL_HKLviewer.mergedata = None
         self.viewer.iarray = -1
         self.viewer.colour_scene_id = -1
         self.viewer.radii_scene_id = -1
         self.viewer.match_valarrays = []
         self.viewer.proc_arrays = []
         self.spacegroup_choices = []
         display.reset_settings()
         self.settings = display.settings()
         self.viewer.settings = self.params.NGL_HKLviewer.viewer
         self.viewer.mapcoef_fom_dict = {}
         try:
             hkl_file = any_reflection_file(file_name)
             arrays = hkl_file.as_miller_arrays(
                 merge_equivalents=False,
             )  #observation_type_callback=misc_dialogs.get_shelx_file_data_type)
             #arrays = f.file_server.miller_arrays
         except Exception as e:
             self.NewFileLoaded = False
             self.mprint(to_str(e))
             arrays = []
         valid_arrays = []
         self.array_infostrs = []
         self.array_infotpls = []
         for array in arrays:
             #if array.is_hendrickson_lattman_array() :
             #  continue
             #elif (data_only) :
             if (not array.is_real_array()) and (not array.is_complex_array()) \
              and (not array.is_integer_array()) and (not array.is_bool_array()) :
                 self.mprint('Ignoring miller array \"%s\" of %s' \
                   %(array.info().label_string(), type(array.data()[0]) ) )
                 continue
             self.array_infostrs.append(
                 ArrayInfo(array, self.mprint).infostr)
             self.array_infotpls.append(
                 ArrayInfo(array, self.mprint).infotpl)
             valid_arrays.append(array)
         self.valid_arrays = valid_arrays
         self.mprint("Miller arrays in this file:")
         for e in self.array_infostrs:
             self.mprint("%s" % e)
         self.NewFileLoaded = True
         if (len(valid_arrays) == 0):
             msg = "No arrays of the supported types in this file."
             self.mprint(msg)
             self.NewFileLoaded = False
             return False
         elif (len(valid_arrays) >= 1):
             if (set_array):
                 self.set_miller_array()
             return True
コード例 #2
0
    def flush_requests(self, show_timings=False):
        t1 = time.time()
        result = None
        while len(self._pending) > 0:
            (methodname, params) = self._pending.pop(0)

            # remove any unicode types in params
            if (isinstance(params, unicode)):
                params = to_str(params)
            elif (isinstance(params, list) or isinstance(params, tuple)):
                new_params = list(params)
                for i in xrange(len(params)):
                    if (isinstance(params[i], unicode)):
                        new_params[i] = to_str(params[i])
                    else:
                        new_params[i] = params[i]
                if (isinstance(params, tuple)):
                    new_params = tuple(new_params)
                params = new_params

            # call a method on the remote server
            try:
                request = xmlrpclib.dumps(params,
                                          methodname,
                                          encoding=self.__encoding,
                                          allow_none=self.__allow_none)

                response = self.__transport.request(self.__host,
                                                    self.__handler,
                                                    request,
                                                    verbose=self.__verbose)

                if len(response) == 1:
                    result = response[0]
            except KeyboardInterrupt:
                raise
            except Exception, e:
                msg = to_str(e)
                if (hasattr(e, "errno")):
                    if (e.errno in [32, 54, 61, 104, 111, 10054, 10061]):
                        self._pending.insert(0, (methodname, params))
                        t = time.strftime("%H:%M:%S", time.localtime())
                        self._errors.append("%s -- %s" % (t, msg))
                        break
                if ("timed out" in msg):
                    print "XMLRPC timeout, ignoring request"
                    self._timeouts += 1
                elif msg.startswith("<ProtocolError "):
                    self._pending = []
                    break
                elif ("exceptions.SystemExit" in msg):
                    self._pending = []
                    break
                else:
                    msg = "XMLRPC error: %s\nMethod: %s\nParams: %s\n" % \
                      (msg, to_str(methodname), ", ".join([ to_str(p) for p in params ]))
                    if (not self.raise_errors):
                        print >> sys.stderr, msg
                    else:
                        raise RuntimeError(msg)
コード例 #3
0
ファイル: frames.py プロジェクト: dials/cctbx
    def load_reflections_file(self,
                              file_name,
                              set_array=True,
                              data_only=False):
        file_name = to_str(file_name)
        if (file_name != ""):
            from iotbx.reflection_file_reader import any_reflection_file
            from iotbx.gui_tools.reflections import get_array_description
            try:
                hkl_file = any_reflection_file(file_name)
            except Exception as e:
                raise Sorry(to_str(e))
            arrays = hkl_file.as_miller_arrays(
                merge_equivalents=False,
            )  #observation_type_callback=misc_dialogs.get_shelx_file_data_type)
            #arrays = f.file_server.miller_arrays
            valid_arrays = []
            array_info = []
            for array in arrays:
                if array.is_hendrickson_lattman_array():
                    continue
                elif (data_only):
                    if (not array.is_real_array()) and (
                            not array.is_complex_array()):
                        continue
                labels = array.info().label_string()
                desc = get_array_description(array)
                array_info.append("%s (%s)" % (labels, desc))
                valid_arrays.append(array)
            self.valid_arrays = valid_arrays
            if (len(valid_arrays) == 0):
                msg = "No arrays of the supported types in this file."
                raise Sorry(msg)
            elif (len(valid_arrays) == 1):
                if (set_array):
                    self.set_miller_array(valid_arrays[0])
                return valid_arrays[0]
            else:
                #dlg = SelectArrayDialog(self, -1, "Select data")
                dlg = wx.SingleChoiceDialog(
                    parent=None,
                    message="Please select the data you wish to view:",
                    caption="Select data",
                    choices=array_info)
                # print("kau labels info is", array_info) #Kau added
                # print("Kau printing array_info from calling ", array_info)

                if (dlg.ShowModal() == wx.ID_OK):
                    sel = dlg.GetSelection()
                    if (set_array):
                        self.set_miller_array(valid_arrays[sel])
                    wx.CallAfter(dlg.Destroy)
                    self.settings_panel.update_column_choices(
                        array_info, valid_arrays, sel)  # kau added
                    # self.settings_panel.update_column_choices(array_info,valid_arrays,sel) # kau added
                    return valid_arrays[sel]
                wx.CallAfter(dlg.Destroy)

        raise Abort()
コード例 #4
0
 def check_file(self):
     import coot  # import dependency
     if os.path.exists(self.file_name):
         file_mtime = os.path.getmtime(self.file_name)
         if file_mtime > self.last_mtime:
             if self.model_imol is not None:
                 clear_and_update_molecule_from_file(
                     self.model_imol, to_str(self.file_name))
             else:
                 self.model_imol = read_pdb(to_str(self.file_name))
             self.last_mtime = file_mtime
コード例 #5
0
ファイル: watch_file.py プロジェクト: cctbx/cctbx-playground
 def check_file (self) :
   import coot # import dependency
   if os.path.exists(self.file_name) :
     file_mtime = os.path.getmtime(self.file_name)
     if file_mtime > self.last_mtime :
       if self.model_imol is not None :
         clear_and_update_molecule_from_file(self.model_imol,
           to_str(self.file_name))
       else :
         self.model_imol = read_pdb(to_str(self.file_name))
       self.last_mtime = file_mtime
コード例 #6
0
 async def ReceiveMessage(self):
     while True:
         await asyncio.sleep(self.sleeptime)
         if self.was_disconnected in [
                 4242,  # reload
                 4241,  # javascriptcleanup
                 1006,  # WebSocketServerProtocol.close_code is absent
                 1001,  # normal exit
                 1005,
                 1000
         ]:
             await self.mywebsock.wait_closed()
             return  # shutdown
         if self.parent.viewerparams.scene_id is None or self.parent.miller_array is None \
             or self.websockclient is None or self.mywebsock.client_connected is None:
             await asyncio.sleep(self.sleeptime)
             continue
         message = ""
         try:  # use EAFP rather than LBYL style with websockets
             message = await self.mywebsock.recv()
         except Exception as e:
             if self.was_disconnected != 4242:
                 self.mprint(to_str(e) + "\n" +
                             traceback.format_exc(limit=10),
                             verbose=1)
             #continue
         await self.OnWebsocketClientMessage(None, None, message)
コード例 #7
0
  def __init__(self, parent, items,
               label='',
               label_size=(100, -1),
               label_style='normal',
               sub_labels=[],
               ctrl_size=(300, -1)):

    CtrlBase.__init__(self, parent=parent, label_style=label_style)

    if label != '':
      opt_box = wx.FlexGridSizer(1, len(items) * 2 + 1, 0, 10)
      self.txt = wx.StaticText(self, label=label, size=label_size)
      self.txt.SetFont(self.font)
      opt_box.Add(self.txt, flag=wx.ALIGN_CENTER_VERTICAL)
    else:
      opt_box = wx.FlexGridSizer(1, len(items) * 2, 0, 10)

    for key, value in items:
      if sub_labels != []:
        sub_label = u.to_str(sub_labels[items.index((key, value))])
      else:
        sub_label = key

      if len(items) > 1:
        opt_label = wx.StaticText(self, id=wx.ID_ANY, label=sub_label)
        opt_box.Add(opt_label, flag=wx.ALIGN_CENTER_VERTICAL)

      item = wx.TextCtrl(self, id=wx.ID_ANY, size=ctrl_size,
                         style=wx.TE_PROCESS_ENTER)
      item.SetValue(str(value))
      opt_box.Add(item, flag=wx.ALIGN_CENTER_VERTICAL)
      self.__setattr__(key, item)

    self.SetSizer(opt_box)
コード例 #8
0
 def StartWebsocket(self):
     try:
         if self.websockeventloop is not None:
             self.mprint("websockeventloop already running", verbose=1)
             return
         if self.websockeventloop is None:
             self.websockeventloop = asyncio.new_event_loop()
             asyncio.set_event_loop(self.websockeventloop)
             if self.parent.debug is not None:
                 self.websockeventloop.set_debug(True)
                 import logging
                 logging.getLogger("asyncio").setLevel(logging.WARNING)
         self.server = websockets.serve(
             self.WebSockHandler,
             '127.0.0.1',
             self.websockport,
             create_protocol=MyWebSocketServerProtocol)
         self.websockeventloop.run_until_complete(self.server)
         self.mprint("starting WebSockHandler on port %s" %
                     str(self.websockport),
                     verbose=1)
         # run_forever() blocks execution so put in a separate thread
         self.wst = threading.Thread(
             target=self.websockeventloop.run_forever)
         self.wst.daemon = True
         self.wst.start()
         if not self.server:
             raise Sorry("Could not connect to web browser")
     except Exception as e:
         self.mprint(to_str(e) + "\n" + traceback.format_exc(limit=10),
                     verbose=0)
コード例 #9
0
 async def ReceiveMessage(self):
     while True:
         await asyncio.sleep(self.sleeptime)
         if self.was_disconnected in [
                 4242,  # reload
                 4241,  # javascriptcleanup
                 1006,  # WebSocketServerProtocol.close_code is absent
                 1001,  # normal exit
                 1005,
                 1000
         ]:
             await self.mywebsock.wait_closed()
             return  # shutdown
         if self.websockclient is None or self.mywebsock.client_connected is None:
             await asyncio.sleep(self.sleeptime)
             continue
         message = ""
         try:  # use EAFP rather than LBYL style with websockets
             message = await self.mywebsock.recv()
         except Exception as e:
             if self.was_disconnected != 4242:
                 self.mprint(to_str(e) + "\n" +
                             traceback.format_exc(limit=10),
                             verbose=1)
         self.clientmsgqueue_sem.acquire(blocking=True,
                                         timeout=lock_timeout)
         self.clientmsgqueue.append(message)
         self.clientmsgqueue_sem.release()
コード例 #10
0
ファイル: frames.py プロジェクト: dials/cctbx
 def OnLoadFile(self, evt):
     file_name = wx.FileSelector(
         "Reflections file",
         wildcard="Reflection files (*.mtz, *.sca, *.hkl)|*.mtz;*.sca;*.hkl",
         default_path=os.getcwd(),
         flags=wx.FD_OPEN)
     self.load_reflections_file(to_str(file_name))
コード例 #11
0
 def __init__ (self, pdb_file, map_file, needs_rebuild=False) :
   self.file_name = pdb_file
   self.needs_rebuild = needs_rebuild
   import gtk
   import coot
   import coot_python
   toolbar = coot_python.main_toolbar()
   assert (toolbar is not None)
   return_button = gtk.ToolButton()
   return_button.set_label("Return to PHENIX")
   return_button.set_is_important(True)
   toolbar.insert(return_button, -1)
   return_button.connect("clicked", self.OnReturn)
   return_button.show()
   maps_button = gtk.ToolButton()
   maps_button.set_label("Fetch new maps")
   maps_button.set_is_important(True)
   toolbar.insert(maps_button, -1)
   maps_button.connect("clicked", self.OnNewMaps)
   maps_button.show()
   self._imol = read_pdb(to_str(pdb_file))
   set_molecule_bonds_colour_map_rotation(self._imol, 30)
   self._map_mols = []
   self.load_maps(map_file)
   dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO,
     gtk.BUTTONS_OK, "You may now edit your model to prepare for further "+
     "building and refinement.   When you are finished, "+
     "click the \"Save model and return\" button on the toolbar, then close "+
     "Coot.  If you want to recalculate the map coefficients, click \"Fetch "+
     "new maps\".")
   dialog.run()
   dialog.destroy()
コード例 #12
0
 def find_missing_atoms (self, out=None) :
   '''
   Function for finding missing protein atoms
   Derived from run_find_missing function in phenix/validation/__init__.py
   '''
   if out is None :
     out = sys.stdout
   self.missing_atoms = []
   # make_header("Finding missing atoms", out=out)
   try :
     missing_list = rotamer_eval.eval_sidechain_completeness(
       pdb_hierarchy=self.pdb_hierarchy,
       ignore_hydrogens=True,
       report_whole_res=True,
       return_ca_pos=True)
   except Exception as e :
     print(to_str(e), file=out)
   else :
     for (res_info, missing_atoms, xyz) in missing_list :
       if len(missing_atoms) == 0 :
         continue
       chain_id = res_info[0:2].strip()
       try :
         resseq = int(res_info[2:6])
       except ValueError : # FIXME use hybrid36?
         print("  warning: indecipherable residue number '%s'" % \
           res_info[2:6], file=out)
         print(res_info)
         continue
       alt = res_info[-4]
       resname = res_info[-3:]
       # self.get_residue_info((chain_id, resseq, resname, alt), "missing")
       self.missing_atoms.append((chain_id, "%s %s" % (resname, str(resseq)),
         alt, ", ".join(missing_atoms),
         "chain '%s' and resseq %s" % (chain_id, str(resseq)), xyz))
コード例 #13
0
 def GetValue(self):
   val = self._path_text.GetValue().strip()
   if (isinstance(val, unicode)) and wxtbx.is_unicode_build():
     return to_str(val)
   else :
     assert isinstance(val, str)
     return val
コード例 #14
0
 def __init__(self, pdb_file, map_file, needs_rebuild=False):
     self.file_name = pdb_file
     self.needs_rebuild = needs_rebuild
     import gtk
     import coot
     import coot_python
     toolbar = coot_python.main_toolbar()
     assert (toolbar is not None)
     return_button = gtk.ToolButton()
     return_button.set_label("Return to PHENIX")
     return_button.set_is_important(True)
     toolbar.insert(return_button, -1)
     return_button.connect("clicked", self.OnReturn)
     return_button.show()
     maps_button = gtk.ToolButton()
     maps_button.set_label("Fetch new maps")
     maps_button.set_is_important(True)
     toolbar.insert(maps_button, -1)
     maps_button.connect("clicked", self.OnNewMaps)
     maps_button.show()
     self._imol = read_pdb(to_str(pdb_file))
     set_molecule_bonds_colour_map_rotation(self._imol, 30)
     self._map_mols = []
     self.load_maps(map_file)
     dialog = gtk.MessageDialog(
         None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
         "You may now edit your model to prepare for further " +
         "building and refinement.   When you are finished, " +
         "click the \"Save model and return\" button on the toolbar, then close "
         +
         "Coot.  If you want to recalculate the map coefficients, click \"Fetch "
         + "new maps\".")
     dialog.run()
     dialog.destroy()
コード例 #15
0
ファイル: path.py プロジェクト: cctbx/cctbx-playground
 def GetValue (self) :
   val = self._path_text.GetValue().strip()
   if (isinstance(val, unicode)) and wxtbx.is_unicode_build() :
     return to_str(val)
   else :
     assert isinstance(val, str)
     return val
コード例 #16
0
ファイル: text_base.py プロジェクト: cctbx/cctbx-playground
 def GetValue (self) :
   val = wx.TextCtrl.GetValue(self)
   if wxtbx.is_unicode_build() :
     return to_str(val)
   else :
     assert isinstance(val, str)
     return val
コード例 #17
0
ファイル: text_base.py プロジェクト: zhuligs/cctbx_project
 def GetValue(self):
     val = wx.TextCtrl.GetValue(self)
     if wxtbx.is_unicode_build():
         return to_str(val)
     else:
         assert isinstance(val, str)
         return val
コード例 #18
0
 def __init__(self, millarr, mprint=sys.stdout.write):
     from iotbx.gui_tools.reflections import get_array_description
     data = millarr.data()
     if (isinstance(data, flex.int)):
         data = [e for e in data if e != display.inanval]
     if millarr.is_complex_array():
         data = flex.abs(millarr.data())
     data = [e for e in data if not math.isnan(e)]
     self.maxdata = max(data)
     self.mindata = min(data)
     self.maxsigmas = self.minsigmas = None
     if millarr.sigmas() is not None:
         data = millarr.sigmas()
         data = [e for e in data if not math.isnan(e)]
         self.maxsigmas = max(data)
         self.minsigmas = min(data)
     self.minmaxdata = (roundoff(self.mindata), roundoff(self.maxdata))
     self.minmaxsigs = (roundoff(self.minsigmas), roundoff(self.maxsigmas))
     self.labels = self.desc = ""
     #import code, traceback; code.interact(local=locals(), banner="".join( traceback.format_stack(limit=10) ) )
     if millarr.info():
         self.labels = millarr.info().label_string()
         self.desc = get_array_description(millarr)
     self.span = ("?", "?")
     dmin = 0.0
     dmax = 0.0
     try:
         self.span = (millarr.index_span().min(),
                      millarr.index_span().max())
         dmin = millarr.d_max_min()[1]
         dmax = millarr.d_max_min()[0]
     except Exception, e:
         mprint(to_str(e))
コード例 #19
0
ファイル: frames.py プロジェクト: cctbx/cctbx-playground
 def load_reflections_file (self, file_name, set_array=True,
     data_only=False) :
   file_name = to_str(file_name)
   if (file_name != "") :
     from iotbx.reflection_file_reader import any_reflection_file
     from iotbx.gui_tools.reflections import get_array_description
     try :
       hkl_file = any_reflection_file(file_name)
     except Exception, e :
       raise Sorry(to_str(e))
     arrays = hkl_file.as_miller_arrays(merge_equivalents=False,
       )#observation_type_callback=misc_dialogs.get_shelx_file_data_type)
     #arrays = f.file_server.miller_arrays
     valid_arrays = []
     array_info = []
     for array in arrays :
       if array.is_hendrickson_lattman_array() :
         continue
       elif (data_only) :
         if (not array.is_real_array()) and (not array.is_complex_array()) :
           continue
       labels = array.info().label_string()
       desc = get_array_description(array)
       array_info.append("%s (%s)" % (labels, desc))
       valid_arrays.append(array)
     if (len(valid_arrays) == 0) :
       msg = "No arrays of the supported types in this file."
       raise Sorry(msg)
     elif (len(valid_arrays) == 1) :
       if (set_array) :
         self.set_miller_array(valid_arrays[0])
       return valid_arrays[0]
     else :
       #dlg = SelectArrayDialog(self, -1, "Select data")
       dlg = wx.SingleChoiceDialog(parent=None,
         message="Please select the data you wish to view:",
         caption="Select data",
         choices=array_info)
       if (dlg.ShowModal() == wx.ID_OK) :
         sel = dlg.GetSelection()
         if (set_array) :
           self.set_miller_array(valid_arrays[sel])
         wx.CallAfter(dlg.Destroy)
         return valid_arrays[sel]
       wx.CallAfter(dlg.Destroy)
コード例 #20
0
ファイル: frames.py プロジェクト: cctbx/cctbx-playground
 def OnSave (self, evt) :
   output_file = wx.FileSelector("Save image as:",
     default_path=os.getcwd(),
     default_filename="hklview.png",
     wildcard="PNG image (*.png)|*.png",
     flags=wx.SAVE)
   if (output_file != "") :
     self.viewer.save_screen_shot(file_name=to_str(output_file),
       extensions=["png"])
コード例 #21
0
ファイル: frames.py プロジェクト: dials/cctbx
 def OnSave(self, evt):
     output_file = wx.FileSelector("Save image as:",
                                   default_path=os.getcwd(),
                                   default_filename="hklview.png",
                                   wildcard="PNG image (*.png)|*.png",
                                   flags=wx.FD_SAVE)
     if (output_file != ""):
         self.viewer.save_screen_shot(file_name=to_str(output_file),
                                      extensions=["png"])
コード例 #22
0
ファイル: info_panels.py プロジェクト: TheApacheCats/cctbx
 def set_map_coeffs(self, array):
   assert (array.is_complex_array())
   self.map_txt.SetLabel(str(array.info().label_string()))
   self._current_array = array
   map = array.fft_map(resolution_factor=0.25)
   self._current_map = map
   self.info_panel = wx.Panel(self.panel, -1)
   self.panel_sizer.Add(self.info_panel, 1, wx.ALL|wx.EXPAND)
   szr = wx.BoxSizer(wx.VERTICAL)
   self.info_panel.SetSizer(szr)
   box = wx.StaticBox(self.info_panel, -1, "Map info:")
   box_szr = wx.StaticBoxSizer(box, wx.VERTICAL)
   szr.Add(box_szr, 1, wx.EXPAND|wx.ALL, 5)
   grid = wx.FlexGridSizer(cols=2)
   box_szr.Add(grid, 0, wx.EXPAND)
   import iotbx.map_tools
   info_list = iotbx.map_tools.get_map_summary(map)
   for label, value in info_list :
     txt1 = wx.StaticText(self.info_panel, -1, label + ":")
     font = txt1.GetFont()
     font.SetWeight(wx.FONTWEIGHT_BOLD)
     txt1.SetFont(font)
     grid.Add(txt1, 0, ALN_FLAGS, 5)
     str_value = to_str(value)
     alert = False
     if (str_value.endswith("***")):
       str_value = re.sub("\s*\*\*\*", "", str_value)
       alert = True
     txt2 = wx.StaticText(self.info_panel, -1, str_value)
     font2 = txt2.GetFont()
     font2.SetFamily(wx.FONTFAMILY_MODERN)
     if (alert):
       font2.SetWeight(wx.FONTWEIGHT_BOLD)
       txt2.SetForegroundColour((200,0,0))
       txt1.SetForegroundColour((200,0,0))
     txt2.SetFont(font2)
     grid.Add(txt2, 0, ALN_FLAGS, 5)
   self.histogram = wxtbx.plots.histogram(self.info_panel, figure_size=(6,4))
   self.draw_plot(n_bins=20, log_scale=False)
   box_szr.Add(self.histogram, 1, wx.EXPAND, 5)
   hbox = wx.BoxSizer(wx.HORIZONTAL)
   box_szr.Add(hbox, 0, wx.TOP, 5)
   ip = self.info_panel
   btn = wx.Button(ip, -1, "Save plot to file...")
   self.Bind(wx.EVT_BUTTON, lambda evt: self.histogram.save_image(), btn)
   hbox.Add(btn, 0, ALN_FLAGS, 5)
   hbox.Add(wx.StaticText(ip, label="Number of bins:"), 0, ALN_FLAGS, 5)
   self.n_bins_ctrl = wx.SpinCtrl(ip, value="20", min=10, max=50, initial=20)
   self.Bind(wx.EVT_SPINCTRL, self.OnRedraw, self.n_bins_ctrl)
   hbox.Add(self.n_bins_ctrl, 0, ALN_FLAGS, 5)
   self.log_scale_box = wx.CheckBox(ip, label="Use log scale for Y-axis")
   hbox.Add(self.log_scale_box, 0, ALN_FLAGS, 5)
   self.Bind(wx.EVT_CHECKBOX, self.OnRedraw, self.log_scale_box)
   szr.Fit(self.info_panel)
   self.panel.Layout()
   self.panel_sizer.Fit(self.panel)
   self.Fit()
コード例 #23
0
 def load_maps (self, map_file) :
   if (len(self._map_mols) > 0) :
     set_colour_map_rotation_for_map(0)
     for imol in self._map_mols :
       close_molecule(imol)
   else :
     set_colour_map_rotation_for_map(10)
   print "Loading %s" % to_str(map_file)
   self._map_mols = []
   map_imol = auto_read_make_and_draw_maps(to_str(map_file))
   if (isinstance(map_imol, int)) :
     # XXX this may be dangerous, but auto_read_make_and_draw_maps only returns
     # the last imol
     self._map_mols = [ map_imol - 1, map_imol ]
   else :
     self._map_mols = map_imol
   set_imol_refinement_map(self._map_mols[0])
   set_scrollable_map(self._map_mols[0])
コード例 #24
0
ファイル: info_panels.py プロジェクト: cctbx/cctbx-playground
 def set_map_coeffs (self, array) :
   assert (array.is_complex_array())
   self.map_txt.SetLabel(str(array.info().label_string()))
   self._current_array = array
   map = array.fft_map(resolution_factor=0.25)
   self._current_map = map
   self.info_panel = wx.Panel(self.panel, -1)
   self.panel_sizer.Add(self.info_panel, 1, wx.ALL|wx.EXPAND)
   szr = wx.BoxSizer(wx.VERTICAL)
   self.info_panel.SetSizer(szr)
   box = wx.StaticBox(self.info_panel, -1, "Map info:")
   box_szr = wx.StaticBoxSizer(box, wx.VERTICAL)
   szr.Add(box_szr, 1, wx.EXPAND|wx.ALL, 5)
   grid = wx.FlexGridSizer(cols=2)
   box_szr.Add(grid, 0, wx.EXPAND)
   import iotbx.map_tools
   info_list = iotbx.map_tools.get_map_summary(map)
   for label, value in info_list :
     txt1 = wx.StaticText(self.info_panel, -1, label + ":")
     font = txt1.GetFont()
     font.SetWeight(wx.FONTWEIGHT_BOLD)
     txt1.SetFont(font)
     grid.Add(txt1, 0, ALN_FLAGS, 5)
     str_value = to_str(value)
     alert = False
     if (str_value.endswith("***")) :
       str_value = re.sub("\s*\*\*\*", "", str_value)
       alert = True
     txt2 = wx.StaticText(self.info_panel, -1, str_value)
     font2 = txt2.GetFont()
     font2.SetFamily(wx.FONTFAMILY_MODERN)
     if (alert) :
       font2.SetWeight(wx.FONTWEIGHT_BOLD)
       txt2.SetForegroundColour((200,0,0))
       txt1.SetForegroundColour((200,0,0))
     txt2.SetFont(font2)
     grid.Add(txt2, 0, ALN_FLAGS, 5)
   self.histogram = wxtbx.plots.histogram(self.info_panel, figure_size=(6,4))
   self.draw_plot(n_bins=20, log_scale=False)
   box_szr.Add(self.histogram, 1, wx.EXPAND, 5)
   hbox = wx.BoxSizer(wx.HORIZONTAL)
   box_szr.Add(hbox, 0, wx.TOP, 5)
   ip = self.info_panel
   btn = wx.Button(ip, -1, "Save plot to file...")
   self.Bind(wx.EVT_BUTTON, lambda evt: self.histogram.save_image(), btn)
   hbox.Add(btn, 0, ALN_FLAGS, 5)
   hbox.Add(wx.StaticText(ip, label="Number of bins:"), 0, ALN_FLAGS, 5)
   self.n_bins_ctrl = wx.SpinCtrl(ip, value="20", min=10, max=50, initial=20)
   self.Bind(wx.EVT_SPINCTRL, self.OnRedraw, self.n_bins_ctrl)
   hbox.Add(self.n_bins_ctrl, 0, ALN_FLAGS, 5)
   self.log_scale_box = wx.CheckBox(ip, label="Use log scale for Y-axis")
   hbox.Add(self.log_scale_box, 0, ALN_FLAGS, 5)
   self.Bind(wx.EVT_CHECKBOX, self.OnRedraw, self.log_scale_box)
   szr.Fit(self.info_panel)
   self.panel.Layout()
   self.panel_sizer.Fit(self.panel)
   self.Fit()
コード例 #25
0
 def load_maps(self, map_file):
     if (len(self._map_mols) > 0):
         set_colour_map_rotation_for_map(0)
         for imol in self._map_mols:
             close_molecule(imol)
     else:
         set_colour_map_rotation_for_map(10)
     print "Loading %s" % to_str(map_file)
     self._map_mols = []
     map_imol = auto_read_make_and_draw_maps(to_str(map_file))
     if (isinstance(map_imol, int)):
         # XXX this may be dangerous, but auto_read_make_and_draw_maps only returns
         # the last imol
         self._map_mols = [map_imol - 1, map_imol]
     else:
         self._map_mols = map_imol
     set_imol_refinement_map(self._map_mols[0])
     set_scrollable_map(self._map_mols[0])
コード例 #26
0
 def set_file(self, file_name):
     self.file_name = os.path.abspath(file_name)
     from iotbx import file_reader
     import iotbx.pdb
     self._pdb_in = file_reader.any_file(
         file_name,
         force_type="pdb",
         raise_sorry_if_errors=True,
         raise_sorry_if_not_expected_format=True)
     self._pdb_in.check_file_type("pdb")
     self._hierarchy = self._pdb_in.file_object.hierarchy
     info_list = iotbx.pdb.show_file_summary(
         pdb_in=self._pdb_in.file_object, hierarchy=self._hierarchy)
     self.SetTitle("Info for %s" % to_unicode(self.file_name))
     self.file_txt.SetLabel(to_unicode(self.file_name))
     if (self.info_panel is not None):
         self.panel_sizer.Detach(self.info_panel)
         self.info_panel.Destroy()
     self.info_panel = wx.Panel(self.panel, -1)
     self.panel_sizer.Add(self.info_panel, 1, wx.ALL | wx.EXPAND)
     szr = wx.BoxSizer(wx.VERTICAL)
     self.info_panel.SetSizer(szr)
     box = wx.StaticBox(self.info_panel, -1, "File contents:")
     box_szr = wx.StaticBoxSizer(box, wx.VERTICAL)
     szr.Add(box_szr, 1, wx.EXPAND | wx.ALL, 5)
     grid = wx.FlexGridSizer(cols=2)
     box_szr.Add(grid, 1, wx.EXPAND)
     for label, value in info_list:
         txt1 = wx.StaticText(self.info_panel, -1, label + ":")
         font = txt1.GetFont()
         font.SetWeight(wx.FONTWEIGHT_BOLD)
         txt1.SetFont(font)
         grid.Add(txt1, 0, ALN_FLAGS, 5)
         str_value = to_str(value)
         alert = False
         if (str_value.endswith("***")):
             str_value = re.sub("\s*\*\*\*", "", str_value)
             alert = True
         txt2 = wx.StaticText(self.info_panel, -1, str_value)
         font2 = txt2.GetFont()
         font2.SetFamily(wx.FONTFAMILY_MODERN)
         if (alert):
             font2.SetWeight(wx.FONTWEIGHT_BOLD)
             txt2.SetForegroundColour((200, 0, 0))
             txt1.SetForegroundColour((200, 0, 0))
         txt2.SetFont(font2)
         grid.Add(txt2, 0, ALN_FLAGS, 5)
     if (len(self._hierarchy.models()) == 1):
         if (len(self._hierarchy.models()[0].chains()) > 1):
             btn = wx.Button(self.info_panel, -1, "B-factors by chain...")
             szr.Add(btn, 0, wx.ALL, 5)
             self.Bind(wx.EVT_BUTTON, self.OnShowChainBstats, btn)
     szr.Fit(self.info_panel)
     self.panel.Layout()
     self.panel_sizer.Fit(self.panel)
     self.Fit()
コード例 #27
0
 def update_model(self, pdb_file):
     """
 Example of a user-defined function which will automatically be made
 accessible via XML-RPC.
 """
     import coot
     if (self.current_imol is None):
         self.current_imol = read_pdb(to_str(pdb_file))
     else:
         clear_and_update_molecule_from_file(self.current_imol, pdb_file)
コード例 #28
0
ファイル: info_panels.py プロジェクト: cctbx/cctbx-playground
 def set_file (self, file_name) :
   self.file_name = os.path.abspath(file_name)
   from iotbx import file_reader
   import iotbx.pdb
   self._pdb_in = file_reader.any_file(file_name, force_type="pdb",
     raise_sorry_if_errors=True,
     raise_sorry_if_not_expected_format=True)
   self._pdb_in.check_file_type("pdb")
   self._hierarchy = self._pdb_in.file_object.hierarchy
   info_list = iotbx.pdb.show_file_summary(
     pdb_in=self._pdb_in.file_object,
     hierarchy=self._hierarchy)
   self.SetTitle("Info for %s" % to_unicode(self.file_name))
   self.file_txt.SetLabel(to_unicode(self.file_name))
   if (self.info_panel is not None) :
     self.panel_sizer.Detach(self.info_panel)
     self.info_panel.Destroy()
   self.info_panel = wx.Panel(self.panel, -1)
   self.panel_sizer.Add(self.info_panel, 1, wx.ALL|wx.EXPAND)
   szr = wx.BoxSizer(wx.VERTICAL)
   self.info_panel.SetSizer(szr)
   box = wx.StaticBox(self.info_panel, -1, "File contents:")
   box_szr = wx.StaticBoxSizer(box, wx.VERTICAL)
   szr.Add(box_szr, 1, wx.EXPAND|wx.ALL, 5)
   grid = wx.FlexGridSizer(cols=2)
   box_szr.Add(grid, 1, wx.EXPAND)
   for label, value in info_list :
     txt1 = wx.StaticText(self.info_panel, -1, label + ":")
     font = txt1.GetFont()
     font.SetWeight(wx.FONTWEIGHT_BOLD)
     txt1.SetFont(font)
     grid.Add(txt1, 0, ALN_FLAGS, 5)
     str_value = to_str(value)
     alert = False
     if (str_value.endswith("***")) :
       str_value = re.sub("\s*\*\*\*", "", str_value)
       alert = True
     txt2 = wx.StaticText(self.info_panel, -1, str_value)
     font2 = txt2.GetFont()
     font2.SetFamily(wx.FONTFAMILY_MODERN)
     if (alert) :
       font2.SetWeight(wx.FONTWEIGHT_BOLD)
       txt2.SetForegroundColour((200,0,0))
       txt1.SetForegroundColour((200,0,0))
     txt2.SetFont(font2)
     grid.Add(txt2, 0, ALN_FLAGS, 5)
   if (len(self._hierarchy.models()) == 1) :
     if (len(self._hierarchy.models()[0].chains()) > 1) :
       btn = wx.Button(self.info_panel, -1, "B-factors by chain...")
       szr.Add(btn, 0, wx.ALL, 5)
       self.Bind(wx.EVT_BUTTON, self.OnShowChainBstats, btn)
   szr.Fit(self.info_panel)
   self.panel.Layout()
   self.panel_sizer.Fit(self.panel)
   self.Fit()
コード例 #29
0
 def LoadReflectionsFile(self, file_name, set_array=True, data_only=False):
     file_name = to_str(file_name)
     if (file_name != ""):
         from iotbx.reflection_file_reader import any_reflection_file
         self.viewer.isnewfile = True
         self.viewer.iarray = 0
         self.viewer.icolourcol = 0
         self.viewer.iradiicol = 0
         display.reset_settings()
         self.settings = display.settings()
         self.viewer.settings = self.settings
         self.viewer.mapcoef_fom_dict = {}
         try:
             hkl_file = any_reflection_file(file_name)
         except Exception, e:
             raise Sorry(to_str(e))
         arrays = hkl_file.as_miller_arrays(
             merge_equivalents=False,
         )  #observation_type_callback=misc_dialogs.get_shelx_file_data_type)
         #arrays = f.file_server.miller_arrays
         valid_arrays = []
         self.array_info = []
         for array in arrays:
             #if array.is_hendrickson_lattman_array() :
             #  continue
             #elif (data_only) :
             if (data_only):
                 if (not array.is_real_array()) and (
                         not array.is_complex_array()):
                     continue
             self.array_info.append(ArrayInfo(array).infostr)
             valid_arrays.append(array)
         self.valid_arrays = valid_arrays
         for i, e in enumerate(self.array_info):
             self.mprint("%d, %s" % (i, e))
         if (len(valid_arrays) == 0):
             msg = "No arrays of the supported types in this file."
             raise Sorry(msg)
         elif (len(valid_arrays) == 1):
             if (set_array):
                 self.set_miller_array(valid_arrays[0])
             return valid_arrays[0]
コード例 #30
0
 def update_model (self, pdb_file) :
   """
   Example of a user-defined function which will automatically be made
   accessible via XML-RPC.
   """
   import coot
   if (self.current_imol is None) :
     self.current_imol = read_pdb(to_str(pdb_file))
   else :
     clear_and_update_molecule_from_file(self.current_imol,
       pdb_file)
コード例 #31
0
ファイル: path.py プロジェクト: ndevenish/cctbx_project-fork
 def GetValue(self):
     val = self._path_text.GetValue().strip()
     # use unicode check to avoid bytes in Python 3
     check_type = bytes
     if sys.version_info.major == 2:
         check_type = unicode
     if (isinstance(val, check_type)) and wxtbx.is_unicode_build():
         return to_str(val)
     else:
         assert isinstance(val, str)
         return val
コード例 #32
0
 def add_label(self,label=None):
   '''
    Add a label (up to 80-character string) to write to output map.
    Default is to specify the program name and date
   '''
   if not self.labels:
     self.labels=[]
   if len(label)>80:  label=label[:80]
   self.labels.reverse()  # put at beginning
   self.labels.append(to_str(label, codec='utf8')) # make sure it is a string
   self.labels.reverse()
   self._print("Label added: %s " %(label))
コード例 #33
0
def load_refinement(pdb_file,
                    map_file,
                    work_dir=None,
                    peaks_file=None,
                    show_symmetry=True,
                    have_anom_map=None,
                    have_residual_map=None):
    import coot  # import dependency
    import os.path
    import sys
    if (work_dir is not None):
        if os.path.isdir(work_dir):
            os.chdir(work_dir)
        else:
            for k, arg in enumerate(sys.argv[1:-1]):
                if (arg == "--script"):
                    script_file = sys.argv[k + 2]
                    if os.path.isfile(script_file):
                        script_dir = os.path.dirname(script_file)
                        if (script_dir != ""):
                            os.chdir(script_dir)
    read_pdb(to_str(pdb_file))
    if (peaks_file is not None) and (os.path.isfile(peaks_file)):
        imol = read_pdb(to_str(peaks_file))
        set_mol_displayed(imol, False)
    auto_read_make_and_draw_maps(to_str(map_file))
    if (have_anom_map):
        imol = make_and_draw_map(to_str(map_file), "ANOM", "PHANOM", "", 0, 0)
        set_contour_level_in_sigma(imol, 3.0)
        if (have_residual_map):
            set_map_colour(imol, 0.0, 1.0, 1.0)
            set_map_displayed(imol, False)
        else:
            set_map_colour(imol, 1.0, 1.0, 0.0)
    if (have_residual_map):
        imol = make_and_draw_map(to_str(map_file), "ANOMDIFF", "PHANOMDIFF",
                                 "", 0, 1)
        set_contour_level_in_sigma(imol, 3.0)
        set_map_colour(imol, 1.0, 1.0, 0.0)
コード例 #34
0
 def update_files(self):
     import coot  # import dependency
     if (self.model_imol is not None):
         clear_and_update_molecule_from_file(self.model_imol,
                                             to_str(self.pdb_file))
     else:
         self.model_imol = read_pdb(to_str(self.pdb_file))
     if (len(self.map_imols) > 0):
         set_colour_map_rotation_for_map(0)
         for imol in self._map_mols:
             close_molecule(imol)
     else:
         set_colour_map_rotation_for_map(10)
     map_imol = auto_read_make_and_draw_maps(to_str(self.map_file))
     if (isinstance(map_imol, int)):
         # XXX this may be dangerous, but auto_read_make_and_draw_maps only returns
         # the last imol
         self.map_imols = [map_imol - 1, map_imol]
     else:
         self.map_imols = map_imol
     set_imol_refinement_map(self.map_imols[0])
     set_scrollable_map(self.map_imols[0])
コード例 #35
0
def load_refinement (
    pdb_file,
    map_file,
    work_dir=None,
    peaks_file=None,
    show_symmetry=True,
    have_anom_map=None,
    have_residual_map=None) :
  import coot # import dependency
  import os.path
  import sys
  if (work_dir is not None) :
    if os.path.isdir(work_dir) :
      os.chdir(work_dir)
    else :
      for k, arg in enumerate(sys.argv[1:-1]) :
        if (arg == "--script") :
          script_file = sys.argv[k+2]
          if os.path.isfile(script_file) :
            script_dir = os.path.dirname(script_file)
            if (script_dir != "") :
              os.chdir(script_dir)
  read_pdb(to_str(pdb_file))
  if (peaks_file is not None) and (os.path.isfile(peaks_file)) :
    imol = read_pdb(to_str(peaks_file))
    set_mol_displayed(imol, False)
  auto_read_make_and_draw_maps(to_str(map_file))
  if (have_anom_map) :
    imol = make_and_draw_map(to_str(map_file),"ANOM","PHANOM","",0,0)
    set_contour_level_in_sigma(imol, 3.0)
    if (have_residual_map) :
      set_map_colour(imol, 0.0, 1.0, 1.0)
      set_map_displayed(imol, False)
    else :
      set_map_colour(imol, 1.0, 1.0, 0.0)
  if (have_residual_map) :
    imol = make_and_draw_map(to_str(map_file),"ANOMDIFF","PHANOMDIFF","",0,1)
    set_contour_level_in_sigma(imol, 3.0)
    set_map_colour(imol, 1.0, 1.0, 0.0)
コード例 #36
0
 def StopWebsocket(self):
   try:
     if self.websockclient: # might not have been created if program is closed before a data set is shown
       self.websockclient['handler'].send_text(u"", opcode=0x8)
   except Exception as e:
     self.mprint( to_str(e) + "\n" + traceback.format_exc(limit=10), verbose=0)
   self.mprint("Shutting down Websocket listening thread", verbose=1)
   self.server.shutdown()
   self.parent.javascriptcleaned = True
   self.msgqueuethrd.join()
   self.mprint("Shutting down WebsocketServer", verbose=1)
   self.wst.join()
   self.isterminating = True
コード例 #37
0
ファイル: watch_file.py プロジェクト: cctbx/cctbx-playground
 def update_files (self) :
   import coot # import dependency
   if (self.model_imol is not None) :
     clear_and_update_molecule_from_file(self.model_imol,
                                         to_str(self.pdb_file))
   else :
     self.model_imol = read_pdb(to_str(self.pdb_file))
   if (len(self.map_imols) > 0) :
     set_colour_map_rotation_for_map(0)
     for imol in self._map_mols :
       close_molecule(imol)
   else :
     set_colour_map_rotation_for_map(10)
   map_imol = auto_read_make_and_draw_maps(to_str(self.map_file))
   if (isinstance(map_imol, int)) :
     # XXX this may be dangerous, but auto_read_make_and_draw_maps only returns
     # the last imol
     self.map_imols = [ map_imol - 1, map_imol ]
   else :
     self.map_imols = map_imol
   set_imol_refinement_map(self.map_imols[0])
   set_scrollable_map(self.map_imols[0])
コード例 #38
0
ファイル: cmdlineframes.py プロジェクト: RAPD/cctbx_project
  def update_settings(self, new_phil=None):
    try:
      if not new_phil:
        new_phil = self.master_phil.format(python_object = self.params)

      self.currentphil, diff_phil = self.GetNewCurrentPhilFromPython(new_phil, self.currentphil)
      diff = None
      if len(diff_phil.all_definitions()) < 1:
        self.mprint( "Nothing's changed")
        return False

      diff = diff_phil.extract().NGL_HKLviewer
      self.mprint("diff phil:\n" + diff_phil.as_str() )

      self.params = self.currentphil.extract()
      phl = self.params.NGL_HKLviewer

      if hasattr(diff, "filename"):
        self.ResetPhilandViewer(diff_phil)
        self.load_reflections_file(phl.filename)

      if hasattr(diff, "column") or hasattr(diff, "fomcolumn") \
       or hasattr(diff, "mergedata") or hasattr(diff, "columnbinthresholds"):
        #print "mergedata in updatesettings: " , self.params.NGL_HKLviewer.mergedata
        if self.set_column(phl.column, phl.fomcolumn):
          self.set_column_bin_thresholds(phl.columnbinthresholds, phl.binarray)

      if hasattr(diff, "spacegroupchoice"):
        self.set_spacegroup_choice(phl.spacegroupchoice)

      if hasattr(diff, "cameratype"):
        self.set_camera_type(phl.cameratype)

      if hasattr(diff, "viewer"):
        self.viewer.settings = phl.viewer
        self.settings = phl.viewer

      msg = self.viewer.update_settings(diff)
      self.mprint( msg)
      #import code, traceback; code.interact(local=locals(), banner="".join( traceback.format_stack(limit=10) ) )
      self.SendInfo()
      self.NewFileLoaded = False

      if (self.miller_array is None) :
        self.mprint( "No miller array has been selected")
        return False
      return True
    except Exception as e:
      self.mprint(to_str(e) + "\n" + traceback.format_exc())
      return False
コード例 #39
0
 def __init__(self, ligand_file_info):
     import gtk
     import coot  # import dependency
     title = "Select ligand(s)"
     self.ligand_file_info = ligand_file_info
     self.ligand_imols = []
     for file_name, cc, xyz in ligand_file_info:
         self.ligand_imols.append(read_pdb(to_str(file_name)))
     self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
     self.window.set_default_size(300, 200)
     self.window.set_title(title)
     scrolled_win = gtk.ScrolledWindow()
     outside_vbox = gtk.VBox(False, 2)
     inside_vbox = gtk.VBox(False, 0)
     inside_vbox.set_border_width(2)
     self.window.add(outside_vbox)
     outside_vbox.pack_start(scrolled_win, True, True,
                             0)  # expand fill padding
     scrolled_win.add_with_viewport(inside_vbox)
     scrolled_win.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
     frame = gtk.Frame(title)
     vbox = gtk.VBox(False, 0)
     inside_vbox.pack_start(frame, False, False, 2)
     self.model = gtk.ListStore(bool, gobject.TYPE_STRING,
                                gobject.TYPE_STRING)
     tv = gtk.TreeView(self.model)
     cell1 = gtk.CellRendererToggle()
     cell1.connect("toggled", self.OnToggle, self.model)
     col1 = gtk.TreeViewColumn("Keep")
     col1.pack_start(cell1, False)
     col1.add_attribute(cell1, "active", 0)
     cell2 = gtk.CellRendererText()
     col2 = gtk.TreeViewColumn("File")
     col2.pack_start(cell2, False)
     col2.add_attribute(cell2, "text", 1)
     cell3 = gtk.CellRendererText()
     col3 = gtk.TreeViewColumn("CC")
     col3.pack_start(cell3, False)
     col3.add_attribute(cell3, "text", 2)
     tv.append_column(col1)
     tv.append_column(col2)
     tv.append_column(col3)
     frame.add(tv)
     for file_name, cc, xyz in ligand_file_info:
         self.model.append([False, os.path.basename(file_name), cc])
     continue_btn = gtk.Button("Close and continue")
     continue_btn.connect("clicked", self.OnContinue)
     outside_vbox.pack_end(continue_btn, False, False, 0)
     self.window.show_all()
コード例 #40
0
    def onWriteTableOne(self, e):
        ''' Write Table 1 to a file '''

        save_dlg = wx.FileDialog(self,
                                 message="Save Table 1",
                                 defaultDir=os.curdir,
                                 defaultFile="table_1.txt",
                                 wildcard="*.txt",
                                 style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
        if save_dlg.ShowModal() == wx.ID_OK:
            with open(save_dlg.GetPath(), 'a') as tb1_file:
                for i in range(len(self.tb1_data)):
                    line = u'{:<25} {:<40}\n'.format(self.tb1_labels[i],
                                                     self.tb1_data[i][0])
                    tb1_file.write(to_str(line))
コード例 #41
0
ファイル: chimerax.py プロジェクト: dials/cctbx
    def _connect(self):
        # find client.py in ISOLDE
        client_path = None
        with tempfile.NamedTemporaryFile(mode='w', suffix='.py',
                                         delete=False) as python_script:
            python_script.write("""\
from chimerax import isolde
print(isolde.__file__)
""")
        command = [
            self.command, '--nogui', '--exit', '--script', python_script.name
        ]
        python_process = subprocess.Popen(args=command,
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE,
                                          shell=False)
        stdout, stderr = python_process.communicate()
        python_process.wait()
        if python_process.returncode != 0:
            raise Sorry('The ISOLDE installation location could not be found.')
        else:
            if os.path.isfile(python_script.name):
                try:
                    os.remove(python_script.name)
                except IOError:
                    pass
            stdout = to_str(stdout).split('\n')
            line = None
            for line in stdout:
                if 'isolde' in line:
                    break
            client_path = os.path.abspath(
                os.path.join(line, '..', 'remote_control', 'rest_server',
                             'client.py'))
        if client_path is not None and os.path.isfile(client_path):
            # import from file
            if sys.version_info.major > 2:
                import importlib.util
                spec = importlib.util.spec_from_file_location(
                    'client', client_path)
                client = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(client)
            else:
                import imp
                client = imp.load_source('client', client_path)
            self._client = client.IsoldeRESTClient('localhost', self.port)
            self._client.connect()
            self._connected = True
コード例 #42
0
  def onWriteTableOne(self, e):
    ''' Write Table 1 to a file '''

    save_dlg = wx.FileDialog(self,
                             message="Save Table 1",
                             defaultDir=os.curdir,
                             defaultFile="table_1.txt",
                             wildcard="*.txt",
                             style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT
                             )
    if save_dlg.ShowModal() == wx.ID_OK:
      with open(save_dlg.GetPath(), 'a') as tb1_file:
       for i in range(len(self.tb1_data)):
          line = u'{:<25} {:<40}\n'.format(self.tb1_labels[i],
                                           self.tb1_data[i][0])
          tb1_file.write(to_str(line))
コード例 #43
0
 def __init__ (self, ligand_file_info) :
   import gtk
   import coot # import dependency
   title = "Select ligand(s)"
   self.ligand_file_info = ligand_file_info
   self.ligand_imols = []
   for file_name, cc, xyz in ligand_file_info :
     self.ligand_imols.append(read_pdb(to_str(file_name)))
   self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
   self.window.set_default_size(300, 200)
   self.window.set_title(title)
   scrolled_win = gtk.ScrolledWindow()
   outside_vbox = gtk.VBox(False, 2)
   inside_vbox = gtk.VBox(False, 0)
   inside_vbox.set_border_width(2)
   self.window.add(outside_vbox)
   outside_vbox.pack_start(scrolled_win, True, True, 0) # expand fill padding
   scrolled_win.add_with_viewport(inside_vbox)
   scrolled_win.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
   frame = gtk.Frame(title)
   vbox = gtk.VBox(False, 0)
   inside_vbox.pack_start(frame, False, False, 2)
   self.model = gtk.ListStore(bool, gobject.TYPE_STRING, gobject.TYPE_STRING)
   tv = gtk.TreeView(self.model)
   cell1 = gtk.CellRendererToggle()
   cell1.connect("toggled", self.OnToggle, self.model)
   col1 = gtk.TreeViewColumn("Keep")
   col1.pack_start(cell1, False)
   col1.add_attribute(cell1, "active", 0)
   cell2 = gtk.CellRendererText()
   col2 = gtk.TreeViewColumn("File")
   col2.pack_start(cell2, False)
   col2.add_attribute(cell2, "text", 1)
   cell3 = gtk.CellRendererText()
   col3 = gtk.TreeViewColumn("CC")
   col3.pack_start(cell3, False)
   col3.add_attribute(cell3, "text", 2)
   tv.append_column(col1)
   tv.append_column(col2)
   tv.append_column(col3)
   frame.add(tv)
   for file_name, cc, xyz in ligand_file_info :
     self.model.append([False, os.path.basename(file_name), cc])
   continue_btn = gtk.Button("Close and continue")
   continue_btn.connect("clicked", self.OnContinue)
   outside_vbox.pack_end(continue_btn, False, False, 0)
   self.window.show_all()
コード例 #44
0
 def find_missing_atoms(self, out=None):
     '''
 Function for finding missing protein atoms
 Derived from run_find_missing function in phenix/validation/__init__.py
 '''
     if out is None:
         out = sys.stdout
     self.missing_atoms = []
     # make_header("Finding missing atoms", out=out)
     try:
         missing_list = rotamer_eval.eval_sidechain_completeness(
             pdb_hierarchy=self.pdb_hierarchy,
             ignore_hydrogens=True,
             report_whole_res=True,
             return_ca_pos=True)
     except Exception, e:
         print >> out, to_str(e)
コード例 #45
0
ファイル: file_reader.py プロジェクト: cctbx/cctbx-playground
 def _try_as_txt (self) :
   file_as_string = open(self.file_name).read()
   file_as_ascii = to_str(file_as_string)
   self._file_type = "txt"
   self._file_object = file_as_string
コード例 #46
0
ファイル: strctrl.py プロジェクト: cctbx/cctbx-playground
 def FormatValue (self, value) :
   if wxtbx.is_unicode_build() :
     return to_str(value)
   else :
     return value
コード例 #47
0
  def flush_requests (self, show_timings=False) :
    t1 = time.time()
    result = None
    while len(self._pending) > 0 :
      (methodname, params) = self._pending.pop(0)

      # remove any unicode types in params
      if (isinstance(params, unicode)):
        params = to_str(params)
      elif (isinstance(params, list) or isinstance(params, tuple)):
        new_params = list(params)
        for i in xrange(len(params)):
          if (isinstance(params[i], unicode)):
            new_params[i] = to_str(params[i])
          else:
            new_params[i] = params[i]
        if (isinstance(params, tuple)):
          new_params = tuple(new_params)
        params = new_params

      # call a method on the remote server
      try :
        request = xmlrpclib.dumps(params, methodname,
                                  encoding=self.__encoding,
                                  allow_none=self.__allow_none)

        response = self.__transport.request(
            self.__host,
            self.__handler,
            request,
            verbose=self.__verbose
        )

        if len(response) == 1 :
          result = response[0]
      except KeyboardInterrupt :
        raise
      except Exception, e :
        msg = to_str(e)
        if (hasattr(e, "errno")) :
          if (e.errno in [32,54,61,104,111,10054,10061]) :
            self._pending.insert(0, (methodname, params))
            t = time.strftime("%H:%M:%S", time.localtime())
            self._errors.append("%s -- %s" % (t, msg))
            break
        if ("timed out" in msg) :
          print "XMLRPC timeout, ignoring request"
          self._timeouts += 1
        elif msg.startswith("<ProtocolError ") :
          self._pending = []
          break
        elif ("exceptions.SystemExit" in msg) :
          self._pending = []
          break
        else :
          msg = "XMLRPC error: %s\nMethod: %s\nParams: %s\n" % \
            (msg, to_str(methodname), ", ".join([ to_str(p) for p in params ]))
          if (not self.raise_errors) :
            print >> sys.stderr, msg
          else :
            raise RuntimeError(msg)
コード例 #48
0
ファイル: frames.py プロジェクト: cctbx/cctbx-playground
 def OnLoadFile (self, evt) :
   file_name = wx.FileSelector("Reflections file",
     wildcard="Reflection files (*.mtz, *.sca, *.hkl)|*.mtz;*.sca;*.hkl",
     default_path=os.getcwd(),
     flags=wx.OPEN)
   self.load_reflections_file(to_str(file_name))
コード例 #49
0
def start_coot_and_wait (
    pdb_file,
    map_file,
    ligand_files,
    ligand_ccs,
    cif_files=(),
    work_dir=None,
    coot_cmd="coot",
    log=None) :
  from iotbx import file_reader
  from libtbx.str_utils import make_header
  from libtbx import easy_run
  import cootbx
  assert (len(ligand_files) > 0) and (len(ligand_files) == len(ligand_ccs))
  if (log is None) : log = sys.stdout
  cwd = os.getcwd()
  if (work_dir is None) : work_dir = cwd
  if (not os.path.isdir(work_dir)) :
    os.makedirs(work_dir)
  os.chdir(work_dir)
  base_script = __file__.replace(".pyc", ".py")
  ligand_xyzs = []
  for pdb_file in ligand_files :
    pdb_file = to_str(pdb_file)
    pdb_in = file_reader.any_file(pdb_file, force_type="pdb")
    pdb_in.assert_file_type("pdb")
    coords = pdb_in.file_object.atoms().extract_xyz()
    ligand_xyzs.append(coords.mean())
  ligand_info = zip(ligand_files, ligand_ccs, ligand_xyzs)
  f = open("edit_in_coot.py", "w")
  f.write(open(base_script).read())
  f.write("\n")
  f.write("import coot\n")
  cootbx.write_disable_nomenclature_errors(f)
  f.write("read_pdb(\"%s\")\n" % to_str(pdb_file))
  f.write("auto_read_make_and_draw_maps(\"%s\")\n" % to_str(map_file))
  for cif_file in cif_files :
    f.write("read_cif_dictionary(\"%s\")\n" % to_str(cif_file))
  f.write("m = manager(%s)\n" % str(ligand_info))
  f.close()
  make_header("Ligand selection in Coot", log)
  rc = easy_run.call("\"%s\" --no-state-script --script edit_in_coot.py &" %
    coot_cmd)
  if (rc != 0) :
    raise RuntimeError("Launching Coot failed with status %d" % rc)
  print >> log, "  Waiting for user input at %s" % str(time.asctime())
  out_file = ".COOT_LIGANDS"
  output_files = output_ccs = None
  while (True) :
    if (os.path.isfile(out_file)) :
      print >> log, "  Coot editing complete at %s" % str(time.asctime())
      ligand_indices = [ int(i) for i in open(out_file).read().split() ]
      output_files = []
      for i in ligand_indices :
        ligand_file = os.path.join(work_dir, "coot_ligand_out_%d.pdb" % (i+1))
        output_files.append(ligand_file)
      output_ccs = [ ligand_ccs[i] for i in ligand_indices ]
      break
    else :
      time.sleep(t_wait / 1000.)
  assert (output_files is not None)
  os.chdir(cwd)
  return output_files, output_ccs