Example #1
0
    async def _run_docking(self):
        receptor = self._selected_receptor
        ligands = self._selected_ligands
        site = None
        if self._selected_site:
            site = self._selected_site

        if not receptor or not ligands:
            if self._selected_site is None:
                Logs.warning(
                    "Trying to run docking without having one receptor, one site and at least one ligand selected"
                )
                return

        self.loading_bar.percentage = 0
        self.enable_loading_bar()
        self.make_plugin_usable(False)
        try:
            await self._plugin.run_docking(self._selected_receptor, ligands,
                                           site, self.get_params())
        except Exception as e:
            message = f'{type(e).__name__}: {next(iter(e.args), "Error Occurred. Please Check Logs.")}'
            Logs.error(message)
            self._plugin.send_notification(NotificationTypes.error, message)

        self.make_plugin_usable(True)
        self.enable_loading_bar(False)
Example #2
0
    def _receive(self):
        payload = None
        try:
            has_data = self._process_conn.poll()
            if has_data:
                payload = self._process_conn.recv()
        except BrokenPipeError:
            Logs.debug("Pipe has been closed, exiting process")
            self._plugin._on_stop()
            return False

        if payload:
            if payload == stop_bytes:
                Logs.debug("Pipe has been closed, exiting process")
                self._plugin._on_stop()
                return False

            received_object, command_hash, request_id = self._serializer.deserialize_command(
                payload, self.__version_table)
            if received_object == None and command_hash == None and request_id == None:
                return True  # Happens if deserialize_command returns None, an error message is already displayed in that case

            try:
                callback = self._serializer._command_callbacks[command_hash]
            except:
                Logs.error("Received a command without callback associated:",
                           command_hash)
                return True
            callback(self, received_object, request_id)
        return True
Example #3
0
    def __start_process(self):
        entry = self.__pending.popleft()
        entry.send(_ProcessManager.process_data_type_starting, [])
        request = entry.request
        args = [request.executable_path] + request.args
        has_text = entry.output_text

        def enqueue_output(out, err, queue_out, queue_err, text):
            if text:
                sentinel = ''
            else:
                sentinel = b''

            for line in iter(err.readline, sentinel):
                queue_err.put(line)
            err.close()
            for line in iter(out.readline, sentinel):
                queue_out.put(line)
            out.close()

        try:
            entry.process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1, cwd=request.cwd_path, universal_newlines=has_text, close_fds=POSIX)
            Logs.debug("Process started:", request.executable_path, "for session", entry.session._session_id)
        except:
            Logs.error("Couldn't execute process", request.executable_path, "Please check if executable is present and has permissions:\n", traceback.format_exc())
            entry.send(_ProcessManager.process_data_type_done, [-1])
            return
        entry.stdout_queue = Queue()
        entry.stderr_queue = Queue()
        thread = Thread(target=enqueue_output, args=(entry.process.stdout, entry.process.stderr, entry.stdout_queue, entry.stderr_queue, has_text))
        thread.daemon = True
        thread.start()
        self.__running.append(entry)
Example #4
0
def init_hashes():
    hashes = dict()
    i = -1
    for command in _Commands:
        i += 1
        hash = hash_command(command.name)
        if hash in hashes:
            Logs.error("Command hash collision detected:", command.name, "and",
                       hashes[hash])
            continue
        hashes[hash] = command.name
        _Hashes.CommandHashes[i] = hash

    hashes.clear()
    i = -1

    for command in _Messages:
        i += 1
        hash = hash_command(command.name)
        if hash in hashes:
            Logs.error("Message hash collision detected:", command.name, "and",
                       hashes[hash])
            continue
        hashes[hash] = command.name
        _Hashes.MessageHashes[i] = hash
Example #5
0
def write_json(helper, content):
    if (content is None):
        return None
    elif (isinstance(content, _Button)):
        type_name = "Button"
        _button_json.write_json(helper, content)
    elif (isinstance(content, _Mesh)):
        type_name = "Mesh"
        _mesh_json.write_json(helper, content)
    elif (isinstance(content, _Slider)):
        type_name = "Slider"
        _slider_json.write_json(helper, content)
    elif (isinstance(content, _TextInput)):
        type_name = "TextInput"
        _text_input_json.write_json(helper, content)
    elif (isinstance(content, _Label)):
        type_name = "Label"
        _label_json.write_json(helper, content)
    elif (isinstance(content, _UIList)):
        type_name = "List"
        _ui_list_json.write_json(helper, content)
    elif (isinstance(content, _Image)):
        type_name = "Image"
        _image_json.write_json(helper, content)
    elif (isinstance(content, _LoadingBar)):
        type_name = "LoadingBar"
        _loading_bar_json.write_json(helper, content)
    else:
        Logs.error("unknown content type: " + str(type(content)))
        return None
    helper.write("type_name", type_name)
