def _display_selected(workspace): paths_names = self.write_selection(workspace) self._paths_selected = len(paths_names) self.set_display(len(paths_names) != 0) self._list.items = [] for path_name in paths_names: self._workpaths[path_name[0]] = True Logs.debug('filename:', path_name[1]) clone = self._prefab_entry.clone() clone.find_node( 'Label').get_content().text_value = path_name[1] icon_ln = clone.find_node('Selected Icon') icon_ln.add_new_image(self._icon_path) icon_ln.selected = True icon_ln.path = path_name[0] clone.get_content().register_pressed_callback( partial(self.toggle_selected, icon_ln)) self._list.items.append(clone) if self._is_component: self._ln_cancel.enabled = False self._plugin.refresh_menu() else: self._ln_cancel.enabled = True self._plugin.open_menu(self._menu)
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
def load_request(self, button=None): if not self.request: self.plugin.send_notification(nanome.util.enums.NotificationTypes.message, "Please select a request") return self.save_fields_to_vars() self.set_load_enabled(False) results = {} for i, step in enumerate(self.request['steps']): resource = self.settings.get_resource(step['resource']) import_type = resource['import type'] metadata = step['metadata_source'] data = resource['data'].replace("\'", "\"") # override data if necessary data_override_field_name = f"{self.request['name']} {step['name']} data" if step['override_data']: data = self.fields[data_override_field_name] contexts = [self.fields, results, self.settings.variables] response = self.get_response(resource, contexts, data) var_uid, var_value = self.settings.get_output_variable(resource, 0) if not response: self.plugin.send_notification(nanome.util.enums.NotificationTypes.error, f"Step {i} failed. Aborting {self.request['name']}") self.set_load_enabled(True) return results[f'step{i+1}'] = json.dumps(var_value) or response.text Logs.debug(f'setting step{i+1} to {var_value} ({self.settings.variables[var_uid][0]})') if import_type: import_name = self.contextualize(variable=resource['import name'], contexts=contexts) self.import_to_nanome(import_name, import_type, var_value or response.text, metadata) self.set_load_enabled(True)
def decontextualize(self, json, contexts=[], left_wrapper="{{", right_wrapper="}}", k_or_v=False): def replace(json, old, new, k_or_v=False): newd = {} for k, v in json.items(): if k_or_v: if v == old: newd[k] = new else: newd[k] = v if isinstance(v, dict): v = replace(v, old, new, k_or_v) if not k_or_v: if k == old: newd[new] = v else: newd[k] = v return newd if not contexts: contexts = [self.variable_values] for context in contexts: for var_value, var_names in context.items(): Logs.debug(f'replacing {var_value} with {var_names[0]}') json = replace(json, var_value, left_wrapper + var_names[0] + right_wrapper, k_or_v) return json
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)
def on_run(self): self.set_to_refresh() self.open_matryx_menu() self.defer(self.populate_all_tournaments, 60) # self.print_node(self._menu_matryx.root) Logs.debug('requesting directory...') self.request_directory('/', self.on_directory_received)
def start(self): self.make_tracking_atoms() self.make_menu() import time time.sleep(5) Logs.debug("requesting complexes") self.request_complex_list(self.connect_complexes)
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
def __update_secondary_structure(self, complex): molecules = complex._molecules if len(molecules) != len(self.__current_complex_result): Logs.debug("[DSSP] Complex", complex._name, ": Molecule count", len(molecules), "doesn't match DSSP count", len(self.__current_complex_result)) return for i in range(len(self.__current_complex_result)): secondary = self.__current_complex_result[i] molecule = molecules[i] residues = dict() for chain in molecule._chains: residues[chain._name] = dict() for residue in chain._residues: residues[chain._name][residue._serial] = residue for dssp_info in secondary: try: chain = residues[dssp_info[0]] residue = chain[dssp_info[1]] structure_type = dssp_info[2] if structure_type == " ": residue._secondary_structure = _Residue.SecondaryStructure.Coil elif structure_type == "E": residue._secondary_structure = _Residue.SecondaryStructure.Sheet elif structure_type == "H": residue._secondary_structure = _Residue.SecondaryStructure.Helix except: Logs.debug("[DSSP] Key not found:", dssp_info[0], dssp_info[1], traceback.format_exc())
def update_score(self, value=None): Logs.debug("update score called: ", value) if value is None: self.rmsd_score_label.text_value = "--" else: self.rmsd_score_label.text_value = str("%.3g" % value) self._plugin.update_content(self.rmsd_score_label)
def set_scores(self, molecule): """Clean and Parse score information for provided molecule.""" molecule.min_atom_score = float('inf') molecule.max_atom_score = float('-inf') num_rgx = r'(-?[\d.]+(?:e[+-]\d+)?)' pattern = re.compile( '<{},{},{}> {} {} {} {} {}'.format(*([num_rgx] * 8)), re.U) for associated in molecule.associateds: # make the labels pretty :) associated['Minimized Affinity'] = associated.pop( '> <minimizedAffinity>') associated['Atomic Interaction Terms'] = associated.pop( '> <atomic_interaction_terms>') pose_score = associated['Minimized Affinity'] for residue in molecule.residues: residue.label_text = pose_score + " kcal/mol" # TODO: Re-enable this when core-bug with frame labels is fixed. # https://nanome.slack.com/archives/CBDV1975K/p1641410333253500 residue.labeled = False interaction_terms = associated['Atomic Interaction Terms'] interaction_values = re.findall(pattern, interaction_terms) for i, atom in enumerate(molecule.atoms): if i < len(interaction_values) - 1: Logs.debug("interaction values for atom " + str(i) + ": " + str(interaction_values[i])) atom.score = float(interaction_values[i][5]) molecule.min_atom_score = min(atom.score, molecule.min_atom_score) molecule.max_atom_score = max(atom.score, molecule.max_atom_score)
def get_exception(self, default_error, pattern=".*?([\w ]*Error:[\w ]*)"): exc = traceback.format_exc() Logs.debug(exc) exc_lines = re.findall(pattern, exc, re.MULTILINE) if not len(exc_lines) or len(exc_lines[0]) < 15: return default_error else: return exc_lines[0]
def start_simulation(self): Logs.debug("Start Simulation") self.__start = timer() self.running = True self.__stream = None self.__menu.change_state(True) self.request_complexes(self._selected_complexes, self.on_complexes_received)
def on_complexes_received(self, complexes): Logs.debug("Requested complexes") for complex in complexes: if (complex is None): Logs.debug("None received") else: complex.locked = True self.label_all(complex) self.update_structures_deep([complex])
def upload_files(self, paths): files = [] for path in paths: files.append(('files', open(path, 'rb'))) response = requests.post(self._url + '/upload/files', files=files) ipfs_hash = response.json()['data']['hash'] Logs.debug('ipfs hash', ipfs_hash) return ipfs_hash
def run_test_group(test, options = TestOptions()): Logs.debug("runnning test group", test.__name__) counter = TestCounter() test.run(counter) Logs.debug("tests passed: ", str(counter.passed)+"/"+str(counter.total)) if (counter.passed < counter.total): return False else: return True
def connect_complexes(self, complexes): Logs.debug("received some complexes", len(complexes)) for complex in complexes: if complex.name == "head": self.head_complex = complex elif complex.name == "left": self.left_complex = complex elif complex.name == "right": self.right_complex = complex self.request_controller_transforms(self.received)
def check_menu_stats(self, pos, rot, scale): self.outstanding = False if not self.menu_position.equals(pos) or not self.menu_rotation.equals( rot) or not self.menu_scale.equals(scale): Logs.error("Menu not where it should be!") Logs.error(self.menu_position, pos) Logs.error(self.menu_rotation, rot) Logs.error(self.menu_scale, scale) else: Logs.debug("passed menu check")
def on_files_received(self, file_list): # For each file we read, display if error, and file content for file in file_list: Logs.debug('Error?', str(nanome.util.FileErrorCode(file.error_code)), 'Content:', file.data.decode('utf-8')) if nanome.util.FileErrorCode( file.error_code) != nanome.util.FileErrorCode.file_unreachable: self._menu_accounts._wallet_json = file.data.decode('utf-8')
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
def open_variable_setup(self, button): self.variable_confirm.root.clear_children() self.variable_confirm.var_path = button.json_path self.variable_confirm.var_value = button.name self.variable_confirm.height = 1 self.variable_confirm.width = 1 ln_name = self.variable_confirm.root.create_child_node() ln_name.sizing_type = ln_name.SizingTypes.ratio ln_name.sizing_value = 0.2 ln_name.create_child_node().add_new_label( 'Name' ).text_horizontal_align = nanome.util.enums.HorizAlignOptions.Middle ln_var_name = ln_name.create_child_node() ln_var_name.forward_dist = 0.02 inp_var_name = ln_var_name.add_new_text_input() inp_var_name.placeholder_text = 'variable name' inp_var_name.max_length = 0 inp_var_name.max_length = 24 inp_var_name.register_changed_callback(self.set_output_variable) ln_value = self.variable_confirm.root.create_child_node() ln_value.sizing_type = ln_name.SizingTypes.ratio ln_value.sizing_value = 0.7 ln_label = ln_value.create_child_node() ln_label.sizing_type = ln_name.SizingTypes.ratio ln_label.sizing_value = 0.1 ln_label.forward_dist = 0.02 ln_label.add_new_label( 'Value' ).text_horizontal_align = nanome.util.enums.HorizAlignOptions.Middle ln_var_value = ln_value.create_child_node() ln_var_value.sizing_type = ln_var_value.SizingTypes.ratio ln_var_value.sizing_value = 0.5 ln_var_value.add_new_label(text=button.text.value.idle) ln_create_var = self.variable_confirm.root.create_child_node() ln_create_var.sizing_type = ln_create_var.SizingTypes.ratio ln_create_var.sizing_value = 0.1 btn_create = ln_create_var.add_new_button(text="Set Resource Variable") btn_create.register_pressed_callback(self.create_output_var) self.variable_confirm.enabled = True self.plugin.update_menu(self.variable_confirm) Logs.debug( f'Are you sure you want to create a variable for {button.name}?') Logs.debug(f'variable path: {button.json_path}')
def print_node(self, layout_node, depth=0): prefix = '| ' * (depth - 1) + ('|-- ' if depth > 0 else '') Logs.debug(prefix + layout_node.name) children = layout_node.get_children() if len(children) > 0: for child in children: self.print_node(child, depth + 1) if depth == 0: Logs.debug('---------------------------------')
def stop_simulation(self): Logs.debug("Stop Simulation") self.running = False # self.__menu.remove_progress_bar() self.__menu.change_state(False) if self.__stream != None: self.__stream.destroy() try: os.remove('tmp.pdb') except: pass
def start(self): Logs.debug("Start RMSD Plugin") self.args = RMSD.Args() self._menu = RMSDMenu(self) self._menu.build_menu() self.selected_before = [] self._mobile = [] self._target = None # passed from rmsd_menu.py to compare the index # and autoselect entry menu complex self.compare_index = None
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()
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)
def _updated_complexes_received(self, complex_list): self.__complex_list = complex_list indices = [] for complex in complex_list: for atom in complex.atoms: indices.append(atom.index) end = timer() Logs.debug("Second Request:", end - self.__start) self._start = timer() self.create_writing_stream(indices, nanome.util.enums.StreamType.position, self.on_stream_creation)
def update(self): has_data = None try: has_data = self.__pipe.poll() if has_data: data = self.__pipe.recv() except BrokenPipeError: Logs.debug("Pipe has been closed, exiting process") return False if has_data: self.__received_data(data) return True
def count_structures(complex): molecule_counter = sum(1 for i in complex.molecules) chain_counter = sum(1 for i in complex.chains) residue_counter = sum(1 for i in complex.residues) bond_counter = sum(1 for i in complex.bonds) atom_counter = sum(1 for i in complex.atoms) return molecule_counter, chain_counter, residue_counter, bond_counter, atom_counter Logs.debug("molecule_counter:", molecule_counter) Logs.debug("chain_counter:", chain_counter) Logs.debug("residue_counter:", residue_counter) Logs.debug("bond_counter:", bond_counter) Logs.debug("atom_counter:", atom_counter)
def send_tx(self, fn): try: account = self._plugin._account signed_tx = account.signTransaction(self.create_tx(fn)) receipt = self._web3.eth.sendRawTransaction( signed_tx.rawTransaction) tx_hash = receipt.hex() Logs.debug('%s tx %s' % (fn.fn_name, tx_hash)) return tx_hash except ValueError as err: Logs.debug('%s tx revert, revert!' % fn.fn_name) raise err