Example #6
0
 def load_molecule(self, code):
     url_to_load = url.replace("{{NAME}}", code)
     response = requests.get(url_to_load)
     file = tempfile.NamedTemporaryFile(delete=False)
     self._name = code
     try:
         file.write(response.text.encode("utf-8"))
         file.close()
         if type == "PDB":
             complex = nanome.structure.Complex.io.from_pdb(path=file.name)
             self.add_bonds([complex], self.bonds_ready)
         elif type == "SDF":
             complex = nanome.structure.Complex.io.from_sdf(path=file.name)
             self.bonds_ready([complex])
         elif type == "MMCIF":
             complex = nanome.structure.Complex.io.from_mmcif(
                 path=file.name)
             self.add_bonds([complex], self.bonds_ready)
         else:
             Logs.error("Unknown file type")
     except:  # Making sure temp file gets deleted in case of problem
         self._loading = False
         Logs.error("Error while loading molecule:\n",
                    traceback.format_exc())
     os.remove(file.name)
Example #7
0
        def on_stream_creation(stream, error):
            if error != StreamCreationError.NoError:
                Logs.error("Error while creating stream")
                return

            self.__stream = stream
            self.__data_queue = deque()
            cwd_path = self.__nanobabel_dir
            exe = 'nanobabel.exe' if IS_WIN else 'nanobabel'
            exe_path = os.path.join(cwd_path, exe)
            args = [
                'minimize', '-h', '-l', '20', '-n',
                str(steps), '-ff', ff, '-i', input_file.name, '-cx',
                constraints_file.name, '-o', output_file.name
            ]
            if IS_WIN:
                args += ['-dd', 'data']
            if steepest:
                args.append('-sd')
            Logs.debug(args)

            p = Process(exe_path, args, True)
            p.on_error = self.__on_process_error
            p.on_output = self.__on_process_output
            p.on_done = self.__on_process_done
            p.start()

            self.__process = p
            self.__process_running = True
            self._is_running = True
Example #8
0
 def deserialize(self, version, context):
     ui_type = _UIBaseSerializer.ContentType(context.read_uint())
     try:
         serializer = _UIBaseSerializer.registered_serializers[ui_type]
     except:
         Logs.error("Trying to deserialize unknown UI type:", ui_type)
         return
     return context.read_using_serializer(serializer)
Example #9
0
def parse_value(str, parser):
    if parser == None:
        return str
    try:
        return parser(str)
    except:
        Logs.error("Wrong value:", str, "\nExpected:", parser)
        sys.exit(1)
Example #10
0
def main():
    if not NANOBABEL:
        Logs.error('Error: nanobabel not found, please set NANOBABEL env var')
        sys.exit(1)

    plugin = nanome.Plugin("Minimization", "Run minimization on selected structures. See Advanced Parameters for forcefield, number of steps, and steepest descent", "Minimization", True)
    plugin.set_plugin_class(Minimization)
    plugin.run()
Example #11
0
def _receive_create_stream_result(network, result, request_id):
    if result[0] != StreamCreationError.NoError:
        network._call(request_id, None, result[0])

        if result[0] == StreamCreationError.UnsupportedStream:
            Logs.error("Tried to create an unsupported type of stream")
        return
    stream = Stream(network, result[1], result[2], result[3])
    network._call(request_id, stream, StreamCreationError.NoError)
Example #12
0
def _receive_interrupt_stream(network, result, request_id):
    try:
        stream = Stream._streams[result[1]]
    except:
        Logs.error(
            "Got an error for an unknown stream. Probably tried to update an unknown stream:",
            result[1])
        return

    stream._interrupt(result[0])
Example #13
0
 def to_json(self, path):
     helper = _JsonHelper()
     _menu_json.write_json(helper, self.base_object)
     menu_string = json.dumps(helper.get_dict())
     try:
         with open(path, "w") as f:
             f.write(menu_string)
     except:
         Logs.error("Could not write to file: " + path)
         raise
Example #14
0
def run_test(test, counter):
    try:
        Logs.debug("\trunning test", test.__name__)
        counter.total += 1
        test()
    except Exception as err:
        Logs.error("\ttest failed.")
        print(traceback.format_exc())
    else:
        counter.passed += 1
Example #15
0
 def __bonding_done(self, result_code):
     if result_code == -1:
         Logs.error("Couldn't execute openbabel to generate bonds. Is it installed?")
         self.__callback(self.__complexes)
         return
     with open(self.__output.name) as f:
         lines = f.readlines()
     content = _sdf.parse_lines(lines)
     result = _sdf.structure(content)
     self.__match_and_bond(result)
     self.__next()
Example #16
0
 def __dssp_done(self, result_code):
     if result_code != 0:
         Logs.error("DSSP failed, code:", result_code)
         self.__callback(self.__complexes)
         return
     with open(self.__output.name) as f:
         lines = f.readlines()
     secondary = self.__parse_dssp(lines)
     Logs.debug(secondary)
     self.__current_complex_result.append(secondary)
     self.__next()
Example #17
0
def _parse_lines(lines):
    lines = [line.rstrip() for line in lines]
    # Content structure
    lines = _CIF_Lines(lines)
    try:
        parsed_file = ParseLines(lines)
    except Exception:
        Logs.error("\tParse failed. Error on line:", lines.get_line_number())
        Logs.error(traceback.format_exc())
    content = raw_to_formatted(parsed_file)
    return content
Example #18
0
def get_data_category(line):
    match = re.match(category_regex, line)
    if (match == None):
        Logs.error(line)
        return
    category = match.group(1)
    key = match.group(2)
    value = match.group(3)
    if category == None:
        category = "Misc"
    return category, key, value
Example #19
0
    def on_directory_received(self, result):
        # If API couldn't access directory, display error
        if result.error_code != nanome.util.DirectoryErrorCode.no_error:
            Logs.error('Directory request error:', str(result.error_code))
            return

        # For each entry in directory, display name and if directory
        for entry in result.entry_array:
            Logs.debug(entry.name, 'Is Directory?', entry.is_directory)
            if entry.name == 'temp':
                self.request_files(['/temp/matryx_wallet.json'],
                                   self.on_files_received)  # Read matryx.txt
Example #20
0
 def connect(self, host, port):
     try:
         self._connection.connect((host, port))
         self._connection.setblocking(False)
         Logs.message("Connected to server", host, port)
     except (ssl.SSLError, socket.error) as e:
         self._socket = None
         self._context = None
         self._connection = None
         Logs.error("Cannot connect to plugin server at", host, port, e)
         return False
     return True
    def on_stream_creation(self, stream, error):
        self.__waiting_for_complexes = False
        if error == StreamCreationError.AtomNotFound:
            Logs.error("Tried to create a stream with bad atoms")
            self.stop_simulation()
            return

        self.__stream = stream
        self.__process.set_stream(stream)
        end = timer()
        Logs.debug("Stream creation:", end - self.__start)
        self.__run_simulation(self.__complex_list)
Example #22
0
 def _received_request(self, data, session):
     type = data[0]
     if type == _ProcessManager._CommandType.start:
         request = data[1]
         entry = _ProcessEntry(request, session)
         self.__pending.append(entry)
         session.send_process_data(
             [_ProcessManager._DataType.queued, request])
     elif type == _ProcessManager._CommandType.stop:
         self.__stop_process(data[1])
     else:
         Logs.error("Received unknown process command type")
 def workspace_received(workspace):
     try:
         self.save_workspace(workspace, file)
     except:
         self.send_notification(
             NotificationTypes.error,
             "Failed to save workspace, check plugin")
         Logs.error("Failed to save workspace", traceback.format_exc())
     self.btn_save.unusable = False
     self.update_content(self.btn_save)
     file.close()
     self.refresh_menu()
     self.__timer = timer()
Example #24
0
 def serialize(self, version, value, context):
     if value == None:
         return
     try:
         ui_type = _UIBaseSerializer.registered_classes[type(
             value).__name__]
         serializer = _UIBaseSerializer.registered_serializers[ui_type]
     except:
         Logs.error("Trying to serialize unknown UI type:",
                    type(value).__name__)
         return
     context.write_uint(ui_type)
     context.write_using_serializer(serializer, value)
Example #25
0
 async def run(self, src_complex: Complex):
     with tempfile.TemporaryDirectory() as work_dir:
         pdb_path = path.join(work_dir, "mol.pdb")
         pqr_path = path.join(work_dir, "mol.pqr")
         map_path = path.join(work_dir, "map")
         src_complex.io.to_pdb(pdb_path)
         try:
             pqr_struct = await self.run_pdb2pqr(pdb_path, pqr_path)
             volume = await self.run_apbs(work_dir, pqr_struct, pqr_path,
                                          map_path)
             return [pqr_parser.structure_to_complex(pqr_struct), volume]
         except Exception as e:
             Logs.error(e)
             return None
Example #26
0
 def from_json(self, path):
     try:
         with open(path, "r") as f:
             menu_string = f.read()
             menu_json = json.loads(menu_string)
     except:
         Logs.error("Could not read json file: " + path)
         raise
     try:
         json_helper = _JsonHelper(menu_json)
         return _menu_json.parse_json(json_helper)
     except:
         Logs.error("Json does not correctly represent a menu.")
         raise
        def set_complexes(complex_list):
            self._respond_to_update = True
            self._complexes = complex_list
            self._ligand_names = []
            self._ligand_atom_counts = {}
            self._ligand_frames = {}
            atom_counts = [0 for _ in range(len(complex_list))]
            for complex_i in range(0, len(complex_list)):
                complex = complex_list[complex_i]
                complex.locked = True
                complex = complex_list[complex_i].convert_to_frames()
                complex.index = complex_list[complex_i].index
                complex_list[complex_i] = complex
                molecule_list = list(complex.molecules)
                atom_counts[complex_i] = len(
                    list(molecule_list[complex.current_frame].atoms))

                for atom in complex_list[complex_i].atoms:
                    atom._old_position = atom.position

                if complex_i > 0:
                    if (atom_counts[complex_i] > atom_counts[0]):
                        err_msg = "Error with receptor/ligand combination. Ligand cannot be larger than receptor."
                        Logs.error(err_msg)
                        self.send_notification(NotificationTypes.error,
                                               err_msg)
                        self.stop_scoring()
                        return
                    self._ligand_frames[complex.index] = complex.current_frame
                    self._ligand_atom_counts[
                        complex.index] = atom_counts[complex_i]
                    self._ligand_names.append(
                        complex_list[complex_i].full_name)
                    for residue in complex_list[complex_i].residues:
                        residue.labeled = False
                    for atom in complex_list[complex_i].atoms:
                        atom.labeled = self.settings._labels

                    complex_updated_callback = functools.partial(
                        self.complex_updated, complex_list[1:])
                    complex_list[complex_i].register_complex_updated_callback(
                        complex_updated_callback)

            self.unfreeze_button("Stop scoring")
            self.hide_scores(True)
            self._respond_to_update = False
            self.update_structures_deep(
                complex_list[0:],
                functools.partial(self.request_complexes, index_list[1:],
                                  self.setup_spheres))
Example #28
0
    def to_json(self, path):
        helper = _JsonHelper()
        helper.write("is_menu", False)
        helper.write("title", "node")
        child = helper.make_instance()
        _layout_node_json.write_json(child, self.base_object)
        helper.write("effective_root", child)
        node_string = json.dumps(helper.get_dict())

        try:
            with open(path, "w") as f:
                f.write(node_string)
        except:
            Logs.error("Could not write to file: " + path)
            raise
Example #29
0
 def receive(self):
     try:
         data = self._connection.recv(4096)
     except ssl.SSLWantReadError:
         time.sleep(0.01)
     except ssl.SSLEOFError:
         Logs.error("Connection closed by plugin server")
         return False
     except KeyboardInterrupt:
         raise
     except:
         Logs.error(traceback.format_exc())
         return False
     else:
         self._received_data(data)
     return True
Example #30
0
 def from_json(self, path):
     try:
         with open(path) as f:
             node_string = f.read()
             node_json = json.loads(node_string)
     except:
         Logs.error("Could not read json file: " + path)
         raise
     try:
         json_helper = _JsonHelper(node_json)
         assert (json_helper.read("is_menu", False) == False)
         return _layout_node_json.parse_json(
             json_helper.read_object("effective_root"))
     except:
         Logs.error("Json does not correctly represent a layout node.")
         raise