keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_main/_files_managment.py
.py
2,381
54
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Files input and output. """ import os from pymod_lib.pymod_seq import seq_io from pymod_lib import pymod_vars class PyMod_files_managment: def build_sequence_file(self, elements, sequences_filename, new_directory=None, file_format="fasta", remove_indels=True, unique_indices_headers=False, use_structural_information=False, same_length=True, first_element=None, add_extension=True): """ Wrapper for the 'build_sequence_file' in the 'seq_io' module. """ alignment_extension = pymod_vars.alignment_extensions_dictionary[file_format] if new_directory == None: target_dirpath = self.alignments_dirpath else: target_dirpath = new_directory if add_extension: sequences_filepath = os.path.join(target_dirpath, "%s.%s" % (sequences_filename, alignment_extension)) else: sequences_filepath = os.path.join(target_dirpath, sequences_filename) seq_io.build_sequence_file(elements=elements, sequences_filepath=sequences_filepath, file_format=file_format, remove_indels=remove_indels, unique_indices_headers=unique_indices_headers, use_structural_information=use_structural_information, same_length=same_length, first_element=first_element) def save_alignment_fasta_file(self, file_name, aligned_elements, first_element=None, custom_directory=None, unique_indices_headers=False): """ Saves in the Alignments directory a .fasta alignment file containing the sequences of the "aligned_elements". """ self.build_sequence_file(aligned_elements, file_name, file_format="fasta", remove_indels=False, first_element=first_element, new_directory=custom_directory, unique_indices_headers=unique_indices_headers)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_main/_elements_loading.py
.py
31,180
656
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module implementing a series of methods which allow to load PyMod elements in PyMod. """ import os import re from Bio import SeqIO from pymol import cmd from pymod_lib.pymod_gui.shared_gui_components_qt import askyesno_qt, askopenfile_qt from pymod_lib.pymod_gui.specific_gui_components_qt import (Search_string_window_qt, Add_feature_window_qt, Edit_sequence_window_qt) from pymod_lib import pymod_structure from pymod_lib import pymod_vars from pymod_lib.pymod_protocols import structural_databases_protocols from pymod_lib.pymod_seq.seq_manipulation import check_correct_sequence from pymod_lib.pymod_element_feature import Element_feature from pymod_lib.pymod_exceptions import PyModInvalidFile class PyMod_elements_loading: ############################################################################################### # FILES MANAGMENT. # ############################################################################################### ################################################################# # Check correct files formats. # ################################################################# def is_sequence_file(self, file_path, file_format, show_error=True): """ Try to open a sequence file using Biopython. Returns 'True' if the file is a valid file of the format specified in the 'file_format' argument. """ valid_file = False file_handler = None try: file_handler = open(file_path,"r") r = list(SeqIO.parse(file_handler, file_format)) if len(r) > 0: valid_file = True except: valid_file = False if file_handler != None: file_handler.close() return valid_file def is_valid_structure_file(self,file_name, format="pdb", show_error=True): valid_pdb = False file_handler = open(file_name, "r") for line in file_handler.readlines(): if line.startswith("ATOM") or line.startswith("HETATM"): try: x,y,z = float(line[30:38]), float(line[38:46]), float(line[46:54]) valid_pdb = True break except: pass file_handler.close() if not valid_pdb and show_error: title = "FileType Error" message = "The selected File is not a valid PDB." self.main_window.show_error_message(title,message) return valid_pdb ################################################################# # Load sequence files. # ################################################################# def open_sequence_file(self, file_full_path, file_format="fasta"): """ Method for loading in PyMod new sequences parsed from sequence files. It will build new PyMod elements, but it will not display its widgets in the main window. """ if not os.path.isfile(file_full_path): raise IOError("File does not exist: %s." % file_full_path) if not self.is_sequence_file(file_full_path, file_format): raise PyModInvalidFile("Can not open an invalid '%s' file: %s." % (file_format, file_full_path)) # Parses a sequence file through Biopython. This will automatically crop headers that have # " " (space) characters. elements_to_return = [] for record in SeqIO.parse(file_full_path, file_format): # Then builds a PyMod_element object and add it to the 'pymod_elements_list'. c = self.build_pymod_element_from_seqrecord(record) e = self.add_element_to_pymod(c) elements_to_return.append(e) return elements_to_return def build_cluster_from_alignment_file(self, alignment_file, extension="fasta"): """ Creates a cluster with all the sequences contained in an alignment file. """ # Gets the sequences using Biopython. aligned_elements = [] records = SeqIO.parse(alignment_file, extension) for record in records: new_child_element = self.build_pymod_element_from_seqrecord(record) self.add_element_to_pymod(new_child_element) aligned_elements.append(new_child_element) new_cluster = self.add_new_cluster_to_pymod(cluster_type="alignment", child_elements=aligned_elements, algorithm="imported") return new_cluster ################################################################# # Opening PDB files. # ################################################################# def open_structure_file(self, pdb_file_full_path, file_format="pdb"): """ Opens a PDB file (specified in 'pdb_file_full_path'), reads its content, imports in PyMod the sequences of the polypeptide chains and loads in PyMOL their 3D structures. """ if not self.is_valid_structure_file(pdb_file_full_path, file_format): raise PyModInvalidFile("Can not open an invalid '%s' file." % file_format) p = pymod_structure.Parsed_pdb_file(self, pdb_file_full_path, output_directory=self.structures_dirpath) elements_to_return = [] for element in p.get_pymod_elements(): e = self.add_element_to_pymod(element) elements_to_return.append(e) # Renames the full PDB file if needed. original_pdb_filename = p.structure_file_name if original_pdb_filename in self.original_pdb_files_set: counter = 1 while original_pdb_filename in self.original_pdb_files_set: original_pdb_filename = "%s_%s" % (counter, original_pdb_filename) counter += 1 for e in elements_to_return: e.rename_file_name_root(original_pdb_filename) self.original_pdb_files_set.add(original_pdb_filename) return elements_to_return def color_struct(self): color_to_return = pymod_vars.pymod_regular_colors_list[self.color_index % len(pymod_vars.pymod_regular_colors_list)] self.color_index += 1 return color_to_return ################################################################# # Open files dialogs from PyMod. # ################################################################# def choose_alignment_file(self): """ Lets users choose an alignment file. """ # Creates a PyQt widget that lets the user select multiple files. alignment_file_path = askopenfile_qt("Open an alignment file", name_filter="*fasta *aln *clu *sto *sth", parent=self.get_qt_parent()) if not alignment_file_path: return (None, None) # Finds the right extension. extension = os.path.splitext(alignment_file_path)[1].replace(".","") if extension == "fasta": pass elif extension in ("aln", "clu"): extension = "clustal" elif extension in ("sto", "sth"): extension = "stockholm" # Unknown format. else: title = "Format Error" message = "Unknown alignment file format: %s" % (extension) self.main_window.show_error_message(title, message) return (None, None) return alignment_file_path, extension def choose_structure_file(self): """ Lets users choose a strcture file. """ # Creates a PyQt widget that lets the user select multiple files. open_filepath = askopenfile_qt("Open an alignment file", name_filter="*pdb *ent", parent=self.get_qt_parent()) if open_filepath == "": return (None, None) # Finds the right extension. extension = os.path.splitext(os.path.basename(open_filepath))[1].replace(".","") return open_filepath, extension ############################################################################################### # EDIT SEQUENCE AND STRUCTURES. # ############################################################################################### def show_edit_sequence_window(self, pymod_element): """ Edit a sequence. """ self.edit_sequence_window = Edit_sequence_window_qt(self.main_window, pymod_element=pymod_element, title="Edit Sequence", upper_frame_title="Edit your Sequence", submit_command=self.edit_sequence_window_state) self.edit_sequence_window.show() # self.edit_sequence_window.resize(700, self.edit_sequence_window.sizeHint().height()) def edit_sequence_window_state(self): """ Accept the new sequence. """ edited_sequence = self.edit_sequence_window.get_sequence() # When editing elements with a structure loaded in PyMOL, only indels can be added/removed. if self.edit_sequence_window.pymod_element.has_structure(): if self.edit_sequence_window.pymod_element.my_sequence.replace("-", "") != edited_sequence.replace("-", ""): message = ("The amino acid sequence of an element with a 3D structure" " loaded in PyMOL can not be edited. Only indels can be" " added or removed.") self.main_window.show_error_message("Sequence Error", message) return None if not len(edited_sequence): self.main_window.show_error_message("Sequence Error", "Please submit a non empty string.") return None if not check_correct_sequence(edited_sequence): self.main_window.show_error_message("Sequence Error", "Please provide a sequence with only standard amino acid characters.") return None self.edit_sequence_window.pymod_element.set_sequence(edited_sequence, permissive=True) self.main_window.gridder(update_clusters=True, update_elements=True) self.edit_sequence_window.destroy() def duplicate_sequence(self, element_to_duplicate): """ Make a copy of a certain element. """ if element_to_duplicate.has_structure(): p = pymod_structure.Parsed_pdb_file(self, element_to_duplicate.get_structure_file(basename_only=False), output_directory=self.structures_dirpath, new_file_name=pymod_vars.copied_chain_name % self.new_objects_index) self.new_objects_index += 1 for element in p.get_pymod_elements(): self.add_element_to_pymod(element, color=element_to_duplicate.my_color) # Add this to use the old color shceme of PyMod: color=self.color_struct() else: #duplicated_element = self.build_pymod_element(pmel.PyMod_sequence_element, element_to_duplicate.my_sequence, element_to_duplicate.my_header_root) duplicated_element = self.build_pymod_element_from_args(element_to_duplicate.my_header_root, element_to_duplicate.my_sequence) self.add_element_to_pymod(duplicated_element) return duplicated_element ################################################################# # Add features. # ################################################################# def show_add_feature_window(self, pymod_element, selected_residue): """ Edit a feature to a residue (or series of residues). """ self.add_feature_window = Add_feature_window_qt(self.main_window, pymod_element=pymod_element, selected_residue=selected_residue, title="Add a Feature to %s" % pymod_element.compact_header, upper_frame_title="Add a Feature to your Sequence", submit_command=self.add_feature_window_state) self.add_feature_window.show() def add_feature_window_state(self): """ Accept the new feature. """ selected_element = self.add_feature_window.pymod_element #----------------------------------- # Get the parameters from the GUI. - #----------------------------------- # Gets the residue range. residue_range_str = self.add_feature_window.get_residue_range() selection_warning_title = "Selection Warning" examples_string = "'34' for a single residue, '12-20' for a residue range" selection_warning_message = "Please provide a valid string to select one ore more residues (use the format: %s)." % examples_string # Checks for an empty string. if not residue_range_str: self.main_window.show_warning_message(selection_warning_title, selection_warning_message) return None # Checks for a single residue. sre_match = re.search("^\d+$", residue_range_str) if sre_match: try: residue_range = (int(residue_range_str), int(residue_range_str)) except ValueError: self.main_window.show_warning_message(selection_warning_title, selection_warning_message) return None # Checks for a residue range. else: sre_match = re.search("^(\d+\-\d+)$", residue_range_str) if not sre_match: self.main_window.show_warning_message(selection_warning_title, selection_warning_message) return None try: min_res, max_res = residue_range_str.split("-") residue_range = (int(min_res), int(max_res)) except (ValueError, IndexError): self.main_window.show_warning_message(selection_warning_title, selection_warning_message) return None if residue_range[1] < residue_range[0]: self.main_window.show_warning_message(selection_warning_title, "Invalid residue range. The index of the second residue in the range (%s) can not be smaller than the first one (%s)." % (residue_range[1], residue_range[0])) return None # Convert the 'db_index' values obtained from the GUI into 'seq_index' values. try: feature_start = selected_element.get_residue_by_db_index(residue_range[0]).seq_index feature_end = selected_element.get_residue_by_db_index(residue_range[1]).seq_index # The 'db_index' values do not correspond to any residue. except KeyError as e: self.main_window.show_warning_message(selection_warning_title, 'The selected sequence does not have a residue with the following id: %s.' % e) return None # Gets the feature name. feature_name = self.add_feature_window.get_feature_name() sre_match = re.search("[^ a-zA-Z0-9_-]", feature_name) if not feature_name or sre_match: self.main_window.show_warning_message(selection_warning_title, 'Please provide a valid "Feature Name" string (only alphanumeric characters and the "-", "_" and " " characters are allowed).') return None if len(feature_name) > 15: self.main_window.show_warning_message(selection_warning_title, 'Please provide a "Feature Name" string shorter than 15 characters.') return None # Gets the feature color. selected_rgb, selected_hex = self.add_feature_window.get_selected_colors() feature_color = self.add_new_color(selected_rgb, selected_hex) #------------------------------------------------ # Actually adds the new feature to the element. - #------------------------------------------------ # Adds the domain to the sequence. new_feature = Element_feature(id=None, name=feature_name, start=feature_start, end=feature_end, description=feature_name, feature_type='sequence', color=feature_color) selected_element.add_feature(new_feature) self.main_window.color_element_by_custom_scheme(selected_element, selected_feature=new_feature) if self.add_feature_window.get_select_in_pymol(): selection_name = "%s_%s_%s" % (feature_name.replace(" ", "_"), selected_element.unique_index, selected_element.features_count) cmd.select(selection_name, "object %s and resi %s-%s" % (selected_element.get_pymol_selector(), residue_range[0], residue_range[1])) selected_element.features_selectors_list.append(selection_name) self.add_feature_window.destroy() def delete_features_from_context_menu(self, pymod_element): for selection in pymod_element.features_selectors_list: try: cmd.delete(selection) except: pass pymod_element.clear_features() pymod_element.revert_original_color() self.main_window.color_element(pymod_element) ################################################################# # Search subsequences. # ################################################################# def show_search_string_window(self, pymod_element): """ Search for a sub-sequence in a protein sequence. """ self.search_string_window = Search_string_window_qt(self.main_window, pymod_elements=[pymod_element], title="Search in %s" % pymod_element.compact_header, upper_frame_title="Search a string in your sequence", submit_command=self.search_string_window_state, submit_button_text="Search") self.search_string_window.show() def search_string_window_state(self, event=None): selected_element = self.search_string_window.pymod_element #----------------------------------- # Get the parameters from the GUI. - #----------------------------------- # Get the string to search for in the selected sequence. search_string = self.search_string_window.get_search_string() _search_string = "" # " '" + search_string + "'" selection_warning_title = "Search Warning" # examples_string = "'34' for a single residue, '12-20' for a residue range" # selection_warning_message = "Please provide a valid string to select one ore more residues (use the format: %s)." % examples_string # Checks for an empty string. if not search_string: self.main_window.color_element(selected_element) self.search_string_window.show_results(self.search_string_window.default_message, state="empty") return None # Decides whether to use regex to search for a string. use_regex = self.search_string_window.get_regex_use() # Checks the search string. if not use_regex: # Search for invalid characters. search_sre = re.search("[^A-Za-z]", search_string) if search_sre: self.main_window.show_warning_message(selection_warning_title, "Please provide a string containing only standard amino acid characters (example: 'ATGV').") return None else: # Test the regular expression. try: search_sre = re.search(search_string, "test_string") except re.error: self.main_window.show_warning_message(selection_warning_title, "Please provide a string containing a valid regular expression.") return None # Gets the highlight color. highlight_color = self.search_string_window.get_highlight_color() #------------------------------------------------------------ # Searches for the string in the selected protein sequence. - #------------------------------------------------------------ selection_results_title = "Search Results" full_sequence = str(selected_element.my_sequence.replace("-", "")) # Actually executes the regular expression to look for sequences. finditer_results = list(re.finditer(search_string, full_sequence, flags=re.IGNORECASE)) if not finditer_results: self.main_window.color_element(selected_element) results_message = "Pattern" + _search_string + " not found." self.search_string_window.show_results(results_message, state="not_found") return None # Builds a list of residue indices encompassing the matched strings. selected_residues = [] for re_match in finditer_results: selected_residues.extend(list(range(re_match.start(), re_match.end()))) selected_residues = set(selected_residues) # Stores the original colors and assign the temporary highlight color to the matched # substrings. original_color_scheme = selected_element.color_by for res in selected_element.get_polymer_residues(): res.store_current_colors() # Stores the original colors. if res.seq_index in selected_residues: res.custom_color = highlight_color # Sets the highlight color. else: res.custom_color = res.get_default_color() # Use the original color. # Colors only the sequence and highlights the matching residues. self.main_window.color_element_by_custom_scheme(selected_element, use_features=False, color_structure=False) # Restores the original colors. The next time the sequence is changed (for example # when inserting/removing gaps), the highlighted residues will be colored back with # their original color. for res in selected_element.get_polymer_residues(): res.revert_original_colors() selected_element.color_by = original_color_scheme # Show a message with the summary of the results. def _get_results_string(n_results): if n_results == 1: return str(n_results) + " time." else: return str(n_results) + " times." results_message = ("Pattern" + _search_string + " found " + _get_results_string(len(finditer_results))) self.search_string_window.show_results(results_message, state="found") # Select in PyMOL. if self.search_string_window.get_select_in_pymol(): residues_to_select_list = [] for re_match in finditer_results: try: pymol_start_res = selected_element.get_residue_by_index(re_match.start(), only_polymer=True).db_index pymol_end_res = selected_element.get_residue_by_index(re_match.end(), only_polymer=True).db_index residues_to_select_list.extend(list(range(pymol_start_res, pymol_end_res))) except IndexError: pass if residues_to_select_list: selection_name = "pymod_search_string" selector_str = "object %s" % selected_element.get_pymol_selector() selector_str += " and resi " + self.main_window._join_residues_list(residues_to_select_list) cmd.select(selection_name, selector_str) ################################################################# # Clusters. # ################################################################# def update_cluster_sequences(self, cluster_element): """ Updates the sequences of a cluster when some sequences are removed or added from the cluster. """ children = cluster_element.get_children() if len(children) > 1: cluster_element.adjust_aligned_children_length() cluster_element.update_stars() else: if len(children) == 1: children[0].extract_to_upper_level() cluster_element.delete() def extract_selection_to_new_cluster(self): selected_sequences = self.get_selected_sequences() original_cluster_index = self.get_pymod_element_index_in_container(selected_sequences[0].mother) + 1 new_cluster = self.add_new_cluster_to_pymod(cluster_type="generic", child_elements=selected_sequences, algorithm="extracted") self.change_pymod_element_list_index(new_cluster, original_cluster_index) self.main_window.gridder(clear_selection=True, update_clusters=True, update_menus=True) ################################################################# # Transfer alignment files. # ################################################################# def transfer_alignment(self, alignment_element): """ Changes the sequences of the elements contained in a PyMod cluster according to the information present in an externally supplied file (chosen by users through a file dialog) containing the same sequences aligned in a different way. Right now it supports transfer only for sequences having the exactly same sequences in PyMod and in the external alignment. """ # Let users choose the external alignment file. openfilename, extension = self.choose_alignment_file() if None in (openfilename, extension): return False # Sequences in the aligment currently loaded into PyMod. aligned_elements = alignment_element.get_children()[:] # Sequences in the alignment files. external_records = list(SeqIO.parse(openfilename, extension)) if len(external_records) < len(aligned_elements): title = "Transfer error" message = "'%s' has more sequences (%s) than the alignment in '%s' (%s) and the 'Transfer Alignment' function can't be used in this situation." % (alignment_element.my_header, len(aligned_elements), openfilename, len(external_records)) self.main_window.show_error_message(title,message) return False correspondance_list = [] # First try to find sequences that are identical (same sequence and same lenght) in both # alignments. for element in aligned_elements[:]: identity_matches = [] for record in external_records: if str(element.my_sequence).replace("-","") == str(record.seq).replace("-",""): match_dict = {"target-seq":element, "external-seq": record, "identity": True} identity_matches.append(match_dict) if len(identity_matches) > 0: correspondance_list.append(identity_matches[0]) aligned_elements.remove(identity_matches[0]["target-seq"]) external_records.remove(identity_matches[0]["external-seq"]) # Then try to find similar sequences among the two alignments. Right now this is not # implemented. # ... if not len(aligned_elements) == 0: title = "Transfer error" message = "Not every sequence in the target alignment has a corresponding sequence in the external alignment." self.main_window.show_error_message(title, message) return False # Finally transfer the sequences. for match in correspondance_list[:]: if match["identity"]: match["target-seq"].set_sequence(str(match["external-seq"].seq)) correspondance_list.remove(match) self.main_window.gridder(update_clusters=True) def delete_cluster_dialog(self, cluster_element): title = "Delete Cluster?" message = "Are you sure you want to delete %s?" % (cluster_element.my_header) remove_cluster_choice = askyesno_qt(message=message, title=title, parent=self.get_qt_parent()) if not remove_cluster_choice: return None title = "Delete Sequences?" message = "Would you like to delete all the sequences contained in the %s cluster? By selecting 'No', you will only extract them from the cluster." % (cluster_element.my_header) remove_children_choice = askyesno_qt(message=message, title=title, parent=self.get_qt_parent()) # Delete both the cluster and its children. if remove_children_choice: cluster_element.delete() # Delete only the cluster element and extract the child sequences. else: children = cluster_element.get_children() for c in reversed(children[:]): c.extract_to_upper_level() cluster_element.delete() self.main_window.gridder(update_menus=True) ################################################################# # Import PDB files. # ################################################################# def fetch_pdb_files(self, mode, target_selection): fp = structural_databases_protocols.Fetch_structure_file(self) fp.initialize_from_gui(mode, target_selection) fp.launch_from_gui() # def associate_structure_from_popup_menu(self, target_element): # """ # Launched when users press the 'Associate 3D Structure' from the leeft popup menu. # """ # a = structural_databases_protocols.Associate_structure(self, target_element) # a.launch_from_gui()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_main/_elements_interactions.py
.py
18,021
410
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Methods to manipulate PyMod elements within the plugin. """ import os from pymol import cmd from pymod_lib import pymod_vars from pymod_lib.pymod_seq import seq_headers from pymod_lib.pymod_element import PyMod_sequence_element, PyMod_cluster_element class PyMod_elements_interactions: ########################################################################### # Build PyMod elements. # ########################################################################### def build_pymod_element(self, base_class, *args, **configs): """ Dynamically builds the class of the PyMod element. """ # return type(base_class.__name__, (PyMod_element_GUI, base_class), {})(*args, **configs) return base_class(*args, **configs) def build_pymod_element_from_args(self, sequence_name, sequence): return self.build_pymod_element(PyMod_sequence_element, sequence, sequence_name) def build_pymod_element_from_seqrecord(self, seqrecord): """ Gets Biopython a 'SeqRecord' class object and returns a 'PyMod_element' object corresponding to the it. """ new_element = self.build_pymod_element(PyMod_sequence_element, str(seqrecord.seq), seqrecord.id, description=seqrecord.description) return new_element def build_pymod_element_from_hsp(self, hsp_seq, hsp_header): """ Gets a hsp dictionary containing a Biopython 'HSP' class object and returns a 'PyMod_element' object corresponding to the subject in the HSP. """ cs = self.build_pymod_element(PyMod_sequence_element, hsp_seq, hsp_header, description=hsp_header) return cs def add_element_to_pymod(self, element, adjust_header=True, color=None, use_pymod_old_color_scheme=True): """ Used to add elements to the pymod_elements_list. Once an element is added to children of the 'root_element' by this method, it will be displayed in the PyMod main window. This method will initialize the element Tkinter widgets, but it will not display them in the main window. """ # Adds the element to the children of PyMod root element. self.root_element.add_child(element) # Sets its unique index. element.unique_index = self.unique_index self.unique_index += 1 # Adjust its header. if adjust_header and not element.is_cluster(): # Cluster elements do not need their headers to be adjusted. self.adjust_headers(element) # Defines the color. if color: element.my_color = color else: # Use the old color scheme of PyMod. if use_pymod_old_color_scheme and element.has_structure(): element.my_color = self.color_struct() # Adds widgets that will be gridded. element.initialize(self) # Load its structure in PyMOL. if element.has_structure(): self.load_element_in_pymol(element) return element def replace_element(self, old_element, new_element, keep_old_header=False): """ Replaces an old element with a new element, which will be displayed in PyMod main window with the same position of the old element. """ # Gets the old container element and the old index of the target sequence. old_element_container = old_element.mother old_element_index = self.get_pymod_element_index_in_container(old_element) # Actually replaces the old element with the new one. if keep_old_header: pass old_element.delete() if not new_element in self.get_pymod_elements_list(): self.add_element_to_pymod(new_element) # Put the new element in the same cluster (with the same position) of the old one. old_element_container.add_child(new_element) self.change_pymod_element_list_index(new_element, old_element_index) def delete_pdb_file_in_pymol(self, element): # If the sequence has a PDB file loaded inside PyMOL, then delete it. try: cmd.delete(element.get_pymol_selector()) except: pass def add_new_cluster_to_pymod(self, cluster_type="generic", query=None, cluster_name=None, child_elements=[], algorithm=None, update_stars=True): if not cluster_type in ("alignment", "blast-cluster", "profile-cluster", "generic"): raise KeyError("Invalid cluster type.") #----------------------------------------------------------------------------------- # Increase the global count of clusters of the type provided in the 'cluster_type' - # argument. - #----------------------------------------------------------------------------------- if cluster_type == "alignment": self.alignment_count += 1 elif cluster_type in ("blast-cluster", "profile-cluster"): self.blast_cluster_counter += 1 elif cluster_type == "generic": self.new_clusters_counter += 1 #-------------------------------- # Sets the name of the cluster. - #-------------------------------- if cluster_name == None: if cluster_type == "alignment": if algorithm in pymod_vars.algs_full_names_dict: algorithm_full_name = pymod_vars.algs_full_names_dict[algorithm] else: algorithm_full_name = "Unknown" cluster_name = self.set_alignment_element_name(algorithm_full_name, self.alignment_count) elif cluster_type == "blast-cluster": cluster_name = "%s cluster %s (query: %s)" % (algorithm, self.blast_cluster_counter, query.compact_header) elif cluster_type == "profile-cluster": cluster_name = "%s cluster %s" % (algorithm, self.blast_cluster_counter) elif cluster_type == "generic": cluster_name = "New cluster %s" % (self.new_clusters_counter) #---------------------- # Sets the algorithm. - #---------------------- if cluster_type == "blast-cluster": algorithm = "blast-pseudo-alignment" elif cluster_type == "generic": algorithm = "none" elif algorithm == None: algorithm = "?" #---------------------------------------------------------------------- # Creates a cluster element and add the new cluster element to PyMod. - #---------------------------------------------------------------------- cluster_element = self.build_pymod_element(PyMod_cluster_element, sequence="...", header=cluster_name, description=None, color="white", algorithm=algorithm, cluster_type=cluster_type, cluster_id=self.alignment_count) self.add_element_to_pymod(cluster_element) # Add the children, if some were supplied in the argument. if child_elements != []: cluster_element.add_children(child_elements) # Computes the stars of the new alignment element. if update_stars: cluster_element.update_stars() # Sets the leader of the cluster. if cluster_type == "blast-cluster" and query != None: query.set_as_query() return cluster_element def set_alignment_element_name(self, alignment_description, alignment_id="?"): """ Builds the name of a new alignment element. This name will be displayed on PyMod main window. """ alignment_name = "Alignment %s (%s)" % (alignment_id, alignment_description) return alignment_name def updates_blast_search_element_name(self, old_cluster_name, alignment_program, alignment_id="?"): new_name = old_cluster_name # old_cluster_name.rpartition("with")[0] + "with %s)" % (alignment_program) return new_name ########################################################################### # Get and check selections. # ########################################################################### def get_pymod_elements_list(self): return self.root_element.get_descendants() def get_selected_elements(self): """ Returns a list with all the selected elements. """ return [e for e in self.root_element.get_descendants() if e.selected] def get_all_sequences(self): """ Returns a list of all the sequences currently loaded in PyMod. """ return [e for e in self.root_element.get_descendants() if not e.is_cluster()] def get_selected_sequences(self): """ Returns a list of all the sequences selected by the user. """ return [e for e in self.root_element.get_descendants() if e.selected and not e.is_cluster()] def get_cluster_elements(self, cluster_type="all"): """ Returns only those elements in pymod_elements_list with cluster_type = "alignment" or "blast-search". """ cluster_elements = [] for element in self.root_element.get_descendants(): if element.is_cluster(): if cluster_type == "all": cluster_elements.append(element) # elif cluster_type == "alignment" and element.element_type == "alignment": # cluster_elements.append(element) # elif cluster_type == "blast-search" and element.element_type == "blast-search": # cluster_elements.append(element) return cluster_elements def get_selected_clusters(self): return [e for e in self.root_element.get_descendants() if e.selected and e.is_cluster()] def check_only_one_selected_child_per_cluster(self, cluster_element): """ Returns True if the cluster element has only one selected child. This is used in "check_alignment_joining_selection()" and other parts of the PyMod class (while checking the selection for homology modeling). """ if len([child for child in cluster_element.get_children() if child.selected]) == 1: return True else: return False def check_all_elements_in_selection(self, selection, method_name): # Calling methods using 'getattr()' is slower than directly calling them. if False in [getattr(e,method_name)() for e in selection]: return False else: return True def build_sequence_selection(self, selection): """ If the 'selection' argument was not specified, it returns a list with the currently selected sequences. """ if selection == None: selection = self.get_selected_sequences() return selection def all_sequences_are_children(self, selection=None): """ Returns True if all the elements selected by the user are children. A list of PyMod elements is not specified in the 'selection' argument, the target selection will be the list of sequences currently selected in the GUI. """ selection = self.build_sequence_selection(selection) for e in selection: if not e.is_child(): return False return True def all_sequences_have_structure(self, selection=None): """ Returns 'True' if all the elements in the selection have structure loaded into PyMOL. """ selection = self.build_sequence_selection(selection) return self.check_all_elements_in_selection(selection, "has_structure") def all_sequences_have_fetchable_pdbs(self, selection=None): """ Returns 'True' if all the elements in the selection can be used to download a PDB file. """ selection = self.build_sequence_selection(selection) return self.check_all_elements_in_selection(selection, "pdb_is_fetchable") ########################################################################### # Changes elements positions in PyMod list of elements. # ########################################################################### def change_element_list_index(self, element, container_list, new_index): old_index = container_list.index(element) container_list.insert(new_index, container_list.pop(old_index)) def change_pymod_element_list_index(self, pymod_element, new_index): self.change_element_list_index(pymod_element, pymod_element.mother.list_of_children, new_index) def get_pymod_element_index_in_container(self, pymod_element): mother = pymod_element.mother return mother.list_of_children.index(pymod_element) def get_pymod_element_index_in_root(self, pymod_element): if not pymod_element.is_child(): return self.get_pymod_element_index_in_container(pymod_element) else: return self.get_pymod_element_index_in_root(pymod_element.mother) ########################################################################### # Headers. # ########################################################################### def adjust_headers(self, pymod_element): """ This methods renames PyMod elements. Checks if there are other elements in the 'pymod_elements_list' that have the same name. If there are, then add to the sequence's name a string to diversifity it as a copy. """ # First sets the 'my_header_root' attribute. self.set_header_root(pymod_element) # The sets the 'compact_header' attribute and gets a prefix to enumerate copies of an # element. self.set_compact_headers(pymod_element) # Finally sets the 'my_header' attribute. self.set_header(pymod_element) # For elements with structures, also set the name of their structures to be loaded in PyMOL. if pymod_element.has_structure(): self.set_structure_header(pymod_element) def set_header_root(self, pymod_element): pymod_element.my_header_root = seq_headers.get_header_string(pymod_element.original_header) def set_compact_headers(self, pymod_element): # Get the "compact header root" (something like "1UBI_chain_A") of an element. pymod_element.compact_header_root = seq_headers.get_compact_header_string(pymod_element.my_header_root) # Check if there are already some elements with the same "compact header root". if pymod_element.compact_header_root not in self.compact_header_root_dict: # Initializes an item in the 'compact_header_root_dict' dictionary. self.compact_header_root_dict[pymod_element.compact_header_root] = 0 # The "compact header" will be the equal to the "compact header root". names_tuple = ("", pymod_element.compact_header_root) else: # Increases the count in the 'compact_header_root_dict' dictionary. self.compact_header_root_dict[pymod_element.compact_header_root] += 1 # Composes the "prefix" of the "compact header" (something like "1_"). prefix = "%s_" % self.compact_header_root_dict[pymod_element.compact_header_root] # Composes the new "compact header" (something like "1_1UBI_chain_A"). names_tuple = (prefix, prefix + pymod_element.compact_header_root) # Checks if there are some elements which have already the same "compact header". c = 1 while names_tuple[1] in self.compact_header_set: # Increases the number in the prefix until the "compact header" is unique. prefix = "%s_" % c names_tuple = (prefix, prefix + pymod_element.compact_header_root) c += 1 # Updates the dictionary. self.compact_header_root_dict[names_tuple[1]] = 0 # Actually assignes the "prefix" and the "compact header". pymod_element.compact_header_prefix = names_tuple[0] pymod_element.compact_header = names_tuple[1] # Updates the 'compact_header_set'. self.compact_header_set.add(pymod_element.compact_header) def set_header(self, pymod_element, header=None): pymod_element.my_header = pymod_element.compact_header_prefix + pymod_element.my_header_root # pymod_element.compact_header_prefix+pymod_element.my_header_root def set_structure_header(self, pymod_element, full_structure_name=None, chain_file_name=None): """ Renames the structure files of the PyMod element, since when they were first built, they were assigned temporary names. """ # Renames the chain file. renamed_chain_str_file = os.path.join(self.structures_dirpath, "%s%s.pdb" % (pymod_element.compact_header_prefix, pymod_element.my_header_root)) if not os.path.isfile(renamed_chain_str_file): os.rename(pymod_element.get_structure_file(basename_only=False), renamed_chain_str_file) pymod_element.rename_chain_structure_files(chain_structure_file=renamed_chain_str_file)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_main/_pymol_interactions.py
.py
5,827
126
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Interactions of PyMod with PyMOL. """ import os from pymol import cmd from pymod_lib.pymod_gui.specific_gui_components_qt import Import_from_pymol_window_qt from pymod_lib.pymod_vars import sphere_hetres_names class PyMod_pymol_interactions: ############################################################################################### # Basic PyMOL interactions. # ############################################################################################### def load_element_in_pymol(self, element, as_hedgehog=True): """ Loads the PDB structure of the chain into PyMol. """ file_to_load = element.get_structure_file(basename_only=False) pymol_object_name = element.get_pymol_selector() cmd.load(file_to_load, pymol_object_name) cmd.color(element.my_color, pymol_object_name) cmd.hide("everything", pymol_object_name) cmd.show("cartoon", pymol_object_name) # Show the new chain as a cartoon. if as_hedgehog: cmd.show("sticks", "(%s and name cb) or (%s and name ca)" % (pymol_object_name, pymol_object_name)) cmd.util.cnc(pymol_object_name) # Colors by atom. cmd.zoom(pymol_object_name) cmd.center(pymol_object_name) def center_chain_in_pymol(self, pymod_element): cmd.center(pymod_element.get_pymol_selector()) def hide_chain_in_pymol(self, pymod_element): cmd.disable(pymod_element.get_pymol_selector()) def show_chain_in_pymol(self, pymod_element): cmd.enable(pymod_element.get_pymol_selector()) def show_hedgehog_in_pymol(self, pymod_element): pymol_object_name = pymod_element.get_pymol_selector() cmd.hide("everything", pymol_object_name) cmd.show("cartoon", pymol_object_name) # Show the new chain as a cartoon. cmd.show("sticks", "(%s and name cb) or (%s and name ca)" % (pymol_object_name, pymol_object_name)) def show_het_in_pymol(self, pymod_element): self._set_het_show_state_in_pymol(pymod_element, show=True) def hide_het_in_pymol(self, pymod_element): self._set_het_show_state_in_pymol(pymod_element, show=False) def _set_het_show_state_in_pymol(self, pymod_element, show): pymol_object_name = pymod_element.get_pymol_selector() het_residues = pymod_element.get_residues(standard=False, ligands=True, modified_residues=True, water=False) for het_res in het_residues: resname = het_res.three_letter_code res_sel = het_res.get_pymol_selector() if self.TEST or self.DEVELOP: print(resname, res_sel) if resname in sphere_hetres_names: if show: cmd.show("spheres", res_sel) else: cmd.hide("spheres", res_sel) else: if show: cmd.show("sticks", res_sel) else: cmd.hide("sticks", res_sel) ############################################################################################### # Import structures from PyMOL. # ############################################################################################### def import_pymol_selections_from_main_menu(self): """ Method for importing PyMOL Selections into PyMod. It saves PyMOL objects selected by users to file, and loads it into PyMOL using 'open_structure_file()'. """ # Find all structures already loaded into PyMod: items in struct_list are excluded from # importable PyMOL object list. struct_list = [member.get_pymol_selector() for member in self.get_pymod_elements_list() if member.has_structure()] # Importable PyMOL objects. scrolledlist_items = [str(obj) for obj in cmd.get_names("objects") if not obj in struct_list and cmd.get_type(obj) == "object:molecule"] if not scrolledlist_items: if struct_list: self.main_window.show_error_message("No Importable Object", "All PyMOL objects are already imported into PyMod.") else: self.main_window.show_error_message("No Importable Object", "No PyMOL object to import.") return # Builds a new window. self.import_from_pymol_window = Import_from_pymol_window_qt(self.main_window, title="Import from PyMOL", upper_frame_title="Load PyMOL Objects into PyMod", submit_command=self.import_selected_pymol_object, selections_list=scrolledlist_items) self.import_from_pymol_window.show() def import_selected_pymol_object(self): selections_to_import = self.import_from_pymol_window.get_objects_to_import() if len(selections_to_import) > 0: for selected_num, sele in enumerate(selections_to_import): selected_num+=1 filename=sele+".pdb" pdb_file_shortcut = os.path.join(self.structures_dirpath, filename) cmd.save(pdb_file_shortcut,sele) cmd.delete(sele) self.open_structure_file(os.path.abspath(pdb_file_shortcut)) self.import_from_pymol_window.destroy() self.main_window.gridder(update_elements=True) else: self.main_window.show_error_message("Selection Error", "Please select at least one object to import.")
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_main/_workspaces.py
.py
8,643
218
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ PyMod sessions managment. """ import os import shutil import pickle import zipfile from pymod_lib.pymod_gui.shared_gui_components_qt import askopenfile_qt from pymol import cmd import pymod_lib.pymod_vars as pmdt class PyMod_workspaces: def start_new_session(self): # Cleans the main window. self.clear_main_window() # Reinitializes all PyMod elements and counters. self.initialize_pymod_elements_information() # Build a new project directory. self.new_job_state(overwrite=True) def clear_main_window(self): # Cleans the main window. for e in self.get_pymod_elements_list(): self.main_window.delete_element_widgets(e) ################## # Save sessions. # ################## def save_pymod_session(self, project_arc_full_path): try: # Builds a temporary directory in which to store the project files and which will become zipped. project_temp_dirpath = os.path.join(self.current_pymod_dirpath, self.session_temp_dirname) if os.path.isdir(project_temp_dirpath): shutil.rmtree(project_temp_dirpath) os.mkdir(project_temp_dirpath) # Saves a pickle file with the information about the PyMod session. This will remove # PyQt and Tkinter objects stored in the 'PyMod_element' objects, because they can't be pickled. project_pickle_filepath = os.path.join(project_temp_dirpath, "%s.pkl" % self.session_filename) # Temporarily removes the PyQt objects from the main PyMod object so that it can be # pickled. _app = self.app _main_window = self.main_window self.app = None self.main_window = None window_dict = {} for attr_name in dir(self): attr_obj = getattr(self, attr_name) # PyMod windows have the 'is_pymod_window' attribute. if hasattr(attr_obj, "is_pymod_window"): window_dict[attr_name] = attr_obj setattr(self, attr_name, None) with open(project_pickle_filepath, "wb") as a_fh: pickle.dump(self, a_fh) # Restores the GUI objects. self.app = _app self.main_window = _main_window for attr_name in window_dict: setattr(self, attr_name, window_dict[attr_name]) # Saves a PyMOL session. cmd.save(os.path.join(project_temp_dirpath, "%s.pse" % self.session_filename)) # Copies the current project files in the directory. src = self.current_project_dirpath dst = os.path.join(project_temp_dirpath, self.session_filename) shutil.copytree(src, dst) # Builds a .zip file of the temporary directory. src = project_temp_dirpath zpf = project_arc_full_path # os.path.join(project_temp_dirpath, project_arc_name) shutil.make_archive(zpf, 'zip', src) # Removes the .zip extension which is added by the 'make_archive' method. if os.path.isfile(zpf + ".zip"): shutil.move(zpf + ".zip", zpf) # Finally removes the temporary directory. shutil.rmtree(project_temp_dirpath) except Exception as e: if os.path.isdir(project_temp_dirpath): shutil.rmtree(project_temp_dirpath) title = "Save Project Error" message = "Could not save the project file to path: %s" % (project_arc_full_path) if self.main_window is None: self.main_window = _main_window self.main_window.show_error_message(title, message) ################### # Loads sessions. # ################### def open_pymod_session(self, project_archive_filepath): # If some errors happen here, continue the PyMod session. try: # Check if the file is a valid zip file. if not zipfile.is_zipfile(project_archive_filepath): raise Exception("The file is not a zip file.") # Check if the file is a valid PyMod session file. zfh = open(project_archive_filepath, 'rb') zipfile_obj = zipfile.ZipFile(zfh) files_to_check = ["%s.pkl" % self.session_filename, "%s.pse" % self.session_filename] if not set(files_to_check) < set(zipfile_obj.namelist()): zfh.close() raise Exception("The file is not a valid PyMod session file.") zfh.close() # Builds a temporary directory in which to store project files. project_temp_dirpath = os.path.join(self.current_pymod_dirpath, self.session_temp_dirname) if os.path.isdir(project_temp_dirpath): shutil.rmtree(project_temp_dirpath) os.mkdir(project_temp_dirpath) # Extract the file to a temporary directory. shutil.unpack_archive(project_archive_filepath, project_temp_dirpath, format="zip") except Exception as e: self.load_project_failure(project_archive_filepath, e, project_temp_dirpath, continue_session=True) return None # If some errors happens here, close PyMod. try: original_project_name = self.current_project_name # Clears the main window. self.clear_main_window() # Unpickle the data of the saved PyMod project. project_pickle_filepath = os.path.join(project_temp_dirpath, "%s.pkl" % self.session_filename) _app = self.app _main_window = self.main_window a_fh = open(project_pickle_filepath, "rb") self.__dict__ = pickle.load(a_fh).__dict__ a_fh.close() self.app = _app self.main_window = _main_window # Reinitializes the tools parameters from the configuration file. self.initializes_main_paths() self.get_parameters_from_configuration_file() self.initialize_session(original_project_name, saved_session=True) # Reinitializes the GUI of the PyMod elements. for el in self.get_pymod_elements_list(): # Initializes in PyMod and add the GUI swidgets. el.initialize(self) # Updates the structure paths. if el.has_structure(): el.update_all_structure_paths(self.structures_dirpath) # Updates the alignment files (such as trees and dendrograms). if el.is_cluster(): el.update_alignment_files(self.alignments_dirpath) # Loads a PyMOL session. pymol_session_filepath = os.path.join(project_temp_dirpath, "%s.pse" % self.session_filename) cmd.reinitialize() cmd.load(pymol_session_filepath) # Moves the saved session files in the directory current project directory. os.chdir(self.current_pymod_dirpath) shutil.rmtree(self.current_project_dirpath) shutil.move(os.path.join(self.session_temp_dirname, self.session_filename), self.current_project_dirpath) os.chdir(self.current_project_dirpath) # Removes the temporary session directory. shutil.rmtree(project_temp_dirpath) # Updates PyMod main window. self.main_window.gridder(clear_selection=True, update_clusters=True, update_menus=True, update_elements=True) except Exception as e: raise e self.load_project_failure(project_archive_filepath, e, project_temp_dirpath, continue_session=False) def load_project_failure(self, project_archive_filepath, error, project_temp_dirpath, continue_session=True): if os.path.isdir(project_temp_dirpath): shutil.rmtree(project_temp_dirpath) title = "Open Project Error" message = "Could not open the project file '%s': because of the following error: %s." % (project_archive_filepath, error) if not continue_session: message += " PyMod is now shutting down." self.main_window.show_error_message(title, message) if not continue_session: self.main_window.destroy()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_main/_main_menu_commands.py
.py
44,228
983
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Commands executed when interacting with the PyMod main window. """ import os import sys import shutil import re import webbrowser import json from Bio import Phylo from pymol.Qt import QtWidgets import pymol import pymod_lib from pymod_lib import pymod_os_specific as pmos from pymod_lib import pymod_vars from pymod_lib.pymod_gui.shared_gui_components_qt import askyesno_qt, asksaveasfile_qt, askopenfile_qt, askopenfiles_qt from pymod_lib.pymod_gui.specific_gui_components_qt import Raw_sequence_window_qt, PyMod_options_window_qt from pymod_lib.pymod_plot import pymod_plot_qt from pymod_lib.pymod_seq.seq_manipulation import compute_sequence_identity from pymod_lib.pymod_exceptions import PyModInvalidFile, PyModUnknownFile from pymod_lib.pymod_gui.pymod_table import QtTableWindow from pymod_lib.pymod_protocols.similarity_searches_protocols.ncbi_blast import NCBI_BLAST_search from pymod_lib.pymod_protocols.similarity_searches_protocols.local_blast import LOC_BLAST_search from pymod_lib.pymod_protocols.similarity_searches_protocols.psiblast import PSI_BLAST_search from pymod_lib.pymod_protocols.similarity_searches_protocols.phmmer import PHMMER_search from pymod_lib.pymod_protocols.similarity_searches_protocols.jackhmmer import Jackhmmer_search from pymod_lib.pymod_protocols.similarity_searches_protocols.hmmsearch import Hmmsearch_search from pymod_lib.pymod_protocols.similarity_searches_protocols.import_hhsuite import Import_HHsuite_results from pymod_lib.pymod_protocols.alignment_protocols.clustalw import Clustalw_regular_alignment, Clustalw_profile_alignment from pymod_lib.pymod_protocols.alignment_protocols.clustalo import Clustalomega_regular_alignment, Clustalomega_profile_alignment from pymod_lib.pymod_protocols.alignment_protocols.muscle import MUSCLE_regular_alignment from pymod_lib.pymod_protocols.alignment_protocols.salign_seq import SALIGN_seq_regular_alignment, SALIGN_seq_profile_alignment from pymod_lib.pymod_protocols.alignment_protocols.ce_alignment import CEalign_regular_alignment from pymod_lib.pymod_protocols.alignment_protocols.salign_str import SALIGN_str_regular_alignment from pymod_lib.pymod_protocols.domain_analysis_protocols.domain_analysis import Domain_Analysis_Protocol, Fuse_domains_protocol from pymod_lib.pymod_protocols.domain_analysis_protocols.split_domains import Split_into_domains_protocol from pymod_lib.pymod_protocols.evolutionary_analysis_protocols.campo import CAMPO_analysis from pymod_lib.pymod_protocols.evolutionary_analysis_protocols.scr_find import SCR_FIND_analysis from pymod_lib.pymod_protocols.evolutionary_analysis_protocols.entropy_scorer import Entropy_analysis from pymod_lib.pymod_protocols.evolutionary_analysis_protocols.pair_conservation import Pair_conservation_analysis from pymod_lib.pymod_protocols.evolutionary_analysis_protocols.weblogo import WebLogo_analysis from pymod_lib.pymod_protocols.evolutionary_analysis_protocols.espript import ESPript_analysis from pymod_lib.pymod_protocols.evolutionary_analysis_protocols.tree_building import Tree_building from pymod_lib.pymod_protocols.structural_analysis_protocols.ramachandran_plot import Ramachandran_plot from pymod_lib.pymod_protocols.structural_analysis_protocols.contact_map_analysis import Contact_map_analysis from pymod_lib.pymod_protocols.structural_analysis_protocols.structural_divergence_plot import Structural_divergence_plot from pymod_lib.pymod_protocols.structural_analysis_protocols.dope_assessment import DOPE_assessment, show_dope_plot from pymod_lib.pymod_protocols.structural_analysis_protocols.secondary_structure_assignment import Secondary_structure_assignment from pymod_lib.pymod_protocols.structural_analysis_protocols.psipred import PSIPRED_prediction from pymod_lib.pymod_protocols.modeling_protocols.homology_modeling import MODELLER_homology_modeling from pymod_lib.pymod_protocols.modeling_protocols.loop_refinement import MODELLER_loop_refinement from pymod_lib.pymod_protocols.updater_protocols import UpdaterProtocol class PyMod_main_menu_commands: ############################################################################################### # FILES MENU COMMANDS. # ############################################################################################### def open_file_from_the_main_menu(self): """ This method is called when using the 'File -> Open from File...' command in PyMod main menu. """ # Creates a tkinter widget that lets the user select multiple files. file_paths = askopenfiles_qt("Select files to open", name_filter="*.fasta *.fa *.gp *.pdb *.ent", parent=self.get_qt_parent()) # Loads each files in PyMod. loaded_sequences = False for single_file_path in file_paths: extension = os.path.splitext(single_file_path)[1].replace(".","").lower() try: if extension in ("fasta", "fa"): self.open_sequence_file(single_file_path, "fasta") elif extension == "gp": self.open_sequence_file(single_file_path, "genbank") elif extension in ("pdb", "ent"): self.open_structure_file(single_file_path, extension) else: raise PyModUnknownFile() loaded_sequences = True except PyModInvalidFile: title = "File Type Error" message = "The selected File ('%s') is not a valid '%s' file." % (single_file_path, pymod_vars.supported_sequence_file_types[extension]) self.main_window.show_error_message(title, message) except PyModUnknownFile: title = "File Type Error" message = "The selected File ('%s') has an unknown file extension '%s'." % (single_file_path, extension) self.main_window.show_error_message(title, message) if loaded_sequences: self.main_window.gridder() def open_alignment_from_main_menu(self): """ Lets users import in Pymod an alignment stored in an external file. """ openfilename, extension = self.choose_alignment_file() if not None in (openfilename, extension): self.build_cluster_from_alignment_file(openfilename, extension) self.main_window.gridder(update_menus=True, update_elements=True) #------------ # HH-suite. - #------------ def open_hhsuite_hhr_from_main_menu(self): import_protocol = Import_HHsuite_results(self, output_directory=self.similarity_searches_dirpath) import_protocol.launch_from_gui(mode="hhr") def open_hhsuite_a3m_from_main_menu(self): import_protocol = Import_HHsuite_results(self, output_directory=self.similarity_searches_dirpath) import_protocol.launch_from_gui(mode="a3m") ################################################################# # Add new sequences. # ################################################################# def show_raw_seq_input_window(self): """ Launched when the user wants to add a new sequence by directly typing it into a Text entry. """ self.raw_seq_window = Raw_sequence_window_qt(self.main_window, title="Add Raw Sequence", upper_frame_title="Type or Paste your Sequence", submit_command=self.raw_seq_input_window_state) self.raw_seq_window.show() # self.raw_seq_window.resize(700, self.raw_seq_window.sizeHint().height()) def raw_seq_input_window_state(self): """ This is called when the SUBMIT button of the 'Add Raw Sequence' is pressed. """ def special_match(strg, search=re.compile(r'[^QWERTYIPASDFGHKLXCVNM-]').search): return not bool(search(strg)) def name_match(strg, search2=re.compile(r'[^a-zA-Z0-9_]').search): return not bool(search2(strg)) sequence = self.raw_seq_window.get_sequence() sequence_name = self.raw_seq_window.get_sequence_name() if special_match(sequence) and len(sequence): if len(sequence_name) and name_match(sequence_name): self.add_element_to_pymod(self.build_pymod_element_from_args(sequence_name, sequence)) self.raw_seq_window.destroy() self.main_window.gridder() else: title = 'Sequence Name Error' message = 'Please check the sequence name: only letters, numbers and "_" are allowed.' self.main_window.show_error_message(title, message) else: title = 'Sequence Error' message = 'Please check your sequence: only standard amino acid letters, "X" and "-" are allowed.' self.main_window.show_error_message(title, message) ################################################################# # Saving files. # ################################################################# def sequence_save_dialog(self, element): """ Save a single sequence to a file. """ # Ask to remove indels. if "-" in element.my_sequence: remove_indels_choice = self.ask_to_remove_indels() else: remove_indels_choice = False # Choose the file path. filepath = asksaveasfile_qt("Save FASTA file", name_filter="*.fasta", parent=self.get_qt_parent()) if not filepath: return None # Actually saves the file. The file extension will not be added automatically. dirpath = os.path.dirname(filepath) filename = os.path.basename(filepath) self.build_sequence_file([element], filename, file_format="fasta", remove_indels=remove_indels_choice, new_directory=dirpath, add_extension=False) def save_selection_dialog(self, mode="selection"): """ Save selection in a single file. """ # Builds the selection. if mode == "selection": selection = self.get_selected_sequences() elif mode == "all": selection = self.get_all_sequences() else: raise KeyError("Unknown 'mode': %s" % mode) # Ask users if they want to include indels in the sequences to save. remove_indels_choice = False for e in selection: if "-" in e.my_sequence: remove_indels_choice = self.ask_to_remove_indels() break # Ask users to choose a directory where to save the file. filepath = asksaveasfile_qt("Save FASTA file", name_filter="*.fasta", parent=self.get_qt_parent()) if not filepath: return None dirpath = os.path.dirname(filepath) filename = os.path.basename(filepath) self.build_sequence_file(selection, filename, file_format="fasta", remove_indels=remove_indels_choice, same_length=remove_indels_choice, new_directory=dirpath, add_extension=False) def ask_to_remove_indels(self): title = "Save File" message = "Would you like to remove indels from the sequence when saving it to a file?" remove_indels_choice = askyesno_qt(title, message, parent=self.get_qt_parent()) return remove_indels_choice def alignment_save_dialog(self, alignment_element): """ Lets the user choose the path to which an alignment file is going to be saved, and saves an alignment file there. """ save_file_full_path = asksaveasfile_qt("Save an alignment file", name_filter="*.fasta;;*.aln;;*.sto", parent=self.get_qt_parent()) if not save_file_full_path: return None alignment_file_name, extension = os.path.splitext(os.path.basename(save_file_full_path)) extension = extension.replace(".", "") # The get all the aligned elements. aligned_elements = alignment_element.get_children() # Saves a file with all the sequences in the project "Alignments" directory. if extension == "fasta": self.save_alignment_fasta_file(alignment_file_name, aligned_elements) elif extension == "aln": self.build_sequence_file(aligned_elements, alignment_file_name, file_format="clustal", remove_indels=False) elif extension == "sto": self.build_sequence_file(aligned_elements, alignment_file_name, file_format="stockholm", remove_indels=False) # If the user didn't provide a valid extension. else: title = "Format Error" if extension != "": message = "Unknown alignment file extension: '%s'." % (extension) else: message = "No alignment file extension provided." message += " Please provide a valid extension. Example: .fasta (FASTA), .aln (Clustal) or .sto (Stockholm)" self.main_window.show_error_message(title, message) return # Moves the saved file to the path chosen by the user. try: old_path = os.path.join(self.alignments_dirpath, alignment_file_name + "." + extension) os.rename(old_path, save_file_full_path) except Exception as e: title = "File Error" message = "Could not save the alignment file to path '%s' for the following reason: %s." % (save_file_full_path, e) self.main_window.show_error_message(title, message) def save_pdb_chain_to_file_dialog(self, pymod_element): """ Save a PDB single chain to a file. """ # Choose the file path. filepath = asksaveasfile_qt("Save PDB file for this chain", name_filter="*.pdb", parent=self.get_qt_parent()) if not filepath: return None # Actually saves the file. try: if os.path.isfile(filepath): os.remove(filepath) shutil.copy(pymod_element.structure.current_chain_file_path, filepath) except Exception as e: title = "File Error" message = "Could not save the PDB chain file to path '%s' for the following reason: %s." % (filepath, e) self.main_window.show_error_message(title, message) ############################################################################################### # SIMILARITY SEARCHES. # ############################################################################################### def launch_blast_algorithm(self, blast_version): """ Called when BLAST or PSI-BLAST is launched from the main menu. """ if blast_version == "blast": blast_search = NCBI_BLAST_search(self, output_directory=self.similarity_searches_dirpath) elif blast_version == "psi-blast": blast_search = PSI_BLAST_search(self, output_directory=self.similarity_searches_dirpath) elif blast_version == "blastp": blast_search = LOC_BLAST_search(self, output_directory=self.similarity_searches_dirpath) else: raise KeyError(blast_version) blast_search.launch_from_gui() def launch_hmmer_algorithm(self, hmmer_version): if hmmer_version == "phmmer": hmmer_search = PHMMER_search(self, output_directory=self.similarity_searches_dirpath) elif hmmer_version == "jackhmmer": hmmer_search = Jackhmmer_search(self, output_directory=self.similarity_searches_dirpath) elif hmmer_version == "hmmsearch": hmmer_search = Hmmsearch_search(self, output_directory=self.similarity_searches_dirpath) else: raise KeyError(hmmer_version) hmmer_search.launch_from_gui() ############################################################################################### # DOMAIN ANALYSIS # ############################################################################################### def launch_domain_analysis(self, mode): dom_an = Domain_Analysis_Protocol(self, mode) dom_an.launch_from_gui() ############################################################################################### # ALIGNMENT BUILDING. # ############################################################################################### def launch_alignment_from_the_main_menu(self, program, strategy): """ Launched from the 'Sequence', 'Structure Alignment' or 'Profile Alignment' from the submenus of the main window. """ # Regular. if strategy == "regular": # Sequence alignments. if program == "clustalw": aligment_protocol_class = Clustalw_regular_alignment elif program == "clustalo": aligment_protocol_class = Clustalomega_regular_alignment elif program == "muscle": aligment_protocol_class = MUSCLE_regular_alignment elif program == "salign-seq": aligment_protocol_class = SALIGN_seq_regular_alignment # Structural alignments. elif program == "ce": aligment_protocol_class = CEalign_regular_alignment elif program == "salign-str": aligment_protocol_class = SALIGN_str_regular_alignment # Profile. elif strategy == "profile": if program == "clustalw": aligment_protocol_class = Clustalw_profile_alignment elif program == "clustalo": aligment_protocol_class = Clustalomega_profile_alignment elif program == "salign-seq": aligment_protocol_class = SALIGN_seq_profile_alignment # Actually launches the alignment protocol. a = aligment_protocol_class(self, output_directory=self.alignments_dirpath) a.launch_from_gui() ############################################################################################### # STRUCTURAL ANALYSIS TOOLS. # ############################################################################################### def assign_secondary_structure(self, element): sec_str_assignment = Secondary_structure_assignment(self, element) sec_str_assignment.assign_secondary_structure() def dope_from_main_menu(self): """ Called when users decide calculate DOPE of a structure loaded in PyMod. """ dope_assessment = DOPE_assessment(self) dope_assessment.launch_from_gui() def ramachandran_plot_from_main_menu(self): """ PROCHEK style Ramachandran Plot. """ ramachandran_plot = Ramachandran_plot(self) ramachandran_plot.launch_from_gui() def contact_map_from_main_menu(self): """ Contact/distance map analysis for one or more sequences. """ contact_analysis = Contact_map_analysis(self) contact_analysis.launch_from_gui() def sda_from_main_menu(self): """ Analyze the structural divergence between two or more aligned structures. """ sda_analysis = Structural_divergence_plot(self) sda_analysis.launch_from_gui() def launch_psipred_from_main_menu(self): """ Called when users decide to predict the secondary structure of a sequence using PSIPRED. """ psipred_protocol = PSIPRED_prediction(self) psipred_protocol.launch_from_gui() # def superpose_from_main_menu(self): # superpose_protocol = Superpose(self) # superpose_protocol.launch_from_gui() ############################################################################################### # MODELING. # ############################################################################################### def launch_modeller_hm_from_main_menu(self): modeller_session = MODELLER_homology_modeling(self) modeller_session.launch_from_gui() def launch_modeller_lr_from_main_menu(self): modeller_session = MODELLER_loop_refinement(self) modeller_session.launch_from_gui() ############################################################################################### # PYMOD OPTIONS WINDOW. # ############################################################################################### def show_pymod_options_window(self): """ Builds a window that allows to modify some PyMod options. """ self.pymod_options_window = PyMod_options_window_qt(self.main_window, pymod=self, title="PyMod Options", upper_frame_title="Here you can modify options for PyMod", submit_command=self.set_pymod_options_state) self.pymod_options_window.show() # self.pymod_options_window.resize(1100, 800) def set_pymod_options_state(self): """ This function is called when the SUBMIT button is pressed in the PyMod options window. """ old_projects_dir = self.pymod_plugin["pymod_dir_path"].get_value() new_projects_dir = self.pymod_options_window.get_value_from_gui(self.pymod_plugin["pymod_dir_path"]) if not os.path.isdir(new_projects_dir): title = "Configuration Error" message = "The PyMod Projects Directory you specified ('%s') does not exist on your system. Please choose an existing directory." % (new_projects_dir) self.main_window.show_error_message(title, message) return False # Saves the changes to PyMod configuration file. with open(self.cfg_file_path, 'w') as cfgfile: pymod_config_data = {} for tool in self.pymod_tools: new_tool_parameters = {} for parameter in tool.parameters: if parameter.can_be_updated_from_gui(): new_tool_parameters.update({parameter.name: self.pymod_options_window.get_value_from_gui(parameter)}) else: new_tool_parameters.update({parameter.name: parameter.get_value()}) new_tool_dict = {tool.name: new_tool_parameters} pymod_config_data.update(new_tool_dict) cfgfile.write(json.dumps(pymod_config_data)) # Then updates the values of the parameters of the tools contained in "self.pymod_tools" so # that they can be used in the current PyMod session. try: # Prevents the user from changing the project directory during a session. self.get_parameters_from_configuration_file() if old_projects_dir != new_projects_dir: title = "Configuration Updated" message = "You changed PyMod projects directory, the new directory will be used the next time you launch PyMod." self.main_window.show_warning_message(title, message) self.pymod_options_window.destroy() except Exception as e: self.show_configuration_file_error(e, "read") self.main_window.close() ############################################################################################### # ALIGNMENT MENU AND ITS BEHAVIOUR. # ############################################################################################### def save_alignment_to_file_from_ali_menu(self, alignment_element): self.alignment_save_dialog(alignment_element) def launch_campo_from_main_menu(self, pymod_cluster): campo = CAMPO_analysis(self, pymod_cluster) campo.launch_from_gui() def launch_scr_find_from_main_menu(self, pymod_cluster): scr_find = SCR_FIND_analysis(self, pymod_cluster) scr_find.launch_from_gui() def launch_entropy_scorer_from_main_menu(self, pymod_cluster): entropy_scorer = Entropy_analysis(self, pymod_cluster) entropy_scorer.launch_from_gui() def launch_pc_from_main_menu(self, pymod_cluster): entropy_scorer = Pair_conservation_analysis(self, pymod_cluster) entropy_scorer.launch_from_gui() def launch_weblogo_from_main_menu(self, pymod_cluster): weblogo = WebLogo_analysis(self, pymod_cluster) weblogo.launch_from_gui() def launch_espript_from_main_menu(self, pymod_cluster): espript = ESPript_analysis(self, pymod_cluster) espript.launch_from_gui() ################################################################# # Build and display sequence identity and RMSD matrices of # # alignments. # ################################################################# def display_identity_matrix(self, alignment_element): """ Computes the current identity matrix of an alignment and shows it in a new window. """ # Then get all its children (the aligned elements). aligned_elements = alignment_element.get_children() n = len(aligned_elements) # identity_matrix = [[None]*n]*n # [] # Builds an empty (nxn) "matrix". identity_matrix = [] for a in range(n): identity_matrix.append([None]*n) # Computes the identities (or anything else) and builds the matrix. for i in range(len(aligned_elements)): for j in range(len(aligned_elements)): if j >= i: sid = compute_sequence_identity(aligned_elements[i].my_sequence, aligned_elements[j].my_sequence) # This will fill "half" of the matrix. identity_matrix[i][j] = sid # This will fill the rest of the matrix. Comment this if want an "half" matrix. identity_matrix[j][i] = sid # Build the list of sequences names. sequences_names = [] for e in aligned_elements: sequences_names.append(e.compact_header) title = 'Identity matrix for ' + alignment_element.my_header self.show_table(sequences_names, sequences_names, identity_matrix, title) def display_rmsd_matrix_from_alignments_menu(self, alignment_element): # Checks the elements of the alignment. alignments_elements = alignment_element.get_children() aligned_structures = [e for e in alignments_elements if e.has_structure()] if len(aligned_structures) < 2: self.main_window.show_error_message("Selection Error", ("A RMSD matrix can only be computed on alignments containing at least" " two elements having a 3D structure loaded in PyMOL.")) return None if any([e.polymer_type == "nucleic_acid" for e in aligned_structures]): self.main_window.show_error_message("Selection Error", "Can not perform the analysis for nucleic acids structures.") return None if not alignment_element.algorithm in pymod_vars.structural_alignment_tools: message = pymod_vars.structural_alignment_warning % "RMSD matrix" self.main_window.show_warning_message("Alignment Warning", message) ali_protocol = CEalign_regular_alignment(self) alignment_element.rmsd_dict = ali_protocol.compute_rmsd_dict(aligned_structures) self.display_rmsd_matrix(alignment_element) def display_rmsd_matrix(self, alignment_element): """ Computes the current identity matrix of an alignment and shows it in a new window. """ aligned_elements = [e for e in alignment_element.get_children() if e.has_structure()] rmsd_dict = alignment_element.rmsd_dict rmsd_matrix_to_display = [] n = len(aligned_elements) rmsd_matrix_to_display = [[None]*n for a in range(n)] for i, ei in enumerate(aligned_elements): for j, ej in enumerate(aligned_elements): if j >= i: # This will fill "half" of the matrix. if rmsd_dict[(ei.unique_index, ej.unique_index)] is not None: rmsd_matrix_to_display[i][j] = round(rmsd_dict[(ei.unique_index, ej.unique_index)], 4) # This will fill the rest of the matrix. Comment this if want an "half" matrix. if rmsd_dict[(ej.unique_index, ei.unique_index)] is not None: rmsd_matrix_to_display[j][i] = round(rmsd_dict[(ej.unique_index, ei.unique_index)], 4) # Build the list of sequences names. sequences_names = [e.compact_header for e in aligned_elements] title = 'RMSD matrix for ' + alignment_element.my_header self.show_table(sequences_names, sequences_names, rmsd_matrix_to_display, title) def show_table(self, column_headers=None, row_headers=None, data_array=[], title="New Table", # columns_title=None, rows_title=None, # rowheader_width=20, number_of_tabs=2, sortable=False, row_headers_height=25, width=800, height=450 ): """ Displayes in a new window a table with data from the bidimensional 'data_array' numpy array. """ # Builds a new window in which the table will be displayed. new_window = QtTableWindow(parent=self.main_window, title=title, data=data_array, row_labels=row_headers, row_labels_height=row_headers_height, column_labels=column_headers, sortable=sortable,) new_window.show() ################################################################# # Show guide trees and build trees out of alignments. # ################################################################# def show_guide_tree_from_alignments_menu(self, alignment_element): """ Shows the guide tree that was constructed in order to perform a multiple alignment. """ # Gets the path of the .dnd file of the alignment. self.show_tree(alignment_element.get_tree_file_path()) def show_tree(self, tree_file_path): # Reads a tree file using Phylo. tree = Phylo.read(tree_file_path, "newick") tree.ladderize() # Flip branches so deeper clades are displayed at top # Displays its content using pyqtgraph. pymod_plot_qt.draw_tree(tree=tree, pymod=self) def show_dendrogram_from_alignments_menu(self, alignment_element): """ Shows dendrograms built by SALIGN. """ pymod_plot_qt.draw_modeller_dendrogram(dendrogram_filepath=alignment_element.get_tree_file_path(), pymod=self) def build_tree_from_alignments_menu(self, alignment_element): """ Called when the users clicks on the "Build Tree from Alignment" voice in the Alignments menu. """ tree_building = Tree_building(self, input_cluster_element=alignment_element) tree_building.launch_from_gui() ############################################################################################### # MODELS MENU AND ITS BEHAVIOUR. # ############################################################################################### def save_modeling_session(self, modeling_session): """ Build a zip file of the modeling directory of a certain session. """ archive_path = asksaveasfile_qt("Save PyMod Session file", name_filter="*.zip", parent=self.get_qt_parent()) if not archive_path: return None try: pmos.zip_directory(directory_path=os.path.join(self.models_dirpath, os.path.basename(modeling_session.modeling_directory_path)), zipfile_path=archive_path) except: title = "File Error" message = "Could not save the modeling session file to path: %s" % (archive_path) self.main_window.show_error_message(title, message) def show_session_profile(self, modeling_session): """ Shows a DOPE profile of a modeling session. """ show_dope_plot(dope_plot_data=modeling_session.dope_profile_data, parent_window=self.main_window, pymod=self) def show_assessment_table(self, modeling_session): self.show_table(**modeling_session.assessment_table_data) ############################################################################################### # DOMAINS. # ############################################################################################### def launch_domain_splitting(self, pymod_element): protocol = Split_into_domains_protocol(self, pymod_element, output_directory=self.domain_analysis_dirpath) protocol.launch_from_gui() def launch_domain_fuse(self, pymod_element): protocol = Fuse_domains_protocol(self, pymod_element, output_directory=self.domain_analysis_dirpath) protocol.launch_from_gui() ############################################################################################### # SELECTION MENU COMMANDS. # ############################################################################################### def select_all_from_main_menu(self): self.select_all_sequences() def select_all_sequences(self): for element in self.get_pymod_elements_list(): element.widget_group.select_element(select_all=True) def deselect_all_from_main_menu(self): self.deselect_all_sequences() def deselect_all_sequences(self): for element in self.get_pymod_elements_list(): element.widget_group.deselect_element(deselect_all=True) def show_all_structures_from_main_menu(self): for element in self.get_pymod_elements_list(): if element.has_structure(): self.show_chain_in_pymol(element) def hide_all_structures_from_main_menu(self): for element in self.get_pymod_elements_list(): if element.has_structure(): self.hide_chain_in_pymol(element) def select_all_structures_from_main_menu(self): for element in self.get_pymod_elements_list(): if element.has_structure() and not element.selected: element.widget_group.toggle_element() def deselect_all_structures_from_main_menu(self): for element in self.get_pymod_elements_list(): if element.has_structure() and element.selected: element.widget_group.toggle_element() def expand_all_clusters_from_main_menu(self): for element in self.get_cluster_elements(): element.widget_group.expand_cluster() def collapse_all_clusters_from_main_menu(self): for element in self.get_cluster_elements(): element.widget_group.collapse_cluster() ############################################################################################### # DISPLAY MENU COMMANDS. # ############################################################################################### def change_font_from_action(self, font_type=None, font_size=None): self.main_window.update_font(font_type, font_size) def change_font_from_main_menu(self): """ Opens a font selector widget from Qt. """ font, font_is_valid = QtWidgets.QFontDialog.getFont() print("- Selected font:", font, font_is_valid) ############################################################################################### # HELP MENU COMMANDS. # ############################################################################################### developer_email = "giacomo.janson@uniroma1.it" def show_about_dialog(self): # Initializes the message box. about_dialog = PyMod_QMessageBox(self.get_qt_parent()) about_dialog.setIcon(QtWidgets.QMessageBox.Information) about_dialog.setWindowTitle(self.pymod_plugin_name) # Sets the main text. about_dialog.setText("Version: %s" % self.pymod_version + "." + self.pymod_revision) infomative_text = ('Copyright (C): 2020 Giacomo Janson, Alessandro Paiardini\n' 'Copyright (C): 2016 Giacomo Janson, Chengxin Zhang, Alessandro Paiardini' '\n\nFor information on PyMod %s visit:\n' ' http://schubert.bio.uniroma1.it/pymod/\n\n' 'Or send us an email at:\n %s' % (self.pymod_version, self.developer_email)) about_dialog.setInformativeText(infomative_text) # Adds detailed information. pymod_plugin_path = os.path.dirname(os.path.dirname(pymod_lib.__file__)) try: import PyQt5 pyqt5_version = PyQt5.QtCore.PYQT_VERSION_STR except: pyqt5_version = "-" try: from pymol import Qt pymol_pyqt_name = Qt.PYQT_NAME except: pymol_pyqt_name = "-" try: import Bio biopython_version = Bio.__version__ except: biopython_version = "-" try: import numpy numpy_version = numpy.__version__ except: numpy_version = "-" try: import modeller modeller_version = modeller.__version__ modeller_path = repr(modeller.__path__) except: modeller_version = "-" modeller_path = "-" try: import conda import conda.cli.python_api as conda_api conda_version = conda.__version__ if self.DEVELOP: conda_info_dict = json.loads(conda_api.run_command(conda_api.Commands.INFO, "--json")[0]) conda_info_text = "\n# Conda\n" for k in sorted(conda_info_dict.keys()): conda_info_text += "- %s: %s\n" % (k, repr(conda_info_dict[k])) except: conda_version = "-" conda_info_dict = {} conda_info_text = "" has_pymol_conda = str(hasattr(pymol, "externing") and hasattr(pymol.externing, "conda")) def _get_path_string(path): _path = path if os.path.isdir(_path): return _path else: return _path + " (not found)" additional_text = ("# PyMod\n" "- Version: " + self.pymod_version + "\n" "- Revision: " + self.pymod_revision + "\n" "- Plugin path: " + _get_path_string(pymod_plugin_path) + " \n" "- Config directory: " + _get_path_string(self.cfg_directory_path) + "\n" "- PyMod Directory: " + _get_path_string(self.current_pymod_dirpath) + "\n" "- Current PyMod project: " + _get_path_string(self.current_project_dirpath) + "\n\n" "# PyMOL\n" "- Version: " + str(pymol.cmd.get_version()[0]) + "\n" "- Path: " + sys.executable + "\n" "- Qt: " + str(pymol_pyqt_name) + "\n" "- Has Conda: " + has_pymol_conda + "\n\n" "# Python\n" "- Version: " + str(sys.version) + "\n" "- Arch: " + pmos.get_python_architecture() + "\n" "- Path: " + sys.executable + "\n\n" "# Operating system\n" "- Platform: " + sys.platform + "\n" "- Arch: " + pmos.get_os_architecture() + "\n\n" "# Python libs\n" "- PyQt5: " + pyqt5_version + "\n" "- Conda version: " + conda_version + "\n" "- Numpy version: " + numpy_version + "\n" "- Biopython version: " + biopython_version + "\n" "- MODELLER version: " + modeller_version + "\n" "- MODELLER path: " + modeller_path + "\n" ) if self.DEVELOP: additional_text += conda_info_text about_dialog.setDetailedText(additional_text) # Actually shows the message box. about_dialog.setModal(True) about_dialog.exec_() def open_online_documentation(self): webbrowser.open("https://github.com/pymodproject/pymod#how-to-use-pymod") def launch_databases_update(self): db_updater = UpdaterProtocol(self) db_updater.launch_from_gui() ############################################################################################### # SESSIONS. # ############################################################################################### def exit_from_main_menu(self): self.main_window.confirm_close() def start_new_session_from_main_menu(self): title = "Begin New Project?" message = ("Are you really sure you want to begin a new PyMod project? If" " you do not save your current project, its data will be" " permanently lost.") answer = askyesno_qt(title, message, parent=self.get_qt_parent()) if not answer: return None self.start_new_session() def save_session_from_main_menu(self): save_project_full_path = asksaveasfile_qt("Save PyMod Session file", name_filter="*.pmse", parent=self.get_qt_parent()) if not save_project_full_path: return None self.save_pymod_session(save_project_full_path) def open_session_from_main_menu(self): project_archive_filepath = askopenfile_qt("Open a PyMod Session file", name_filter="*.pmse", parent=self.get_qt_parent()) if not project_archive_filepath: return None if not os.path.isfile(project_archive_filepath): return None self.open_pymod_session(project_archive_filepath) class PyMod_QMessageBox(QtWidgets.QMessageBox): def closeEvent(self, event): self.close()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_main/_external.py
.py
2,083
56
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Interactions with external tools. """ import os import sys import subprocess from pymod_lib import pymod_os_specific as pmos class PyMod_external: modeller_lock_title = "MODELLER warning" modeller_lock_message = ("Can not safely exit a MODELLER thread. Please wait" " for it to complete (the only way to quit it is to" " forcibly close PyMOL, but all PyMOL/PyMod data will" " be lost).") def execute_subprocess(self, commandline, new_stdout=subprocess.PIPE, new_stderr=subprocess.PIPE, new_shell=(sys.platform!="win32"), verbose=True, executing_modeller=False): if verbose: print("- Executing the following command:", commandline) if not executing_modeller: subp = subprocess.Popen(commandline, stdout=new_stdout, stderr=new_stderr, shell=new_shell) out_std, err_std = subp.communicate() returncode = subp.returncode if verbose: print("- Stdout:", out_std) if returncode != 0: if verbose: print("- Code:", returncode, ", Stderr:", err_std) raise Exception("Subprocess returned non-zero return code: %s (%s)" % (returncode, err_std)) # Official PyMOL builds on Mac OS will crash if executing MODELLER through using the # 'subprocess' module. For this reason, the 'os' module will be used instead. else: os.system(commandline) def new_execute_subprocess(self, args, verbose=False): if verbose: print("- Executing the following command:", args) subprocess.check_call(args)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_main/_development.py
.py
8,800
217
""" Module for development. """ import os import sys import urllib.request import random import shutil import importlib from pymod_lib.pymod_seq.seq_star_alignment import global_pairwise_alignment_cs class PyMod_development: """ Methods used when developing or testing PyMod. """ def _launch_develop(self): """ For development only. The 'open_sequence_file', 'open_structure_file' and 'build_cluster_from_alignment_file' methods are used to import sequences when PyMod starts. The code in this method illustrates how to the API of PyMod to developers. """ return None #------------------------------------------ # Set up the paths of some example files. - #------------------------------------------ spec = importlib.util.find_spec("pymod_lib") if spec is None: raise Exception("'pymod_lib' module not found.") pymod_lib_data_dirpath = os.path.join(os.path.dirname(spec.origin), "pymod_data") alignment_filepath = os.path.join(pymod_lib_data_dirpath, "sequences", "PF00069_seed_min.fasta") sequence_filepath = os.path.join(pymod_lib_data_dirpath, "sequences", "sequence.fasta") pdb_filepath = os.path.join(pymod_lib_data_dirpath, "pdb", "1NDD.pdb") #------------------------------ # Examples of sequence files. - #------------------------------ # Loads every sequence present in a FASTA file in PyMod. elements = self.open_sequence_file(sequence_filepath) # Selects in PyMod the first element. elements[0].widget_group.toggle_element() # Loads a multiple sequence alignment in PyMod by putting all the # sequences in an alignment object. cluster = self.build_cluster_from_alignment_file(alignment_filepath) # Add to the alignment object the previously loaded elements. add_child = False if add_child: for e in elements: cluster.add_child(e) #------------------------------- # Example of a structure file. - #------------------------------- # Loads in PyMod/PyMOL all the chains present in a PDB file. chain_elements = self.open_structure_file(pdb_filepath) #------------------------------- # Build elements from scratch. - #------------------------------- # Takes the sequence of the first PDB chain loaded before, and initializes # a new PyMod element with a randomized copy of it. template_element = chain_elements[0] randomized_seq = self.randomize_sequence(template_element.my_sequence, n_gaps=1, n_insertions=1) new_element = self.build_pymod_element_from_args("test_sequence", randomized_seq) self.add_element_to_pymod(new_element) # Add a new alignment object to PyMod in which contains the randomized # sequence and the original PDB chain element. new_cluster = self.add_new_cluster_to_pymod(cluster_type="alignment", child_elements=[new_element, template_element], algorithm="imported") # Perform a sequence alignment between the two elements and updated their # sequence in PyMod. sq, st = global_pairwise_alignment_cs(new_element.my_sequence, template_element.my_sequence, 20, 5) new_element.my_sequence = sq template_element.my_sequence = st #----------------------- # Launching protocols. - #----------------------- # Load sessions. if 0: # Loads a PyMod session from the API. Useful when developing some # complex functionality which requires a lot of steps to test. project_archive_filepath = "/home/user/pymod_session.pmse" self.open_pymod_session(project_archive_filepath) # Automatically launches a protocol (input sequences must be correctly selected # in the code above). if 0: # Homology modeling. from pymod_lib.pymod_protocols.modeling_protocols.homology_modeling import MODELLER_homology_modeling modeller_session = MODELLER_homology_modeling(self) modeller_session.launch_from_gui() if 0: # Contact map. from pymod_lib.pymod_protocols.structural_analysis_protocols.contact_map_analysis import Contact_map_analysis Contact_map_analysis(self).launch_from_gui() if 0: # Multiple alignments. from pymod_lib.pymod_protocols.alignment_protocols.clustalo import Clustalomega_regular_alignment Clustalomega_regular_alignment(self).launch_from_gui() if 0: # BLAST. from pymod_lib.pymod_protocols.similarity_searches_protocols.psiblast import PSI_BLAST_search PSI_BLAST_search(self).launch_from_gui() if 0: # HMMER. from pymod_lib.pymod_protocols.similarity_searches_protocols.phmmer import PHMMER_search PHMMER_search(self).launch_from_gui() if 0: # HMMSCAN from pymod_lib.pymod_protocols.domain_analysis_protocols.domain_analysis import Domain_Analysis_Protocol Domain_Analysis_Protocol(self, "local").launch_from_gui() self.main_window.gridder(update_clusters=True, update_menus=True, update_elements=True) def load_uniprot_random(self, reviewed=False, grid=True): try: if reviewed: rev_string = "yes" else: rev_string = "no" temp_fasta_path = urllib.request.urlretrieve("http://www.uniprot.org/uniprot/?query=reviewed:%s+AND+organism:9606&random=yes&format=fasta" % rev_string)[0] self.open_sequence_file(temp_fasta_path) if grid: self.main_window.gridder(update_clusters=True, update_menus=True, update_elements=True) except Exception as e: if grid: self.main_window.show_error_message("UniProt Error", "Could not obtain a sequence from the UniProt server beacuse of the following reason: %s" % str(e)) def load_pdb_random(self, code=None, grid=True): try: spec = importlib.util.find_spec("pymod_lib") if spec is None: raise Exception("'pymod_lib' module not found.") pdb_list_filepath = os.path.join(os.path.dirname(spec.origin), "pymod_data", "pdb", "all_proteins.txt") if code is None: with open(pdb_list_filepath, "r") as p_fh: ids = [i.replace(" ", "") for i in p_fh.read().split("\n")] code = ids[random.randint(0, len(ids)-1)] print("\n# Fetching PDB: %s" % code) file_url = "https://files.rcsb.org/download/%s.pdb" % code temp_path = urllib.request.urlretrieve(file_url)[0] temp_pdb_path = os.path.join(os.path.dirname(temp_path), "%s.pdb" % code) shutil.move(temp_path, temp_pdb_path) elements = self.open_structure_file(temp_pdb_path) if grid: self.main_window.gridder(update_clusters=True, update_menus=True, update_elements=True) return elements except Exception as e: if grid: self.main_window.show_error_message("RCSB PDB Error", "Could not obtain a sequence from the RCSB server beacuse of the following reason: %s" % str(e)) def randomize_sequence(self, sequence, seqid=30.0, n_gaps=0, n_insertions=2): amino_acids = "QWERTYPASDFGHKLCVNM" # + "X" list_seq = list(sequence) n_substitutions = int(seqid*len(list_seq)/100.0) for s in range(0, n_substitutions): seq_len = len(list_seq) random_index = random.randint(0, seq_len-1) list_seq.pop(random_index) list_seq.insert(random_index, random.choice(amino_acids)) max_gap_length = 10 for g in range(0, n_gaps): seq_len = len(list_seq) random_index = random.randint(0, seq_len-1) gap_length = random.randint(0, max_gap_length) for l in range(0, gap_length): list_seq.pop(random_index-l) max_insertion_length = 18 for i in range(0, n_gaps): seq_len = len(list_seq) random_index = random.randint(0, seq_len-1) insertion_length = random.randint(0, max_insertion_length) for l in range(0, insertion_length): list_seq.insert(random_index, random.choice(amino_acids)) return "".join(list_seq)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_externals/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_externals/hhsuite/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_externals/hhsuite/hhmakemodel.py
.py
23,951
705
#!/usr/bin/env python from pymod_lib.pymod_externals.hhsuite.hh_reader import read_result from copy import deepcopy import re, os, sys, tempfile, glob from operator import itemgetter # hzhu from itertools import groupby # hzhu EMPTY = '*' GAP = '-' DEBUG_MODE = False class Gap: """ A gap is a continuous stretch of indels. It is defined by a opening position and a size/length """ def __init__(self, open_pos, size): self.open_pos = open_pos # gap opening position self.size = size # num of indels in the gap def __repr__(self): return 'Gap opening pos = %d, size = %d' % (self.open_pos, self.size) class Grid: """ Implementation of 2D grid of cells Includes boundary handling """ def __init__(self, grid_height, grid_width): """ Initializes grid to be empty, take height and width of grid as parameters Indexed by rows (left to right), then by columns (top to bottom) """ self._grid_height = grid_height self._grid_width = grid_width self._cells = [ [ EMPTY for dummy_col in range(self._grid_width) ] for dummy_row in range(self._grid_height)] def __str__(self): """ Return multi-line string represenation for grid """ ans = '' for row in range(self._grid_height): ans += ''.join(self._cells[row]) ans += '\n' return ans def clear(self): """ Clears grid to be empty """ self._cells = [[EMPTY for dummy_col in range(self._grid_width)] for dummy_row in range(self._grid_height)] def get_grid_height(self): """ Return the height of the grid """ return self._grid_height def get_grid_width(self): """ Return the width of the grid """ return self._grid_width def get_cell(self, row, col): return self._cells[row][col] def get_seq_start(self, row): """ Returns the start position of the sequence """ index = 0 for pos in self._cells[row]: if pos != EMPTY: return index index += 1 return None def get_seq_end(self, row): """ Returns the end position of the sequence """ index = 0 for pos in reversed(self._cells[row]): if pos != EMPTY: return self.get_grid_width() - index index += 1 return None def get_gaps(self, row): """ Return the position of gaps in a row """ gaps = list() index = 0 for pos in self._cells[row]: if pos == GAP: gaps.append(index) index += 1 return gaps def get_gaps_ref_gapless(self, row): """ Return the pos of gaps in a row. The opening positions of the gaps are wrt. the gapless seq """ # get all the indels indels = self.get_gaps(row) gaps = [] # combine continuous indels into a gap for k,i in groupby( enumerate(indels), lambda x: x[0]-x[1] ): g = list(map(itemgetter(1), i)) gaps.append( Gap(g[0], len(g)) ) # offset the gap opening positions for i in range(1, len(gaps)): # offset by total gap number before gaps[i].open_pos -= sum([gaps[j].size for j in range(i)]) return gaps # a list of Gap instances def get_seq_indeces(self, row): seq = list() for pos, res in enumerate(self._cells[row]): if res != EMPTY and res != GAP: seq.append(pos) return seq ## def get_gap_list(self): # hzhu commented this out. wrote a new version ## """ Returns a list of list of all gap positions in the sequence grid. """ ## gap_pos = set() ## for row in range(self.get_grid_height()): ## for gap in self.get_gaps(row): ## gap_pos.add(gap) ## gap_pos = list(sorted(gap_pos)) ## boundaries = [ (x + 1) for x, y in zip(gap_pos, gap_pos[1:]) if y - x != 1 ] ## gap_list = list() ## prev = 0 ## for boundary in boundaries: ## sub_list = [ pos for pos in gap_pos[prev:] if pos < boundary ] ## gap_list.append(sub_list) ## prev += len(sub_list) ## gap_list.append([ x for x in gap_pos[prev:]]) ## return gap_list def get_gap_list(self): """ Returns a list of Gap instances for all rows in the grid """ gap_dict = dict() # each position should occur as gap at most once # keys are gap openning positions # values are Gap instances gap_list = [] for row in range(self.get_grid_height()): gap_pos = [] gaps = self.get_gaps_ref_gapless(row) for g in gaps: if g.open_pos in gap_dict: # if there is already gaps at this open pos if g.size > gap_dict[g.open_pos].size: # if new gap is bigger gap_dict[g.open_pos] = g # keep the larger gap as they overlap else: gap_dict[g.open_pos] = g gap_list = sorted(list(gap_dict.values()), key=lambda x: x.open_pos) # sort according to start position return gap_list # a list of Gap instances def set_gap(self, row, col): """ Set cell with index (row, col) to be a gap """ self._cells[row][col] = GAP def set_empty(self, row, col): """ Set cell with index (row, col) to be a gap """ self._cells[row][col] = EMPTY def set_cell(self, row, col, res): """ Set cell with index (row, col) to be full """ self._cells[row][col] = res def is_empty(self, row, col): """ Checks whether cell with index (row, col) is empty """ # return self._cells[row][col] == EMPTY try: return self._cells[row][col] == EMPTY except IndexError: print("WARNING!") return True def is_gap(self, row, col): """ Checks whetehr cell with indxex (row, col) is a gap """ return self._cells[row][col] == GAP def insert_gaps(self, cols): """ Inserts a gaps into a column of the template grid """ for col in cols: for row in range(self._grid_height): if col >= self.get_seq_start(row) and col < self.get_seq_end(row): self._cells[row].insert(col, GAP) else: self._cells[row].insert(col, EMPTY) self._grid_width += 1 def insert_gaps_row(self, cols, row): """ Intert gaps into cols only for certain row""" for col in cols: if col >= self.get_seq_start(row) and col < self.get_seq_end(row): self._cells[row].insert(col, GAP) else: self._cells[row].insert(col, EMPTY) # NOTE: grid_with should not be changed after every row is updated. #self._grid_width += 1 def clean_trail_empty(self): """ Remove all trailing EMPTY and pad grid to same width""" # first find out the max length (exluding trailing EMPTY) max_width = 0 for row in range(self._grid_height): for i in range(len(self._cells[row])-1, -1, -1): if self._cells[row][i] != EMPTY: break if i+1 > max_width: max_width = i+1 # delete excessive EMPTY for row in range(self._grid_height): del self._cells[row][max_width:] # then pad all rows to the same length [self._cells[row].append( EMPTY * (max_width-len(self._cells[row])) ) \ for row in range(self._grid_height) if len(self._cells[row]) < max_width] self._grid_width = max_width return def remove_gaps(self, keep_width=True): # hzhu add keep_width option """ Removes all gaps from the grid. """ for row in range(self.get_grid_height()): not_gap = list() for col in range(self.get_grid_width()): if not self.is_gap(row, col): not_gap.append(col) self._cells[row] = [ self._cells[row][col] for col in not_gap ] if keep_width: # hzhu only pad to original width if desired for del_pos in range(self._grid_width - len(not_gap)): self._cells[row].append(EMPTY) if not keep_width: # hzhu if width is not kept, make sure width is consistent self.clean_trail_empty() return class QueryGrid(Grid): def __init__(self, grid_height, grid_width): Grid.__init__(self, grid_height, grid_width) def get_query_start(self, row): """ Returns the query start position """ return self.get_seq_start(row) + 1 def get_query_end(self, row): """ Returns the query end postion """ return self.get_seq_end(row) - len(self.get_gaps(row)) def get_col_residue(self, col): """ Tries to find a the query residue in a given column. Used by derive_global_seq() to identify the global query sequence """ for row in range(self.get_grid_height()): if not self.is_empty(row, col): return self._cells[row][col] return GAP class TemplateGrid(Grid): def __init__(self, grid_height, grid_width): Grid.__init__(self, grid_height, grid_width) self._start = list() self._end = list() self._pdb_code = list() self._chain = list() self._organism = list() self._resolution = list() def display(self): """ Return multi-line string represenation for grid """ ans = '' for row in range(self._grid_height): ans += '>P1;{p}\nstructure:{p}:{s}:{c}:{e}:{c}::{o}:{r}:\n{a}*\n'.format( p = self._pdb_code[row], s = add_white_space_end(self.get_template_start(row), 4), e = add_white_space_end(self.get_template_end(row), 4), c = self._chain[row], o = self._organism[row], r = self._resolution[row], a = ''.join(self._cells[row]).replace(EMPTY, GAP).replace('#', GAP)) return ans def debug(self, row): """ Return multi-line string represenation for grid, for debugging purposes """ ans = '{p}\nInternal: {s}, {e} Query: {qs}, {qe} Gaps ({g1}): {g2}\n{seq}\n'.format( p = self._pdb_code[row], s = self.get_seq_start(row), e = self.get_seq_end(row), qs = self.get_template_start(row), qe = self.get_template_end(row), g1 = len(self.get_gaps(row)), g2 = ', '.join([str(gap) for gap in self.get_gaps(row)]), seq = ''.join(self._cells[row])) return ans def set_metadata(self, row, start, end, pdb_code, chain, organism, resolution): """ Used by create_template_grid() to setup metadata of pir template """ self._start.append(start) self._end.append(end) self._pdb_code.append(pdb_code) self._chain.append(chain) self._organism.append(organism) self._resolution.append(resolution) def set_map(self, row, start, end): self._start[row] = start self._end[row] = end def get_template_start(self, row): """ Returns the template start position """ return self._start[row] def get_template_end(self, row): """ Return sthe template end position """ return self._end[row] def del_row(self, row): """ Removes a complete template entry from the grid """ del self._cells[row] del self._start[row] del self._end[row] del self._pdb_code[row] del self._chain[row] del self._organism[row] del self._resolution[row] self._grid_height -= 1 # Helper functions def add_white_space_end(string, length): """ Adds whitespaces to a string until it has the wished length""" edited_string = str(string) if len(edited_string) >= length: return string else: while len(edited_string) != length: edited_string += ' ' return edited_string def get_query_name(hhr_file): with open(hhr_file) as fh: for line in fh: if line.startswith('Query'): # match the PDB Code m = re.search('(\d[A-Z0-9]{3})_(\S)', line) if m: pdb_code = m.group(1) chain = m.group(2) else: pdb_code = 'UKNP' chain = 'A' # raise ValueError('Input HHR-File Does not seem to be a PDB-Structure') break return pdb_code, chain def template_id_to_pdb(template_id): """ Extracts PDB ID and chain name from the provided template id """ # match PDBID without chain (8fab, 1a01) m = re.match(r'/^(\d[A-Za-z0-9]{3})$', template_id) if m: return m.group(1).upper(), 'A' # PDB CODE with chain Identifier m = re.match(r'^(\d[A-Za-z0-9]{3})_(\S)$', template_id) if m: return m.group(1).upper(), m.group(2).upper() # Match DALI ID m = re.match(r'^(\d[A-Za-z0-9]{3})([A-Za-z0-9]?)_\d+$', template_id) if m: return m.group(1).upper(), m.group(2).upper() # No PDB code and chain identified return None, None def create_template_grid(hhr_data): """ Creates a template grid """ total_seq = len(hhr_data) templ_max = max( [ hhr.start[0] + len(to_seq(hhr.template_ali)) for hhr in hhr_data ] ) - 1 template_grid = TemplateGrid(total_seq, templ_max) for row, template in enumerate(hhr_data): seq_start = template.start[0] - 1 templatealignment = to_seq(template.template_ali) seq_end = seq_start + len(templatealignment) # Load Meta Data start = template.start[1] end = template.end[1] # Get pdb_code and chain identifier of template pdb_code, chain = template_id_to_pdb(template.template_id) m = re.search("(\d+.\d+)A", template.template_info) # try to extract resolution of the structure if m: resolution = m.group(1) else: resolution = "" m = re.search("\{(.*)\}", template.template_info) # try to extract the organism if m: organism = m.group(1).replace(":", " ") # make sure that no colons are in the organism else: organism = "" template_grid.set_metadata(row, start, end, pdb_code, chain, organism, resolution) # Write sequence into the grid for pos, col in enumerate(range(seq_start, seq_end)): template_grid.set_cell(row, col, templatealignment[pos]) return template_grid def to_seq(ali): if isinstance(ali, list): return ''.join(ali) else: return ali def create_query_grid(hhr_data): """ Creates a Query Grid """ total_seq = len(hhr_data) query_max = max( [ hhr.start[0] + len(to_seq(hhr.query_ali)) for hhr in hhr_data ] ) - 1 query_grid = QueryGrid(total_seq, query_max) for row, query in enumerate(hhr_data): queryalignment = to_seq(query.query_ali) query_start = query.start[0] - 1 query_end = query_start + len(queryalignment) for pos, col in enumerate(range(query_start, query_end)): if queryalignment[pos] not in ['Z', 'U', 'O', 'J', 'X', 'B']: # CAUTION query_grid.set_cell(row, col, queryalignment[pos]) return query_grid def create_gapless_grid(grid): """ Returns a gapless grid """ gapless = deepcopy(grid) gapless.remove_gaps(keep_width=False) # hzhu: shrink grid return gapless def process_query_grid(query_grid, gapless_grid): """ Processes a query grid sucht that it contains all gaps """ gaplist = query_grid.get_gap_list() off_set = 0 for g in gaplist: gapless_grid.insert_gaps([ p + off_set for p in range(g.open_pos, g.open_pos+g.size) ]) off_set += g.size return gapless_grid def derive_global_seq(processed_query_grid, query_name, query_chain): global_seq = list() for col in range(processed_query_grid.get_grid_width()): global_seq.append(processed_query_grid.get_col_residue(col)) # this is the query entry header = '>P1;{q}\nsequence:{q}:1 :{c}:{l} :{c}::::\n'.format( q = query_name, l = len(global_seq), c = query_chain) return header + ''.join(global_seq) + '*' def process_template_grid(query_grid, template_grid): """ Insertes Gaps into the template grid Only add gaps from **other** query_grids into template grid (NOT gapless) """ gaplist = query_grid.get_gap_list() # use this to keep the offset for row in range(template_grid.get_grid_height()): # do NOT consider gaps in current query row gaplist_row = query_grid.get_gaps_ref_gapless(row) gapdict_row = dict(zip([g.open_pos for g in gaplist_row], [g.size for g in gaplist_row])) off_set = 0 for g in gaplist: # if there is a gap with same opening position in the current row, # only consider g if it is larger than the on in the current row if g.open_pos in gapdict_row: if g.size > gapdict_row[g.open_pos]: template_grid.insert_gaps_row([ p + off_set for p in range(g.open_pos, g.open_pos+g.size-gapdict_row[g.open_pos]) ], row) else: template_grid.insert_gaps_row([ p + off_set for p in range(g.open_pos, g.open_pos+g.size) ], row) off_set += g.size # even if the gaps are not inserted, the offset should be adjusted template_grid.clean_trail_empty() # clean the redundant trailing EMPTY char return template_grid def remove_self_alignment(template_grid, query_name): """ Removes a self alignment from the final pir alignment to prevent clashes with MODELLER """ to_delete = list() for row in range(template_grid.get_grid_height()): if template_grid._pdb_code[row] == query_name: to_delete.append(row) for row in reversed(to_delete): template_grid.del_row(row) return True def write_to_file(line_list, fname): """ Writes the final pir file """ with open(fname, 'w+') as fout: for line in line_list: fout.write(line + "\n") def arg(): import argparse description = """Creates a MODELLER alignment (*.pir) from a HHSearch results file (*.hhr).""" epilog= '2016 Harald Voehringer.' # Initiate a ArgumentParser Class parser = argparse.ArgumentParser(description = description, epilog = epilog) # Call add_options to the parser parser.add_argument('input', help = 'results file from HHsearch with hit list and alignment', metavar = 'FILE') parser.add_argument('cifs', help = 'path to the folder containing cif files', metavar = 'DIR') parser.add_argument('pir', help = 'output file (PIR-formatted multiple alignment)', metavar = 'FILE') parser.add_argument('output', help = 'path to the folder where modified cif files should be written to', metavar = 'DIR') parser.add_argument('-v', '--verbose', action = 'store_true', help = 'verbose mode') parser.add_argument('-m', nargs = '+', help = 'pick hits with specified indices (e.g. -m 2 5)', metavar = 'INT') parser.add_argument('-e', type = float, help = 'maximum E-Value threshold (e.g. -e 0.001)', metavar = 'FLOAT') parser.add_argument('-r', type = float, help = 'residue ratio (filter alignments that have contribute at least residues according to the specified ratio).', default = 0, metavar = 'FLOAT') parser.add_argument('-c', help = 'convert non-canonical residues (default = True)', action = 'store_true', default = True) return parser class PyMod_args: def __init__(self, args_dict): for arg in args_dict: setattr(self, arg, args_dict[arg]) print(self.input) def main(pymod_args={}): if not pymod_args: import sys parser = arg() args = parser.parse_args(sys.argv[1:]) else: args = PyMod_args(pymod_args) global DEBUG_MODE if args.verbose: DEBUG_MODE = True query_name, query_chain = get_query_name(args.input) data = read_result(args.input) selected_templates = list() if args.m and not args.e: selection = map(lambda x: int(x), args.m) print ('Selected templates {st}.'.format(st = ', '.join(args.m))) for i in selection: tmp_info = str(data[i - 1].template_info.split('>')[1]) print ('{i}: {t}'.format( i = i, t = tmp_info[0:80])) selected_templates.append(data[i - 1]) elif args.e and not args.m: print ('Selected templates satisfying E-val <= {e}'.format(e = args.e)) e_values = { float(j.evalue):i for i, j in enumerate(data) } selection = sorted([ val for key, val in e_values.items() if key <= args.e ]) for i in selection: tmp_info = str(data[i - 1].template_info.split('>')[1]) print ('{i}: {t}'.format( i = i + 1, t = tmp_info[0:80])) selected_templates.append(data[i - 1]) elif args.m and args.e: print ('! Please do not use option -m and -e at the same time ! Exiting.') sys.exit() else: selected_templates = data print ('Creating pir file using all templates ({n})'.format( n = len(selected_templates))) query_grid = create_query_grid(selected_templates) # load query grid print ('query_grid') print(query_grid) gapless_query_grid = create_gapless_grid(query_grid) # remove gaps print ('gapless_query_grid') print(gapless_query_grid) processed_query_grid = process_query_grid(query_grid, gapless_query_grid) # insert gaps ##processed_query_grid = process_query_grid(query_grid, query_grid) # insert gaps print ('processed_query_grid') print (processed_query_grid) glob_seq = derive_global_seq(processed_query_grid, query_name, query_chain) # derive query sequence template_grid = create_template_grid(selected_templates) # create template grid print ('template_grid') print (template_grid) processed_template_grid = process_template_grid(query_grid, template_grid) # insert gaps to template sequnces print ('processed_query_grid') print (processed_query_grid) print ('hzhu processed_template_grid') print (processed_template_grid) # final_grid = compare_with_cifs(processed_template_grid, args.cifs, args.output, args.c, args.r) # compare with atom section of cifs final_grid = processed_template_grid remove_self_alignment(final_grid, query_name) # remove self alignment if any write_to_file([glob_seq, final_grid.display()], args.pir) if __name__ == "__main__": main()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_externals/hhsuite/hh_reader.py
.py
7,178
205
#!/usr/bin/env python """ Parser for hhr result files created with hhblits|hhsearch|hhalign -o <hhr_file> """ import sys from collections import namedtuple __author__ = 'Markus Meier (markus.meier@mpibpc.mpg.de)' __version__ = '1.0' __license__ = "GPL-3" hhr_alignment = namedtuple('hhr_alignment', ['query_id', 'query_length', 'query_neff', 'template_id', 'template_length', 'template_info', 'template_neff', 'query_ali', 'template_ali', 'start', 'end', 'probability', 'evalue', 'score', 'aligned_cols', 'identity', 'similarity', 'sum_probs']) class HHRFormatError(Exception): def __init__(self, value): self.value = "ERROR: "+value def __str__(self): return repr(self.value) def get_sequence_name(header): name = header.replace(">", "").split()[0] return name def parse_result(lines): results = [] query_id = None query_length = None query_neff = None query_seq = [] template_id = None template_length = None template_seq = [] template_info = None query_start = None query_end = None template_start = None template_end = None probability = None evalue = None score = None identity = None similarity = None template_neff = None sum_probs = None aligned_cols = None skipped_ali_tags = ["ss_dssp", "ss_pred", "Consensus"] is_alignment_section = False for line in lines: if(line.startswith("Query")): query_id = line.split()[1] elif(line.startswith("Match_columns")): query_length = int(line.split()[1]) elif(line.startswith("Neff")): query_neff = float(line.split()[1]) elif(is_alignment_section and (line.startswith("No") or line.startswith("Done!"))): if query_start is not None: result = hhr_alignment(query_id, query_length, query_neff, template_id, template_length, template_info, template_neff, query_seq, template_seq, (query_start, template_start), (query_end, template_end), probability, evalue, score, aligned_cols, identity, similarity, sum_probs) results.append(result) template_id = None template_info = None query_seq = [] template_seq = [] query_start = None query_end = None template_start = None template_end = None elif(line.startswith("Probab")): tokens = line.split() probability = float(tokens[0].split("=")[1]) evalue = float(tokens[1].split("=")[1]) score = float(tokens[2].split("=")[1]) aligned_cols = int(tokens[3].split("=")[1]) identity = float(tokens[4].split("=")[1].replace("%", "")) / 100.0 similarity = float(tokens[5].split("=")[1]) sum_probs = float(tokens[6].split("=")[1]) if(len(tokens) > 7): template_neff = float(tokens[7].split("=")[1]) continue elif(line.startswith(">")): is_alignment_section = True template_id = line[1:].split()[0] template_info = line elif(line.startswith("Q")): tokens = line.split() if(tokens[1] in skipped_ali_tags): continue try: token_2 = tokens[2].replace("(", "").replace(")", "") token_2 = int(token_2) except: raise HHRFormatError(("Converting failure of start index ({}) " "of query alignment").format(tokens[2])) if query_start is None: query_start = token_2 query_start = min(query_start, token_2) try: token_4 = tokens[4].replace("(", "").replace(")", "") token_4 = int(token_4) except: raise HHRFormatError(("Converting failure of end index ({}) " "of query alignment").format(tokens[4])) if query_end is None: query_end = token_4 query_end = max(query_end, token_4) query_seq.append(tokens[3]) elif(line.startswith("T")): tokens = line.split() if(tokens[1] in skipped_ali_tags): continue template_seq.append(tokens[3]) try: token_2 = tokens[2].replace("(", "").replace(")", "") token_2 = int(token_2) except: raise HHRFormatError(("Converting failure of start index ({}) " "of template alignment").format(tokens[2])) if template_start is None: template_start = token_2 template_start = min(template_start, token_2) try: token_4 = tokens[4].replace("(", "").replace(")", "") token_4 = int(token_4) except: raise HHRFormatError(("Converting failure of end index ({}) " "of template alignment").format(tokens[4])) if template_end is None: template_end = token_4 template_end = max(template_end, token_4) try: token_5 = tokens[4].replace("(", "").replace(")", "") token_5 = int(token_5) except: raise HHRFormatError(("Converting failure of template length ({}) " "in template alignment").format(tokens[5])) template_length = token_5 if(template_id is not None and query_start is not None): result = hhr_alignment(query_id, query_length, query_neff, template_id, template_length, template_info, template_neff, "".join(query_seq), "".join(template_seq), (query_start, template_start), (query_end, template_end), probability, evalue, score, aligned_cols, identity, similarity, sum_probs) results.append(result) return results def read_result(input_file): with open(input_file) as fh: lines = fh.readlines() return parse_result(lines) def main(): counter = 0 for result in read_result(sys.argv[1]): print("Alignment " + str(counter) + "\t evalue: " + str(result.evalue) + "\t probability: " + str(result.probability)) print(result.query_id + "\t" + str(result.start[0]) + "\t" + result.query_ali + "\t" + str(result.end[0])) print(result.template_id + "\t" + str(result.start[1]) + "\t" + result.template_ali + "\t" + str(result.end[1])) counter += 1 if __name__ == "__main__": main()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_gui/shared_gui_components_qt.py
.py
33,063
1,010
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Common functions and variables used by the Qt GUI of PyMod. """ import os from pymol.Qt import QtWidgets, QtCore, QtGui from pymod_lib.pymod_vars import convert_hex_to_rgb ############################################################################### # Menus. # ############################################################################### def add_qt_menu_command(parent, label, command=None, fg_color=None, bg_color=None): """ Adds to a 'parent' QMenu widget a new menu item. """ # Color the label of the menu item. if fg_color != None: action = QtWidgets.QWidgetAction(parent) label_widget = QtWidgets.QLabel(label) s = """QLabel { background-color: %s; color: %s; padding: 3px; } QLabel:hover { background-color: #466e82; color: %s; }""" % (bg_color, fg_color, fg_color) label_widget.setStyleSheet(s) action.setDefaultWidget(label_widget) # Don't color, use a regular 'QAction' object. else: action = QtWidgets.QAction(label, parent) # Associates a command. if command is not None: action.triggered.connect(command) parent.addAction(action) return action ############################################################################### # Dialogs. # ############################################################################### def askyesno_qt(title, message, parent=None, buttons_text=None): """ Wrapper to a Yes/no dialog in PyQt. If 'buttons_text' is 'None', the default "Yes" and "No" buttons will be used. If 'buttons_text' is a list with two strings, the first string will be the text of the "Yes" button and the second one will be the text of the "No" button. """ # Use yes and no buttons. if buttons_text is None: answer = QtWidgets.QMessageBox.question(parent, title, message, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) return answer == QtWidgets.QMessageBox.Yes # Set custom text on the buttons. else: dialog = QtWidgets.QMessageBox(parent) dialog.setWindowTitle(title) dialog.setText(message) yesbutton = dialog.addButton(buttons_text[0], QtWidgets.QMessageBox.YesRole) nobutton = dialog.addButton(buttons_text[1], QtWidgets.QMessageBox.NoRole) answer = dialog.exec_() return dialog.clickedButton() is yesbutton def askopenfile_qt(title, parent=None, initialdir="", initialfile=None, name_filter=""): """ Wrapper to a show a "pick a file to open" dialog in PyQt. """ askfile_dialog = QtWidgets.QFileDialog() if initialdir and os.path.isdir(initialdir): _initialdir = initialdir else: _initialdir = "" askfile_dialog.setFileMode(QtWidgets.QFileDialog.ExistingFile) filepath = askfile_dialog.getOpenFileName(parent, title, _initialdir, name_filter) if isinstance(filepath, (tuple, list)): filepath = filepath[0] else: filepath = str(filepath) return filepath def askopenfiles_qt(title, parent=None, initialdir="", name_filter=""): """ Wrapper to a show a "pick multiple files to open" dialog in PyQt. """ askfile_dialog = QtWidgets.QFileDialog() if initialdir and os.path.isdir(initialdir): _initialdir = initialdir else: _initialdir = "" askfile_dialog.setFileMode(QtWidgets.QFileDialog.ExistingFile) _filepaths = askfile_dialog.getOpenFileNames(parent, title, _initialdir, name_filter) if isinstance(_filepaths, (tuple, list)): filepaths = _filepaths[0] else: filepaths = _filepaths return filepaths def askdirectory_qt(title, parent=None, initialdir=""): """ Wrapper to a show a "pick a directory" dialog in PyQt. """ askdirectory_dialog = QtWidgets.QFileDialog() if initialdir and os.path.isdir(initialdir): _initialdir = initialdir else: _initialdir = "" flags = QtWidgets.QFileDialog.ShowDirsOnly dirpath = str(askdirectory_dialog.getExistingDirectory(parent, title, _initialdir, flags)) return dirpath def asksaveasfile_qt(title, parent=None, initialdir="", name_filter="", check_existent=True): """ Wrapper to a show a "pick a file to save" dialog in PyQt. """ askfile_dialog = QtWidgets.QFileDialog() if initialdir and os.path.isdir(initialdir): _initialdir = initialdir else: _initialdir = "" _filepath = askfile_dialog.getSaveFileName(parent, title, _initialdir, name_filter) if isinstance(_filepath, (tuple, list)): filepath = _filepath[0] sel_filter = _filepath[1] else: filepath = str(_filepath) sel_filter = "" if not filepath: return filepath if name_filter and check_existent: if sel_filter: extension = sel_filter[1:] else: return filepath # PyQt has already checked for the existance of the file. if filepath.endswith(extension): return filepath # PyQt may not have seen the file with the extension. else: if os.path.isfile(filepath + extension): title = "Save As" message = "File '%s' already exists. Do you want to replace it?" % (filepath + extension) choice = askyesno_qt(title, message, parent=parent) if choice: return filepath + extension else: return "" else: return filepath + extension else: return filepath def open_color_dialog(color_format="all"): """ Opens a Qt color dialog and return a string encoding the selected color. """ if not color_format in ("rgb", "hex", "all"): raise KeyError("Unknown 'color_format': %s" % color_format) color = QtWidgets.QColorDialog.getColor() if color.isValid(): color_hex = color.name() color_rgb = convert_hex_to_rgb(color_hex) if color_format == "rgb": return color_rgb elif color_format == "hex": return color_hex elif color_format == "all": return color_rgb, color_hex return None ############################################################################### # Qt windows used in PyMod. # ############################################################################### class PyMod_tool_window_qt(QtWidgets.QMainWindow): """ Class for various types of windows in PyMod. """ middle_layout_type = "qform" is_pymod_window = True def __init__(self, parent, title="New PyMod Window", upper_frame_title="New PyMod Window Sub-title", submit_command=None, submit_button_text="Submit", with_scroll=True, # geometry=None ): super(PyMod_tool_window_qt, self).__init__(parent) #------------------------ # Configure the window. - #------------------------ # Command executed when pressing on the main button of the window. self.submit_command = submit_command # Configure the window. self.setWindowTitle(title) # if geometry is not None: # self.setGeometry(*geometry) # Sets the central widget. self.central_widget = QtWidgets.QWidget() self.setCentralWidget(self.central_widget) # The window has a main vbox layout. self.main_vbox = QtWidgets.QVBoxLayout() #--------------- # Upper frame. - #--------------- self.upper_frame_title = QtWidgets.QLabel(upper_frame_title) self.main_vbox.addWidget(self.upper_frame_title) #---------------- # Middle frame. - #---------------- # Widget that contains the collection of Vertical Box. self.middle_widget = QtWidgets.QWidget() # The Vertical Box that contains other widgets to be displayed in the window. self.middle_vbox = QtWidgets.QVBoxLayout() self.middle_widget.setLayout(self.middle_vbox) # Scroll area which contains the widgets, set as the centralWidget. self.middle_scroll = QtWidgets.QScrollArea() # Scroll area properties. # self.middle_scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) # self.middle_scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.middle_scroll.setWidgetResizable(True) self.middle_scroll.setWidget(self.middle_widget) # QFormLayout in the middle frame. if self.middle_layout_type == "qform": self.middle_formlayout = PyMod_QFormLayout() self.middle_vbox.addLayout(self.middle_formlayout) elif self.middle_layout_type == "qgrid": self.middle_formlayout = QtWidgets.QGridLayout() self.middle_vbox.addLayout(self.middle_formlayout) else: raise KeyError("Unknown 'middle_layout_type': %s" % middle_layout_type) self.add_middle_frame_widgets() self.main_vbox.addWidget(self.middle_scroll) #---------------- # Bottom frame. - #---------------- self.submit_command = submit_command if self.submit_command is not None: self.main_button = QtWidgets.QPushButton(submit_button_text) self.main_button.clicked.connect(lambda a=None: self.submit_command()) self.main_vbox.addWidget(self.main_button) self.main_button.setFixedWidth(self.main_button.sizeHint().width()) # Sets the main vertical layout. self.central_widget.setLayout(self.main_vbox) self.main_vbox.setAlignment(self.main_button, QtCore.Qt.AlignCenter) def add_middle_frame_widgets(self): """ To be overriden in children classes. Add widgets to the 'middle_vbox' by using: self.middle_vbox.addWidget(widget) """ pass class PyMod_protocol_window_qt(PyMod_tool_window_qt): """ Class for showing a window with options for several PyMod protocols. """ def __init__(self, parent, protocol, *args, **configs): self.protocol = protocol PyMod_tool_window_qt.__init__(self, parent=parent, *args, **configs) self.showing_advanced_widgets = False self.additional_initialization() self.build_protocol_middle_frame() # Methods to be overriden in child classes. def build_protocol_middle_frame(self): pass def additional_initialization(self): pass # Methods for showing widgets for advanced options. def show_advanced_button(self): self.advance_options_button = QtWidgets.QPushButton("Show Advanced Options") self.advance_options_button.clicked.connect(self.toggle_advanced_options) self._advanced_options_label = QtWidgets.QLabel("") self.middle_formlayout.addRow(self.advance_options_button, self._advanced_options_label) def toggle_advanced_options(self): if not self.showing_advanced_widgets: self.showing_advanced_widgets = True self.advance_options_button.setText("Hide Advanced Options") for row in self.middle_formlayout.widgets_to_align: if row.is_advanced_option: row.show_widgets() else: self.showing_advanced_widgets = False self.advance_options_button.setText("Show Advanced Options") for row in self.middle_formlayout.widgets_to_align: if row.is_advanced_option: row.hide_widgets() def check_general_input(self): """ Raises an exception if the input is not valid. """ for row in self.middle_formlayout.widgets_to_align: if row.to_be_validated: if row.is_advanced_option and not self.showing_advanced_widgets: continue if hasattr(row, "validate_input"): row.validate_input() return None def show(self): PyMod_tool_window_qt.show(self) if hasattr(self, "advance_options_button"): self.advance_options_button.setFixedWidth(self.advance_options_button.sizeHint().width()) for row in self.middle_formlayout.widgets_to_align: if row.is_advanced_option: row.hide_widgets() ############################################################################### # Qt widgets used in PyMod. # ############################################################################### default_width_hint = 10 class PyMod_QFormLayout(QtWidgets.QFormLayout): """ A custom 'QFormLayout' for many of PyMod input widgets. """ def __init__(self, vertical_spacing=1, *args, **kwargs): QtWidgets.QFormLayout.__init__(self, *args, **kwargs) # self.setVerticalSpacing(vertical_spacing) self.widgets_to_align = [] def add_widget_to_align(self, widget, advanced_option=False, validate=False, align=True): if align: self.widgets_to_align.append(widget) widget.is_advanced_option = advanced_option widget.to_be_validated = validate self.addRow(widget.label, widget.input) def set_input_widgets_width(self, width, min_width=60, max_width=200, padding=30): if width != "auto": for widget in self.widgets_to_align: widget.set_input_widget_width(width) else: widths = [widget.get_width_hint() for widget in self.widgets_to_align] _max_width = max(widths) if _max_width > max_width: _max_width = max_width if _max_width < min_width: _max_width = min_width for widget in self.widgets_to_align: widget.set_input_widget_width(_max_width+padding) class PyMod_form_item(QtWidgets.QWidget): pass class PyMod_entry_qt(QtWidgets.QLineEdit): def __init__(self, *args, **kwargs): super(PyMod_entry_qt, self).__init__(*args, **kwargs) self.pmw_validator = {} def set_pmw_validator(self, validator): self.pmw_validator = validator if not self.pmw_validator: return None if self.pmw_validator["validator"] == "integer": self.setValidator(QtGui.QIntValidator(self.pmw_validator["min"], self.pmw_validator["max"])) elif self.pmw_validator["validator"] == "real": self.setValidator(QtGui.QDoubleValidator(self.pmw_validator["min"], self.pmw_validator["max"], 9)) else: raise KeyError("Unknown 'validator': %s" % self.pmw_validator["validator"]) def getvalue(self, validate=False, option_name="Option"): # Just return the value from the GUI. if not validate: return self.text() # Returns the value from the GUI, but first validate it. If it can not be # validated, raises an exception. else: # A validator was provided. if self.pmw_validator: # Integers and floats. if self.pmw_validator["validator"] in ("integer", "real"): if self.pmw_validator["validator"] == "integer": try: val = int(self.text()) except ValueError as e: raise ValueError("Invalid input for '%s': could not convert to integer." % option_name) else: try: val = float(self.text()) except ValueError as e: raise ValueError("Invalid input for '%s': could not convert to float." % option_name) if not self.pmw_validator["min"] <= val <= self.pmw_validator["max"]: message = ("Invalid input for '%s'. The value must be in the following" " range: %s to %s." % (option_name, self.pmw_validator["min"], self.pmw_validator["max"])) raise ValueError(message) return val else: raise KeyError("Unknown 'validator': %s" % self.pmw_validator["validator"]) else: return self.text() def setvalue(self, value): self.setText(value) class PyMod_entryfield_qt(PyMod_form_item): """ Class for a entryfield widget in PyQt. Designed to be used in 'QFormLayout' GUIs. """ def __init__(self, label_text="Input", value="", readonly=False, style=None, enter_command=None, validate={}): PyMod_form_item.__init__(self) # Label. self.label = QtWidgets.QLabel(label_text) # Entry. self.entry = PyMod_entry_qt(value) self.enter_command = enter_command if self.enter_command is not None: self.entry.returnPressed.connect(self.enter_command) if readonly: self.entry.setReadOnly(True) if style is not None: self.entry.setStyleSheet(style) else: self.entry.setStyleSheet(active_entry_style) self.validate = validate if self.validate: self.entry.set_pmw_validator(self.validate) self.input = self.entry def setvalue(self, value): self.entry.setvalue(value) def getvalue(self, validate=False): return self.entry.getvalue(validate=validate, option_name=self.label.text()) def set_input_widget_width(self, width): self.entry.setFixedWidth(width) def get_width_hint(self): return default_width_hint # self.entry.sizeHint().width() def show_widgets(self): self.label.show() self.entry.show() def hide_widgets(self): self.label.hide() self.entry.hide() def validate_input(self): return self.getvalue(validate=True) class PyMod_plaintextedit_qt(PyMod_form_item): """ Class for a plain text edit widget in PyQt. Designed to be used in 'QFormLayout' GUIs. """ def __init__(self, label_text="Input", value="", style=None): PyMod_form_item.__init__(self) # Label. self.label = QtWidgets.QLabel(label_text) # Entry. self.entry = QtWidgets.QPlainTextEdit(value) if style is not None: self.entry.setStyleSheet(style) else: self.entry.setStyleSheet(active_entry_style) self.entry.setWordWrapMode(QtGui.QTextOption.WrapAnywhere) expanding_size_policy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) expanding_size_policy.setVerticalStretch(1) self.entry.setSizePolicy(expanding_size_policy) self.input = self.entry def setvalue(self, value): self.entry.setPlainText(value) def getvalue(self, validate=False): return self.entry.toPlainText() def set_input_widget_width(self, width): self.entry.setFixedWidth(width) def get_width_hint(self): return default_width_hint # self.entry.sizeHint().width() def show_widgets(self): self.label.show() self.entry.show() def hide_widgets(self): self.label.hide() self.entry.hide() def validate_input(self): return self.getvalue(validate=True) class PyMod_entryfield_button_qt(PyMod_entryfield_qt): """ Class for a entryfield with a button widget in PyQt. Designed to be used in 'QFormLayout' GUIs. """ def __init__(self, button_text="Submit", button_command=None, *args, **kwargs): PyMod_entryfield_qt.__init__(self, *args, **kwargs) self.input = QtWidgets.QHBoxLayout() self.input.addWidget(self.entry) # Adds a button. self.button = QtWidgets.QPushButton(button_text) self.input.addWidget(self.button) self.button.setFixedWidth(self.button.sizeHint().width()) self.button_command = button_command if self.button_command is not None: self.button.clicked.connect(self.button_command) def show_widgets(self): PyMod_entryfield_qt.show_widgets(self) self.button.show() def hide_widgets(self): PyMod_entryfield_qt.hide_widgets(self) self.button.hide() class PyMod_radioselect_qt(PyMod_form_item): """ Class for a radioselect widget in PyQt. Designed to be used in 'QFormLayout' GUIs. """ def __init__(self, label_text="Input", buttons=[]): PyMod_form_item.__init__(self) # Label. self.label = QtWidgets.QLabel(label_text) # Buttons. self.input = QtWidgets.QVBoxLayout() if not buttons: raise ValueError("Please provide a list of button names") if len(buttons) != len(set(buttons)): raise ValueError("Please provide a non redundant list of buttons") self.button_group = QtWidgets.QButtonGroup() self.buttons_names = [] self.buttons_dict = {} for button_name in buttons: button = QtWidgets.QPushButton(button_name) button.setCheckable(True) self.input.addWidget(button) self.buttons_names.append(button_name) self.buttons_dict[button_name] = button self.button_group.addButton(button) def get_buttons(self): return self.button_group.buttons() def get_button_at(self, index): buttons = [b for b in self.get_buttons()] return buttons[index] def setvalue(self, value): self.buttons_dict[value].setChecked(True) def getvalue(self): checked_button = self.button_group.checkedButton() if checked_button is None: return None else: return checked_button.text() def set_input_widget_width(self, width): for button in self.button_group.buttons(): button.setFixedWidth(width) def get_width_hint(self): return max([button.sizeHint().width() for button in self.button_group.buttons()]) def show_widgets(self): self.label.show() for button in self.button_group.buttons(): button.show() def hide_widgets(self): self.label.hide() for button in self.button_group.buttons(): button.hide() class PyMod_combobox_qt(PyMod_form_item): """ Class for a combobox widget in PyQt. Designed to be used in 'QFormLayout' GUIs. """ def __init__(self, label_text="Input", items=[]): PyMod_form_item.__init__(self) # Label. self.label = QtWidgets.QLabel(label_text) # Combobox. self.combobox = QtWidgets.QComboBox() if not items: raise ValueError("Please provide a list of items for the combobox") self.items = items for item in self.items: self.combobox.addItem(item) self.combobox.setEditable(False) self.input = self.combobox def get(self): return self.combobox.currentText() def get_index(self): return self.combobox.currentIndex() def set_input_widget_width(self, width): self.combobox.setFixedWidth(width) def get_width_hint(self): return self.combobox.sizeHint().width() def show_widgets(self): self.label.show() self.combobox.show() def hide_widgets(self): self.label.hide() self.combobox.hide() class PyMod_entrylabel_qt(PyMod_form_item): """ Class for a label widget in PyQt. Designed to be used in 'QFormLayout' GUIs. """ def __init__(self, label_text="Input", value=""): PyMod_form_item.__init__(self) # Label. self.label = QtWidgets.QLabel(label_text) # Second Entry. self.right_label = QtWidgets.QLabel(value) self.right_label.setWordWrap(True) self.input = self.right_label def set_input_widget_width(self, width): self.right_label.setFixedWidth(width) def get_width_hint(self): return self.right_label.sizeHint().width() def show_widgets(self): self.label.show() self.right_label.show() def hide_widgets(self): self.label.hide() self.right_label.hide() class PyMod_hbox_option_qt(PyMod_form_item): """ Class for a combobox widget in PyQt. Designed to be used in 'QFormLayout' GUIs. """ def __init__(self, label_text="Input"): PyMod_form_item.__init__(self) # Label. self.label = QtWidgets.QLabel(label_text) # Hbox. self.hbox = QtWidgets.QHBoxLayout() self.input = self.hbox def set_auto_input_widget_width(self): for idx in range(0, self.hbox.count()): widget = self.hbox.itemAt(idx).widget() if hasattr(widget, "setFixedWidth"): widget.setFixedWidth(widget.sizeHint().width()) def set_input_widget_width(self, width): pass def get_width_hint(self): return default_width_hint def show_widgets(self): self.label.show() for idx in range(0, self.hbox.count()): widget = self.hbox.itemAt(idx).widget() if hasattr(widget, "show"): widget.show() def hide_widgets(self): self.label.hide() for idx in range(0, self.hbox.count()): widget = self.hbox.itemAt(idx).widget() if hasattr(widget, "hide"): widget.hide() class PyMod_spinbox_entry_qt(PyMod_form_item): """ Class for a entryfield widget in PyQt. Designed to be used in 'QFormLayout' GUIs. """ def __init__(self, label_text="Input", value=1, spinbox_min=1, spinbox_max=100): PyMod_form_item.__init__(self) # Label. self.label = QtWidgets.QLabel(label_text) # Spinbox. self.spinbox = QtWidgets.QSpinBox() self.spinbox_min = spinbox_min self.spinbox_max = spinbox_max self.spinbox.setRange(self.spinbox_min, self.spinbox_max) self.spinbox.setStyleSheet(active_entry_style) self.input = self.spinbox def setvalue(self, value): self.spinbox.setValue(value) def getvalue(self, validate=False): # Just return the value from the GUI. if not validate: return self.spinbox.value() # Returns the value from the GUI, but first validate it. If it can not be # validated, raises an exception. else: option_name = self.label.text() try: val = int(self.spinbox.value()) except ValueError as e: raise ValueError("Invalid input for '%s': could not convert to integer." % option_name) if not self.spinbox_min <= val <= self.spinbox_max: message = ("Invalid input for '%s'. The value must be in the following" " range: %s to %s." % (option_name, self.spinbox_min, self.spinbox_max)) raise ValueError(message) return val def set_input_widget_width(self, width): self.spinbox.setFixedWidth(width) def get_width_hint(self): return self.spinbox.sizeHint().width() def show_widgets(self): self.label.show() self.spinbox.show() def hide_widgets(self): self.label.hide() self.spinbox.hide() def validate_input(self): return self.getvalue(validate=True) class PyMod_scalebar_qt(PyMod_form_item): """ Class for a scalerbar widget in PyQt. Designed to be used in 'QFormLayout' GUIs. """ def __init__(self, label_text="New scalebar", slider_value=1, slider_from=1, slider_to=10, slider_resoution=1, # slider_digits=3, slider_tickinterval=1, slider_use_float=False, slider_use_float_val=100.0, slider_binding=None, slider_width=None): PyMod_form_item.__init__(self) # Label. self.label = QtWidgets.QLabel(label_text) # Layout for the input widget and its label. self.input = QtWidgets.QHBoxLayout() # Adds a slider. self.slider = QtWidgets.QSlider() self.slider.setOrientation(QtCore.Qt.Horizontal) self.slider.setTickPosition(QtWidgets.QSlider.TicksBelow) self.slider_use_float = slider_use_float self.slider_use_float_val = slider_use_float_val self.slider.slider_resoution = slider_resoution self.slider.setMinimum(round(self._get_slider_val(slider_from, internal=True))) self.slider.setMaximum(round(self._get_slider_val(slider_to, internal=True))) self.slider.setValue(round(self._get_slider_val(slider_value, internal=True))) self.slider.setTickInterval(round(self._get_slider_val(slider_tickinterval, internal=True))) self.slider.setSingleStep(round(self._get_slider_val(slider_resoution, internal=True))) self.slider.setPageStep(round(self._get_slider_val(slider_tickinterval, internal=True))) self.slider.valueChanged.connect(self._on_slider_change) self.slider.sliderPressed.connect(self._on_slider_pressed) self.slider.sliderReleased.connect(self._on_slider_release) self.on_drag = False self.input.addWidget(self.slider) # Add a label on the right of the slider. self.slider_label = QtWidgets.QLabel(str(slider_to)) self.input.addWidget(self.slider_label) if slider_width: self.slider.setFixedWidth(slider_width) self.slider_label.setFixedWidth(self.slider_label.sizeHint().width()) self.slider_label.setText(str(slider_value)) self.slider_binding = slider_binding def show_widgets(self): self.label.show() self.slider.show() self.slider_label.show() def hide_widgets(self): self.label.hide() self.slider.hide() self.slider_label.hide() def _on_slider_change(self): val = self._get_slider_val(self.slider.value(), internal=False) self.slider_label.setText(str(val)) if not self.on_drag: self.call_slider_biding() def _on_slider_pressed(self): self.on_drag = True def _on_slider_release(self): self.call_slider_biding() self.on_drag = False def call_slider_biding(self): if self.slider_binding is not None: self.slider_binding() def _get_slider_val(self, val, internal=True): if not self.slider_use_float: return val else: if internal: return val*self.slider_use_float_val else: return val/self.slider_use_float_val def getvalue(self): return self._get_slider_val(self.slider.value(), internal=False) def get(self): return self.getvalue() def set_input_widget_width(self, width): pass def set_auto_input_widget_width(self, width): pass def get_width_hint(self): return self.slider.sizeHint().width() + self.slider_label.sizeHint().width() ############################################################################### # CSS Styles used in PyMod. # ############################################################################### default_pt_size = QtGui.QFont().pointSize() active_entry_style = "background-color: white; color: #333333" inactive_entry_style = "background-color: #ccc; color: #7c7c7c" inactive_bg_color = "#e3e3e3" success_bg_color = "#98fb98" failure_bg_color = "#f08080" highlight_color = "#5ac8ff" options_title_style = "font-size: %spt; color: %s" % (default_pt_size+1, highlight_color) small_font_style = "font-size: %spt" % (default_pt_size-1) large_font_style = "font-size: %spt" % (default_pt_size+1)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_gui/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_gui/pymod_table.py
.py
4,840
133
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. import csv import warnings from pymol.Qt import QtCore, QtWidgets, QtGui from pymod_lib.pymod_gui.shared_gui_components_qt import asksaveasfile_qt class TableView(QtWidgets.QTableWidget): """ Custom class derived from 'QTableWidget'. See: https://doc.qt.io/qt-5/qtableview.html. """ def __init__(self, data, parent, sortable=False, column_labels=None, row_labels=None, row_labels_height=25, *args): self.data = data self.column_labels = column_labels self.row_labels = row_labels self.row_labels_height = row_labels_height # Get a set with the length of each column. rows_number = len(self.data) columns_number = len(self.data[0]) QtWidgets.QTableWidget.__init__(self, parent=parent, columnCount=columns_number, rowCount=rows_number, sortingEnabled=sortable, *args) self.set_data() self.resizeColumnsToContents() # self.resizeRowsToContents() self.setStyleSheet("QTableView::item {border: 0px; padding: 0px; margin: 0px;}") # self.itemDoubleClicked.connect(self.on_click) default_font = QtGui.QFont() default_font.setPointSize(default_font.pointSize()-1) self.setFont(default_font) def set_data(self): verticalHeader = self.verticalHeader() verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.Fixed) verticalHeader.setDefaultSectionSize(self.row_labels_height) for i, row in enumerate(self.data): for j, value in enumerate(row): # Gets the value to show in the cell. if value is not None: # Attempts to convert the value in a float. try: _value = float(value) except ValueError: _value = value else: _value = "-" with warnings.catch_warnings(): warnings.simplefilter("ignore") newitem = QtWidgets.QTableWidgetItem(str(_value)) newitem.setData(QtCore.Qt.DisplayRole, _value) newitem.setFlags(QtCore.Qt.ItemIsEnabled) newitem.setTextAlignment(QtCore.Qt.AlignCenter) self.setItem(i, j, newitem) self.setHorizontalHeaderLabels(self.column_labels) if self.row_labels != None: self.setVerticalHeaderLabels(self.row_labels) def on_click(self): pass class QtTableWindow(QtWidgets.QMainWindow): """ Window containing the 'TableView' widget. """ is_pymod_window = True def __init__(self, parent, title, data, sortable=False, column_labels=None, row_labels=None, row_labels_height=25, width=800, height=400): super(QtTableWindow, self).__init__(parent) self.setWindowTitle(title) self.setGeometry(50, 50, width, height) self.table = TableView(data=data, parent=None, sortable=sortable, column_labels=column_labels, row_labels=row_labels, row_labels_height=row_labels_height) self.setCentralWidget(self.table) self.table.show() save_to_action = QtWidgets.QAction('Save to File', self) save_to_action.triggered.connect(lambda a=None: self.save_to_event()) menubar = self.menuBar() file_menu = menubar.addMenu('File') file_menu.addAction(save_to_action) def save_to_event(self): """ Saves the table data to a .csv file. """ # Let the user select the filepath. filepath = asksaveasfile_qt("Save CSV file", name_filter="*.csv") if not filepath: return None try: # Writes a .csv file on that path. with open(filepath, 'w') as csv_fh: writer = csv.writer(csv_fh, delimiter=',', quoting=csv.QUOTE_MINIMAL) if self.table.row_labels is not None: writer.writerow([" "] + self.table.column_labels) else: writer.writerow(self.table.column_labels) for row_idx, row in enumerate(self.table.data): if self.table.row_labels is not None: writer.writerow([self.table.row_labels[row_idx]] + [str(v) for v in row]) else: writer.writerow([str(v) for v in row]) except Exception as e: print("- WARNING: could not write a csv file: %s" % str(e))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_gui/specific_gui_components_qt.py
.py
21,533
559
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Classes for PyQt widgets used in specific parts of the PyMod GUI. """ import os from pymol.Qt import QtWidgets, QtCore from pymod_lib.pymod_seq.seq_manipulation import clean_white_spaces_from_input from pymod_lib.pymod_gui.shared_gui_components_qt import open_color_dialog from pymod_lib.pymod_gui.shared_gui_components_qt import (PyMod_tool_window_qt, PyMod_entryfield_qt, PyMod_entryfield_button_qt, PyMod_radioselect_qt, PyMod_plaintextedit_qt) from pymod_lib.pymod_gui.shared_gui_components_qt import (options_title_style, small_font_style, active_entry_style, inactive_entry_style, inactive_bg_color, success_bg_color, failure_bg_color, askyesno_qt, askopenfile_qt, askdirectory_qt) ##################################################################### # PyMod options window. # ##################################################################### class PyMod_options_window_qt(PyMod_tool_window_qt): """ Window showing a series of options for PyMod. """ middle_layout_type = "qgrid" def __init__(self, parent, pymod, *args, **configs): self.pymod = pymod PyMod_tool_window_qt.__init__(self, parent, *args, **configs) def add_middle_frame_widgets(self): self.tools_params_dict = {} self.row_counter = 0 # This list will be populated inside "build_tool_options_frame()". for single_tool in self.pymod.pymod_tools: # If the tool list of parameter widgets has some alignable widgets, adds them to the # option window list. self.display_options(single_tool) # self.middle_formlayout.set_input_widgets_width(200) return None def display_options(self, single_tool): """ Displays at list of option in the the target_frame contained in a target widget. Used in the PyMod options window. """ # Check that at least one parameter if not any([p.show_widget for p in single_tool.parameters]): return None self.tools_params_dict[single_tool.name] = {} # Grids a label with the name of the tool. tool_full_name_label = QtWidgets.QLabel(single_tool.full_name) tool_full_name_label.setStyleSheet(options_title_style) # print(dir(tool_full_name_label)) # print(tool_full_name_label.font().size()) self.middle_formlayout.addWidget(tool_full_name_label, self.row_counter, 0) self.row_counter += 1 # Actually grids the parmater widgets. for parameter in single_tool.parameters: if not parameter.show_widget: continue # If the display options return a widget, adds it ot the Tool list of parameter widgets. w = self.display_paramenter_options(parameter) self.row_counter += 1 def display_paramenter_options(self, parameter): """ Used to display a series of widgets to choose the parameter value in PyMod options window. This is conditioned on the type of input widget of the 'parameter'. """ # Label with the name of the parameter. param_full_name_label = QtWidgets.QLabel(parameter.full_name) self.middle_formlayout.addWidget(param_full_name_label, self.row_counter, 0) # Do not display any input widget. if parameter.widget_type is None: pass # Display any a text entry input. elif parameter.widget_type == "path_entryfield": # Entry for the path. path_entryfield = QtWidgets.QLineEdit(str(parameter.get_starting_value())) if parameter.editable: path_entryfield.setStyleSheet(active_entry_style + "; " + small_font_style) else: path_entryfield.setStyleSheet(inactive_entry_style + "; " + small_font_style) path_entryfield.setEnabled(False) self.middle_formlayout.addWidget(path_entryfield, self.row_counter, 1) self.tools_params_dict[parameter.parent_tool.name][parameter.name] = path_entryfield # Button for browsing the path. if parameter.editable: path_browse_button = QtWidgets.QPushButton("Browse") path_browse_button.setStyleSheet(small_font_style) if parameter.path_type in ("file", "directory"): path_browse_button.clicked.connect(lambda a=None, p=parameter: self.choose_path(p)) else: raise KeyError("Unknown 'path_type': %s" % str(parameter.path_type)) self.middle_formlayout.addWidget(path_browse_button, self.row_counter, 2) # Button to automatically identifying the path. if parameter.auto_find: auto_find_button = QtWidgets.QPushButton("Auto Find") auto_find_button.setStyleSheet(small_font_style) self.middle_formlayout.addWidget(auto_find_button, self.row_counter, 3) auto_find_button.clicked.connect(lambda a=None, e=path_entryfield: parameter.auto_find_command(e)) # Show the status of a parameter. elif parameter.widget_type == "show_status": text_to_show, status = parameter.get_status() status_entryfield = QtWidgets.QLineEdit(text_to_show) if status: status_entryfield.setStyleSheet("background-color: %s" % success_bg_color) else: status_entryfield.setStyleSheet("background-color: %s" % failure_bg_color) status_entryfield.setEnabled(False) status_entryfield.setFixedWidth(200) self.middle_formlayout.addWidget(status_entryfield, self.row_counter, 1) else: raise KeyError("Unkown 'widget_type': %s" % parameter.widget_type) def choose_path(self, parameter): """ Called when users press the 'Browse' button in order to choose a path on their system. """ new_path = None entry = self.tools_params_dict[parameter.parent_tool.name][parameter.name] current_path = entry.text() askpath_title = "Search for %s %s" % (parameter.parent_tool.full_name, parameter.full_name) # Let users choose a new path. if parameter.path_type == "file": new_path = askopenfile_qt(askpath_title, parent=self.pymod.get_qt_parent(), initialdir=os.path.dirname(current_path), initialfile=os.path.basename(current_path)) elif parameter.path_type == "directory": new_path = askdirectory_qt(askpath_title, parent=self.pymod.get_qt_parent(), initialdir=current_path) # Updates the text in the Entry with the new path name. if new_path: entry.clear() entry.setText(new_path) def get_value_from_gui(self, parameter_obj): """ Gets the value from the input widgets in the PyMod options window. This should be conditioned on the type class of the 'Tool_parameter' in order to be able to retrieve different types of input from the GUI. """ return self.tools_params_dict[parameter_obj.parent_tool.name][parameter_obj.name].text() ##################################################################### # Window for new sequences. # ##################################################################### class Raw_sequence_window_qt(PyMod_tool_window_qt): """ Window with two text entries to add the sequence elements to PyMod. The two entries are one for the name and one for the sequence of the element. """ build_name_entry = True build_sequence_entry = True def add_middle_frame_widgets(self): entry_style = "background-color: white; color: black; font-family: courier" # Creates an Entry for the name of the new sequence. if self.build_name_entry: self.seq_name_input = PyMod_entryfield_qt(label_text="Name:", value="", style=entry_style) self.middle_formlayout.add_widget_to_align(self.seq_name_input) # Creates an Entry widget for the sequence. if self.build_sequence_entry: self.seq_sequence_input = PyMod_plaintextedit_qt(label_text="Sequence:", value="", style=entry_style) self.middle_formlayout.add_widget_to_align(self.seq_sequence_input) def get_sequence(self): return clean_white_spaces_from_input(self.seq_sequence_input.getvalue()).upper() def get_sequence_name(self): return self.seq_name_input.getvalue() class Edit_sequence_window_qt(Raw_sequence_window_qt): """ Window editing the sequence of an element already loaded in PyMod. Does not allow to edit its name. """ build_name_entry = False build_sequence_entry = True def __init__(self, parent, pymod_element, *args, **configs): Raw_sequence_window_qt.__init__(self, parent, *args, **configs) self.pymod_element = pymod_element self.seq_sequence_input.setvalue(self.pymod_element.my_sequence) class Import_from_pymol_window_qt(PyMod_tool_window_qt): """ Window showing a series of checkboxes to import PyMOL objects in PyMod. """ def __init__(self, parent, selections_list, *args, **configs): self.selections_list = selections_list PyMod_tool_window_qt.__init__(self, parent, *args, **configs) # Builds a combobox for each PyMOL object to import. self.sele_checkbox_list = [] for sele in selections_list: checkbox = QtWidgets.QCheckBox(sele) self.sele_checkbox_list.append(checkbox) self.middle_formlayout.addRow(checkbox) def get_objects_to_import(self): sele_list = [] for sele, checkbox in zip(self.selections_list, self.sele_checkbox_list): if checkbox.isChecked(): sele_list.append(sele) return sele_list ############################################### # Window for selecting the "PyMod directory". # ############################################### class Dir_selection_dialog_mixin: """ Mixin class to be incorporated in all the directory selection dialogs. """ def keyPressEvent(self, event): """ By overriding this method, the dialog will not close when pressing the "esc" key. """ if event.key() == QtCore.Qt.Key_Escape: pass else: QtWidgets.QDialog.keyPressEvent(self, event) def closeEvent(self, evnt): if evnt.spontaneous(): title = "Exit PyMod?" message = "Are you really sure you want to exit PyMod?" answer = askyesno_qt(title, message, parent=self.pymod.get_qt_parent()) if answer: self.close() # Closes the dialog. self.main_window.close() # Close the main window if the user exits the dialog. else: evnt.ignore() class PyMod_dir_selection_dialog(Dir_selection_dialog_mixin, QtWidgets.QDialog): """ Dialog to select the PyMod Directory. This is shown when launching PyMod for the first time. """ is_pymod_window = True def __init__(self, app, pymod, confirm_close=True): QtWidgets.QDialog.__init__(self, parent=app) self.main_window = app self.pymod = pymod self.confirm_close = confirm_close self.initUI() def initUI(self): self.setWindowTitle('PyMod Directory Selection') self.vertical_layout = QtWidgets.QVBoxLayout() # Main label. self.label = QtWidgets.QLabel("Select a folder inside which to build the 'PyMod Directory'", self) self.vertical_layout.addWidget(self.label) # Entry and "Browse" button. self.horizontal_layout = QtWidgets.QHBoxLayout() self.main_entry = QtWidgets.QLineEdit(self.pymod.home_directory, self) self.main_entry.setStyleSheet("background-color: white; color: black") self.horizontal_layout.addWidget(self.main_entry) self.browse_button = QtWidgets.QPushButton("BROWSE", self) self.browse_button.clicked.connect(self.pymod_directory_browse_state) self.horizontal_layout.addWidget(self.browse_button) self.vertical_layout.addLayout(self.horizontal_layout) # "Submit" button. self.submit_button = QtWidgets.QPushButton("SUBMIT", self) self.submit_button.setFixedWidth(self.submit_button.sizeHint().width()) self.submit_button.clicked.connect(self.on_submit_button_press) self.vertical_layout.addWidget(self.submit_button) self.vertical_layout.setAlignment(self.submit_button, QtCore.Qt.AlignCenter) # Set the layouts. self.setLayout(self.vertical_layout) def on_submit_button_press(self): self.pymod.pymod_directory_selection_state() def pymod_directory_browse_state(self): """ Let users choose a new path. """ new_path = askdirectory_qt(title="Select a folder in which to build the 'PyMod Directory'", initialdir=str(self.main_entry.text()), parent=self.pymod.get_qt_parent()) if new_path: # Updates the text in the Entry with the new path. self.main_entry.setText(new_path) ############################################## # Window for starting a new "PyMod session". # ############################################## # TODO. ############################################## # Window for adding a feature to a sequence. # ############################################## class Add_feature_window_qt(PyMod_tool_window_qt): def __init__(self, parent, pymod_element, selected_residue, *args, **configs): self.pymod_element = pymod_element self.selected_residue = selected_residue PyMod_tool_window_qt.__init__(self, parent, *args, **configs) def add_middle_frame_widgets(self): # Entryfield for selecting the residues range. self.residue_range_enf = PyMod_entryfield_qt(label_text="Residue(s)", value=str(self.selected_residue.db_index)) self.middle_formlayout.add_widget_to_align(self.residue_range_enf) # Entryfield for the feature name. self.feature_name_enf = PyMod_entryfield_qt(label_text="Feature Name", value="new feature") self.middle_formlayout.add_widget_to_align(self.feature_name_enf) # Widgets for choosing a color for the feature. self.selected_rgb = (1.0, 0.0, 0.0) self.selected_hex = '#ff0000' self.feature_color_enf = PyMod_entryfield_button_qt(label_text="Feature Color", readonly=True, button_text="Pick", button_command=self.pick_color_dialog) self.middle_formlayout.add_widget_to_align(self.feature_color_enf) self.feature_color_enf.entry.setStyleSheet("background-color: %s" % self.selected_hex) # Select in PyMOL. if self.pymod_element.has_structure(): self.select_in_pymol_rds = PyMod_radioselect_qt(label_text="Select in PyMOL", buttons=("Yes", "No")) self.select_in_pymol_rds.setvalue("No") self.middle_formlayout.add_widget_to_align(self.select_in_pymol_rds) self.middle_formlayout.set_input_widgets_width(150) def get_residue_range(self): return self.residue_range_enf.getvalue() def get_feature_name(self): return self.feature_name_enf.getvalue() def pick_color_dialog(self): selected_color = open_color_dialog(color_format="all") if selected_color is not None: self.selected_rgb, self.selected_hex = selected_color # self.feature_color_enf.setvalue(self.selected_hex) self.feature_color_enf.entry.setStyleSheet("background-color: %s" % self.selected_hex) def get_selected_colors(self): return self.selected_rgb, self.selected_hex def get_select_in_pymol(self): return _get_select_in_pymol(self) def _get_select_in_pymol(window): if window.pymod_element.has_structure(): choice_value = window.select_in_pymol_rds.getvalue() if choice_value == "Yes": return True elif choice_value == "No": return False else: raise KeyError(choice_value) else: return False ################################################################ # Window for searching a string in a sequence loaded in PyMod. # ################################################################ class Search_string_window_qt(PyMod_tool_window_qt): inactive_results_color = inactive_bg_color found_results_color = success_bg_color not_found_results_color = failure_bg_color default_message = "Type a pattern and press Enter..." def __init__(self, parent, pymod_elements, *args, **configs): self.pymod_element = pymod_elements[0] PyMod_tool_window_qt.__init__(self, parent, *args, **configs) def add_middle_frame_widgets(self): #------------------------------------- # Form layout for input and results. - #------------------------------------- entries_width = 340 # Entryfield for inserting a subsequence. self.search_string_enf = PyMod_entryfield_qt(label_text="Search For", value="", enter_command=self.submit_command) self.search_string_enf.set_input_widget_width(entries_width) self.middle_formlayout.add_widget_to_align(self.search_string_enf, align=False) # Entryfield for showing the results. self.results_enf = PyMod_entryfield_qt(label_text="", value=self.default_message, readonly=True) self.set_results_entry_bg(self.inactive_results_color) self.results_enf.set_input_widget_width(entries_width) self.middle_formlayout.add_widget_to_align(self.results_enf, align=False) #--------------------------- # Form layout for options. - #--------------------------- # Use regular expressions. self.use_regex_rds = PyMod_radioselect_qt(label_text="Use Regex", buttons=("Yes", "No")) self.use_regex_rds.setvalue("No") self.middle_formlayout.add_widget_to_align(self.use_regex_rds) # Highlight color selection. color_buttons = ("yellow", "red", "green", "cyan") # "violet" self.highlight_color_rds = PyMod_radioselect_qt(label_text='Highlight Color', buttons=color_buttons) self.highlight_color_rds.setvalue('yellow') self.middle_formlayout.add_widget_to_align(self.highlight_color_rds) if self.pymod_element.has_structure(): self.select_in_pymol_rds = PyMod_radioselect_qt(label_text='Select in PyMOL', buttons=("Yes", "No")) self.select_in_pymol_rds.setvalue('No') self.middle_formlayout.add_widget_to_align(self.select_in_pymol_rds) self.middle_formlayout.set_input_widgets_width(width="auto") def get_search_string(self): return self.search_string_enf.getvalue() def get_regex_use(self): use_regex_val = self.use_regex_rds.getvalue() if use_regex_val == "Yes": return True elif use_regex_val == "No": return False else: raise KeyError(use_regex_val) def get_highlight_color(self): return self.highlight_color_rds.getvalue() def show_results(self, message, state): self.results_enf.setvalue(message) if state == "found": self.set_results_entry_bg(self.found_results_color) elif state == "not_found": self.set_results_entry_bg(self.not_found_results_color) elif state == "empty": self.set_results_entry_bg(self.inactive_results_color) else: raise KeyError(state) def set_results_entry_bg(self, color): self.results_enf.input.setStyleSheet("background-color: %s; color: black" % color) def get_select_in_pymol(self): return _get_select_in_pymol(self)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_gui/main_window/_header_entry_qt.py
.py
39,691
781
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module implementing the widgets showed in the left pane of PyMod main window. """ from pymol.Qt import QtWidgets, QtCore, QtGui from pymod_lib.pymod_gui.shared_gui_components_qt import add_qt_menu_command, open_color_dialog from pymod_lib.pymod_seq.seq_manipulation import remove_gap_only_columns import pymod_lib.pymod_vars as pmdt from pymol import cmd ################################################################################################### # Widget for the header label of an element. # ################################################################################################### class MyQLabel_header(QtWidgets.QLabel): """ A custom QLabel for headers of PyMod elements. """ def __init__(self, parent_group): QtWidgets.QLabel.__init__(self, parent_group.pymod_element.my_header) self.parent_group = parent_group self.resize_to_content() # Set the style. self.setStyleSheet("color: red") self.set_default_cursor() def get_main_window(self): return self.parent_group.main_window # def get_pymod_element(self): # return self.parent_group.pymod_element def set_default_cursor(self): # self.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) def resize_to_content(self): self.pixelsWide = self.get_main_window().fm.width(self.text()) self.pixelsHigh = self.get_main_window().fm.height() def update_title(self): self.setText(self.parent_group.pymod_element.my_header) ############################################################################################### # Bindings for mouse events. # ############################################################################################### def mousePressEvent(self, event): """ Left click on an element header. """ # self.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor)) if event.buttons() == QtCore.Qt.LeftButton: self.parent_group.toggle_element() elif event.buttons() == QtCore.Qt.MiddleButton: self.click_structure_with_middle_button() def mouseMoveEvent(self, event): """ Select/Unselect sequences hovering on their headers while the mouse left button is pressed. """ # Only activates when the left button is being pressed. if event.buttons() == QtCore.Qt.LeftButton: highlighted_widget = QtWidgets.QApplication.widgetAt(self.mapToGlobal(event.pos())) # Checks if the widget hovered with the mouse belongs to the 'Header_entry' class and is not # the entry originally clicked. if isinstance(highlighted_widget, MyQLabel_header) and highlighted_widget != self: starting_element_state = self.parent_group.pymod_element.selected if starting_element_state and not highlighted_widget.parent_group.pymod_element.selected: highlighted_widget.parent_group.toggle_element() elif not starting_element_state and highlighted_widget.parent_group.pymod_element.selected: highlighted_widget.parent_group.toggle_element() def enterEvent(self, event): """ Show information on the message bar of the main window. """ self.parent_group.main_window.central_widget.textbox_sequence.setText(str(self.parent_group.pymod_element.my_header)) def leaveEvent(self, event): """ Called when the mouse leaves a header label. """ self.parent_group.main_window.central_widget.textbox_sequence.setText("") def contextMenuEvent(self, event): """ Shows the context menu when right clickings on the header of an element. """ self.build_header_popup_menu() self.context_menu.exec_(self.mapToGlobal(event.pos())) ############################################################################################### # Context menu for the header entry. # ############################################################################################### def build_header_popup_menu(self): """ Builds the popup menu that appears when users left-clicks with on the sequence header in the main window left pan. """ self.context_menu = Header_context_menu(self) # Places the single sequence submenus in a separate submenu in order to distinguish it # from the selection submenu. if len(self.parent_group.pymod.get_selected_sequences()) > 1: self.single_sequence_context_submenu = QtWidgets.QMenu(self.parent_group.pymod_element.my_header, self.context_menu) self.context_menu.addMenu(self.single_sequence_context_submenu) self.single_element_target_submenu = self.single_sequence_context_submenu # Places the single sequence submenus in the main context menu. else: add_qt_menu_command(self.context_menu, self.parent_group.pymod_element.my_header, None) self.single_element_target_submenu = self.context_menu self.context_menu.addSeparator() # Builds a popup menu for sequence elements. if not self.parent_group.pymod_element.is_cluster(): self.build_single_sequence_header_popup_menu() # For cluster elements (alignments or blast-search elements). else: self.build_cluster_popup_menu(self.single_element_target_submenu, mode="cluster", extra_spacer=True) self.update_left_popup_menu() def update_left_popup_menu(self): """ Activates the "Selection" item when at least two elements are selected. In order to make this work the "Selection" item always has to be in the last position in all kind of menus. """ if len(self.parent_group.pymod.get_selected_sequences()) > 1: # self.header_popup_menu.entryconfig(self.header_popup_menu.index(END), state=NORMAL) self.build_selection_menu() elif not self.parent_group.pymod_element.is_cluster(): # self.header_popup_menu.entryconfig(self.header_popup_menu.index(END), state=DISABLED) pass def build_single_sequence_header_popup_menu(self): # Build the "Sequence" menu. self.build_sequence_menu() self.single_element_target_submenu.addSeparator() # Build the "Color" menu. self.build_color_menu() self.single_element_target_submenu.addSeparator() # Build the "Structure" menu. self.build_structure_menu() self.single_element_target_submenu.addSeparator() # Build the "Domains" menu. if self.parent_group.pymod_element.has_domains(only_original=True): self.build_domains_menu() self.single_element_target_submenu.addSeparator() # Build the "Features" menu. if self.parent_group.pymod_element.has_features(): self.builds_features_menu() self.single_element_target_submenu.addSeparator() # Build the "Cluster Options" menu. if self.parent_group.pymod_element.is_child(): self.build_cluster_options_menu() self.single_element_target_submenu.addSeparator() def build_sequence_menu(self): """ Submenu with options for manipulating a sequence loaded in PyMod. """ self.sequence_context_submenu = QtWidgets.QMenu('Sequence', self.single_element_target_submenu) self.single_element_target_submenu.addMenu(self.sequence_context_submenu) add_qt_menu_command(self.sequence_context_submenu, "Save Sequence to File", self.save_sequence_from_left_pane) add_qt_menu_command(self.sequence_context_submenu, "Copy Sequence to Clipboard", self.copy_sequence_to_clipboard) self.sequence_context_submenu.addSeparator() add_qt_menu_command(self.sequence_context_submenu, "Edit Sequence", self.edit_sequence_from_context) add_qt_menu_command(self.sequence_context_submenu, "Search Sub-sequence", self.search_string_from_context) self.sequence_context_submenu.addSeparator() add_qt_menu_command(self.sequence_context_submenu, "Duplicate Sequence", self.duplicate_sequence_from_the_left_pane) add_qt_menu_command(self.sequence_context_submenu, "Delete Sequence", self.delete_sequence_from_the_left_pane) def build_color_menu(self): """ Color submenu containing all the option to color for a single sequence. """ self.color_context_submenu = QtWidgets.QMenu('Color', self.single_element_target_submenu) self.single_element_target_submenu.addMenu(self.color_context_submenu) # A submenu to choose a single color used to color all the residues of a sequence. self.regular_colors_context_submenu = QtWidgets.QMenu('Color whole Sequence by', self.color_context_submenu) self.color_context_submenu.addMenu(self.regular_colors_context_submenu) self.build_regular_colors_submenu(self.regular_colors_context_submenu, "single") # Colors each kind of residue in a sequence in a different way. self.residues_colors_context_submenu = QtWidgets.QMenu('By Residue Properties', self.color_context_submenu) self.color_context_submenu.addMenu(self.residues_colors_context_submenu) add_qt_menu_command(self.residues_colors_context_submenu, "Residue Type", lambda: self.parent_group.main_window.color_selection("single", self.parent_group.pymod_element, "residue_type")) add_qt_menu_command(self.residues_colors_context_submenu, "Polarity", lambda: self.parent_group.main_window.color_selection("single", self.parent_group.pymod_element, "polarity")) # Secondary structure colors. if self.parent_group.can_be_colored_by_secondary_structure(): # self.color_context_submenu.addSeparator() self.sec_str_color_submenu = QtWidgets.QMenu('By Secondary Structure', self.color_context_submenu) self.color_context_submenu.addMenu(self.sec_str_color_submenu) if self.parent_group.pymod_element.has_structure(): add_qt_menu_command(self.sec_str_color_submenu, "Observed", lambda: self.parent_group.main_window.color_selection("single", self.parent_group.pymod_element, "secondary-observed")) if self.parent_group.pymod_element.has_predicted_secondary_structure(): add_qt_menu_command(self.sec_str_color_submenu, "Predicted by PSIPRED", lambda: self.parent_group.main_window.color_selection("single", self.parent_group.pymod_element, "secondary-predicted")) # Conservation colors. if self.parent_group.pymod_element.has_campo_scores() or self.parent_group.pymod_element.has_entropy_scores(): # self.color_context_submenu.addSeparator() self.conservation_colors_menu = QtWidgets.QMenu('By Conservation', self.color_context_submenu) self.color_context_submenu.addMenu(self.conservation_colors_menu) if self.parent_group.pymod_element.has_campo_scores(): add_qt_menu_command(self.conservation_colors_menu, "CAMPO scores", lambda: self.parent_group.main_window.color_selection("single", self.parent_group.pymod_element, "campo-scores")) if self.parent_group.pymod_element.has_entropy_scores(): add_qt_menu_command(self.conservation_colors_menu, "Entropy scores", lambda: self.parent_group.main_window.color_selection("single", self.parent_group.pymod_element, "entropy-scores")) # Energy colors. if self.parent_group.pymod_element.has_dope_scores(): # self.color_context_submenu.addSeparator() self.energy_colors_menu = QtWidgets.QMenu('By Energy', self.color_context_submenu) self.color_context_submenu.addMenu(self.energy_colors_menu) add_qt_menu_command(self.energy_colors_menu, "DOPE scores", lambda: self.parent_group.main_window.color_selection("single", self.parent_group.pymod_element, "dope")) # Color by domain. if self.parent_group.pymod_element.has_domains(): add_qt_menu_command(self.color_context_submenu, "By Domain", lambda: self.parent_group.main_window.color_selection("single", self.parent_group.pymod_element, "domains")) def build_regular_colors_submenu(self, target_menu, color_mode, elements_to_color=None): if color_mode == "single": elements_to_color = self.parent_group.pymod_element # Regular color scheme of the element. add_qt_menu_command(target_menu, "Default Color", lambda: self.parent_group.main_window.color_selection(color_mode, elements_to_color, "regular")) # Build PyMOL color palette menu. self.build_color_palette_submenu(color_mode, elements_to_color, target_menu, "PyMOL Colors", pmdt.pymol_regular_colors_list) ''' # Build PyMOL light color pallette. self.build_color_palette_submenu(color_mode, elements_to_color, target_menu, "PyMOL Light Colors", pmdt.pymol_light_colors_list) ''' # Build PyMod color palette. self.build_color_palette_submenu(color_mode, elements_to_color, target_menu, "PyMod Colors", pmdt.pymod_regular_colors_list) target_menu.addSeparator() # Custom color selection. add_qt_menu_command(target_menu, "Pick Color", lambda a=None, m=color_mode, e=elements_to_color: self.open_color_dialog_from_context(m, e)) def build_color_palette_submenu(self, color_mode, elements_to_color, target_submenu, title, list_of_colors): new_palette_submenu = QtWidgets.QMenu(title, target_submenu) target_submenu.addMenu(new_palette_submenu) for color in list_of_colors: add_qt_menu_command(parent=new_palette_submenu, label=color, command=lambda a=None, c=color: self.parent_group.main_window.color_selection(color_mode, elements_to_color, "regular", c), fg_color=self.parent_group.main_window.get_regular_sequence_color(color), bg_color="#ABABAB") def open_color_dialog_from_context(self, color_mode, elements_to_color): """ Gets from a 'QColorDialog' widget an HEX color string and colors a PyMod selection with it. """ selected_color = open_color_dialog(color_format="all") if selected_color is not None: color_rgb, color_hex = selected_color new_color_name = self.parent_group.pymod.add_new_color(color_rgb, color_hex) self.parent_group.main_window.color_selection(color_mode, elements_to_color, "regular", new_color_name) def build_structure_menu(self): """ Submenu for elements that have a structure loaded in PyMOL. """ self.structure_context_submenu = QtWidgets.QMenu('Structure', self.single_element_target_submenu) if self.parent_group.pymod_element.has_structure(): self.single_element_target_submenu.addMenu(self.structure_context_submenu) # add_qt_menu_command(self.structure_context_submenu, "PDB Chain Information", self.show_structure_info) add_qt_menu_command(self.structure_context_submenu, "Save PDB Chain to File", self.save_structure_from_left_pane) self.structure_context_submenu.addSeparator() add_qt_menu_command(self.structure_context_submenu, "Center Chain in PyMOL", self.center_chain_in_pymol_from_header_entry) # TODO: a switch would be nice. add_qt_menu_command(self.structure_context_submenu, "Show Chain in PyMOL", self.show_chain_in_pymol_from_header_entry) add_qt_menu_command(self.structure_context_submenu, "Hide Chain in PyMOL", self.hide_chain_in_pymol_from_header_entry) self.structure_context_submenu.addSeparator() add_qt_menu_command(self.structure_context_submenu, "Show Chain as Hedgehog", self.show_hedgehog_in_pymol_from_header_entry) add_qt_menu_command(self.structure_context_submenu, "Show Heteroatoms", self.show_het_in_pymol_from_header_entry) add_qt_menu_command(self.structure_context_submenu, "Hide Heteroatoms", self.hide_het_in_pymol_from_header_entry) self.single_element_target_submenu.addMenu(self.structure_context_submenu) else: if self.parent_group.pymod_element.pdb_is_fetchable(): add_qt_menu_command(self.structure_context_submenu, "Fetch PDB File", lambda: self.parent_group.pymod.fetch_pdb_files("single", self.parent_group.pymod_element)) # self.structure_context_submenu.addSeparator() # add_qt_menu_command(self.structure_context_submenu, "Associate 3D Structure", lambda: self.parent_group.pymod.associate_structure_from_popup_menu(self.parent_group.pymod_element)) self.single_element_target_submenu.addMenu(self.structure_context_submenu) def build_domains_menu(self): self.domains_context_submenu = QtWidgets.QMenu('Domains', self.single_element_target_submenu) add_qt_menu_command(self.domains_context_submenu, "Split into Domains", lambda a=None, pe=self.parent_group.pymod_element: self.parent_group.pymod.launch_domain_splitting(pe)) if self.parent_group.pymod_element.derived_domains_list: add_qt_menu_command(self.domains_context_submenu, "Fuse Domains Alignments", lambda a=None, pe=self.parent_group.pymod_element: self.parent_group.pymod.launch_domain_fuse(pe)) self.single_element_target_submenu.addMenu(self.domains_context_submenu) def builds_features_menu(self): self.features_context_submenu = QtWidgets.QMenu('Features', self.single_element_target_submenu) add_qt_menu_command(self.features_context_submenu, "Show Features", lambda: self.parent_group.main_window.color_selection("single", self.parent_group.pymod_element, "custom")) add_qt_menu_command(self.features_context_submenu, "Delete Features", lambda: self.parent_group.pymod.delete_features_from_context_menu(self.parent_group.pymod_element)) self.single_element_target_submenu.addMenu(self.features_context_submenu) def build_cluster_options_menu(self): """ Submenu with options to manage a sequence within its cluster. """ self.cluster_context_submenu = QtWidgets.QMenu('Cluster Options', self.single_element_target_submenu) self.single_element_target_submenu.addMenu(self.cluster_context_submenu) add_qt_menu_command(self.cluster_context_submenu, "Extract Sequence from Cluster", self.extract_from_cluster) # self.cluster_context_submenu.addSeparator() # if not self.parent_group.pymod_element.is_lead(): # add_qt_menu_command(self.cluster_context_submenu, "Make Cluster Lead", self.make_lead_from_left_menu) # else: # add_qt_menu_command(self.cluster_context_submenu, "Remove Cluster Lead", self.remove_lead_from_left_menu) ####################################### # Multiple elements (selection) menu. # ####################################### def build_selection_menu(self): """ Submenu with options for managing a selection. """ self.selection_context_submenu = QtWidgets.QMenu('Selection', self.context_menu) self.context_menu.addMenu(self.selection_context_submenu) # Build the "Sequence" menu. self.build_selection_sequence_menu() self.selection_context_submenu.addSeparator() # Build the "Color" menu. self.build_selection_color_menu() # Build the "Structure" menu. if self.parent_group.pymod.all_sequences_have_structure() or self.parent_group.pymod.all_sequences_have_fetchable_pdbs(): self.selection_context_submenu.addSeparator() self.build_selection_structure_menu() # Build the "Cluster" menu. if self.parent_group.pymod.all_sequences_are_children(): self.selection_context_submenu.addSeparator() self.build_selection_cluster_menu() def build_selection_sequence_menu(self): self.selection_sequence_context_submenu = QtWidgets.QMenu('Sequences', self.selection_context_submenu) self.selection_context_submenu.addMenu(self.selection_sequence_context_submenu) add_qt_menu_command(self.selection_sequence_context_submenu, "Save Selection to File", self.save_selection_from_left_pane) add_qt_menu_command(self.selection_sequence_context_submenu, "Copy Selection to Clipboard", self.copy_selection) self.selection_sequence_context_submenu.addSeparator() add_qt_menu_command(self.selection_sequence_context_submenu, "Duplicate Selection", self.duplicate_selection) add_qt_menu_command(self.selection_sequence_context_submenu, "Delete Selection", self.delete_many_sequences) def build_selection_color_menu(self): self.selection_color_context_submenu = self.build_multiple_color_menu(mode="selection") self.selection_context_submenu.addMenu(self.selection_color_context_submenu) def build_multiple_color_menu(self, mode, cluster_target_menu=None): """ Used to build the color menu of both Selection and cluster elements popup menus. """ if mode == "selection": target_menu = self.context_menu color_selection_mode = "selection" color_selection_target = None sequences_list = self.parent_group.pymod.get_selected_sequences() # color_selection_target = sequences_list color_target_label = "Selection" elif mode == "cluster": target_menu = cluster_target_menu color_selection_mode = "multiple" if self.parent_group.pymod_element.is_cluster(): color_selection_target = self.parent_group.pymod_element.get_children() sequences_list = self.parent_group.pymod_element.get_children() else: color_selection_target = self.parent_group.pymod_element.mother.get_children() sequences_list = self.parent_group.pymod_element.mother.get_children() color_target_label = "Cluster" # Builds the selection color menu. multiple_color_menu = QtWidgets.QMenu('Color', target_menu) # A submenu to choose a single color used to color all the residues of a sequence. multiple_regular_colors_menu = QtWidgets.QMenu("Color whole %s by" % (color_target_label), multiple_color_menu) # Menu(multiple_color_menu, tearoff=0, bg='white', activebackground='black', activeforeground='white') self.build_regular_colors_submenu(multiple_regular_colors_menu, color_selection_mode, elements_to_color=color_selection_target) multiple_color_menu.addMenu(multiple_regular_colors_menu) # multiple_color_menu.addSeparator() # Colors each kind of residue in a sequence in a different way. multiple_residues_colors_menu = QtWidgets.QMenu('By Residue Properties', target_menu) add_qt_menu_command(multiple_residues_colors_menu, "Residue Type", command=lambda: self.parent_group.main_window.color_selection(color_selection_mode, color_selection_target, "residue_type")) add_qt_menu_command(multiple_residues_colors_menu, "Polarity", command=lambda: self.parent_group.main_window.color_selection(color_selection_mode, color_selection_target, "polarity")) multiple_color_menu.addMenu(multiple_residues_colors_menu) # Secondary structure colors. n_selected_seqs = len(sequences_list) n_structures = len([e for e in sequences_list if e.has_structure()]) n_seq_with_predicted_sec_str = len([e for e in sequences_list if e.has_predicted_secondary_structure()]) if n_structures + n_seq_with_predicted_sec_str == n_selected_seqs: # multiple_color_menu.addSeparator() multiple_sec_str_color_menu = QtWidgets.QMenu('By Secondary Structure', multiple_color_menu) multiple_color_menu.addMenu(multiple_sec_str_color_menu) # Available when all the selected sequences have a 3D structure. if n_structures == n_selected_seqs: add_qt_menu_command(multiple_sec_str_color_menu, "Observed", lambda: self.parent_group.main_window.color_selection(color_selection_mode, color_selection_target, "secondary-observed")) # Available only if all the sequences have a predicted secondary structure. if n_seq_with_predicted_sec_str == n_selected_seqs: add_qt_menu_command(multiple_sec_str_color_menu, "Predicted by PSIPRED", lambda: self.parent_group.main_window.color_selection(color_selection_mode, color_selection_target, "secondary-predicted")) # Available if there is at least one element with a 3D structure or a secondary # structure prediction. if not n_structures == n_selected_seqs: add_qt_menu_command(multiple_sec_str_color_menu, "Auto (Observed + Predicted)", lambda: self.parent_group.main_window.color_selection(color_selection_mode, color_selection_target, "secondary-auto")) # Conservation colors. sel_has_campo_scores = all([e.has_campo_scores() for e in sequences_list]) sel_has_entropy_scores = all([e.has_entropy_scores() for e in sequences_list]) if sel_has_campo_scores or sel_has_entropy_scores: multiple_cons_colors_menu = QtWidgets.QMenu('By Conservation', multiple_color_menu) multiple_color_menu.addMenu(multiple_cons_colors_menu) if sel_has_campo_scores: add_qt_menu_command(multiple_cons_colors_menu, "CAMPO scores", lambda: self.parent_group.main_window.color_selection(color_selection_mode, color_selection_target, "campo-scores")) if sel_has_entropy_scores: add_qt_menu_command(multiple_cons_colors_menu, "Entropy scores", lambda: self.parent_group.main_window.color_selection(color_selection_mode, color_selection_target, "entropy-scores")) # Energy colors. if all([e.has_dope_scores() for e in sequences_list]): # multiple_color_menu.addSeparator() multiple_energy_colors_menu = QtWidgets.QMenu('By Energy', multiple_color_menu) multiple_color_menu.addMenu(multiple_energy_colors_menu) add_qt_menu_command(multiple_energy_colors_menu, "DOPE scores", lambda: self.parent_group.main_window.color_selection(color_selection_mode, color_selection_target, "dope")) # Color by domain. if all([e.has_domains() for e in sequences_list]): add_qt_menu_command(multiple_color_menu, "By Domain", lambda: self.parent_group.main_window.color_selection(color_selection_mode, color_selection_target, "domains")) return multiple_color_menu def build_selection_structure_menu(self): self.selection_structure_context_submenu = QtWidgets.QMenu('Structures', self.selection_context_submenu) self.selection_context_submenu.addMenu(self.selection_structure_context_submenu) if self.parent_group.pymod.all_sequences_have_structure(): add_qt_menu_command(self.selection_structure_context_submenu, "Show chains in PyMOL", self.show_selected_chains_in_pymol_from_popup_menu) add_qt_menu_command(self.selection_structure_context_submenu, "Hide chains in PyMOL", self.hide_selected_chains_in_pymol_from_popup_menu) self.selection_structure_context_submenu.addSeparator() add_qt_menu_command(self.selection_structure_context_submenu, "Show Chains as Hedgehog", self.show_hedgehog_chains_in_pymol_from_popup_menu) add_qt_menu_command(self.selection_structure_context_submenu, "Show Heteroatoms", self.show_het_chains_in_pymol_from_popup_menu) add_qt_menu_command(self.selection_structure_context_submenu, "Hide Heteroatoms", self.hide_het_chains_in_pymol_from_popup_menu) elif self.parent_group.pymod.all_sequences_have_fetchable_pdbs(): add_qt_menu_command(self.selection_structure_context_submenu, "Fetch PDB Files", lambda: self.parent_group.pymod.fetch_pdb_files("selection", None)) def build_selection_cluster_menu(self): self.selection_cluster_context_submenu = QtWidgets.QMenu('Cluster Options', self.selection_context_submenu) self.selection_context_submenu.addMenu(self.selection_cluster_context_submenu) add_qt_menu_command(self.selection_cluster_context_submenu, "Extract Sequences from their Clusters", self.extract_selection_from_cluster) selected_sequences = self.parent_group.pymod.get_selected_sequences() mothers_set = set([s.mother for s in selected_sequences]) if len(mothers_set) == 1: if len(selected_sequences) < len(self.parent_group.pymod_element.mother.get_children()): add_qt_menu_command(self.selection_cluster_context_submenu, "Extract Sequences to New Cluster", self.extract_selection_to_new_cluster_from_left_menu) ########################## # Cluster elements menu. # ########################## def build_cluster_popup_menu(self, target_menu, mode="cluster", extra_spacer=False): self.build_cluster_edit_menu(target_menu) def build_cluster_edit_menu(self, target_menu): self.cluster_edit_context_submenu = QtWidgets.QMenu('Edit Cluster', target_menu) target_menu.addMenu(self.cluster_edit_context_submenu) add_qt_menu_command(self.cluster_edit_context_submenu, "Save Alignment To File", self.save_alignment_from_left_pan) self.cluster_edit_context_submenu.addSeparator() add_qt_menu_command(self.cluster_edit_context_submenu, "Delete Gap Only Columns", self.delete_gap_only_columns_from_left_pane) add_qt_menu_command(self.cluster_edit_context_submenu, "Transfer Alignment", self.transfer_alignment_from_left_pane) self.cluster_edit_context_submenu.addSeparator() add_qt_menu_command(self.cluster_edit_context_submenu, "Delete Cluster", self.delete_alignment_from_left_pane) ############################################################################################### # Sequence manipulation events. # ############################################################################################### #------------ # Clusters. - #------------ def extract_from_cluster(self): """ Extracts an element from an alignment. """ self.parent_group.pymod_element.extract_to_upper_level() self.parent_group.main_window.gridder(clear_selection=True, update_clusters=True, update_menus=True) def extract_selection_from_cluster(self): selected_sequences = self.parent_group.pymod.get_selected_sequences() # Using 'reversed' keeps them in their original order once extracted. for e in reversed(selected_sequences): e.extract_to_upper_level() self.parent_group.main_window.gridder(clear_selection=True, update_clusters=True, update_menus=True) def extract_selection_to_new_cluster_from_left_menu(self): # 'gridder' is called in this method. self.parent_group.pymod.extract_selection_to_new_cluster() def make_lead_from_left_menu(self): self.parent_group.pymod_element.set_as_lead() def remove_lead_from_left_menu(self): self.parent_group.pymod_element.remove_all_lead_statuses() #------------------ # Save sequences. - #------------------ def save_sequence_from_left_pane(self): """ Save option in the popup menu, it saves a single sequence. """ self.parent_group.pymod.sequence_save_dialog(self.parent_group.pymod_element) def save_selection_from_left_pane(self): self.parent_group.pymod.save_selection_dialog() #--------------------- # Copy to clipboard. - #--------------------- def copy_sequence_to_clipboard(self): """ Copy option in the popup menu, copies a single sequence. """ cb = self.parent_group.main_window.clipboard cb.clear(mode=cb.Clipboard) cb.setText(self.parent_group.pymod_element.my_sequence, mode=cb.Clipboard) def copy_selection(self): cb = self.parent_group.main_window.clipboard cb.clear(mode=cb.Clipboard) text_to_copy = "" for element in self.parent_group.pymod.get_selected_sequences(): # TODO: Adapt it for WINDOWS. text_to_copy += element.my_sequence + "\n" cb.setText(text_to_copy, mode=cb.Clipboard) #--------------------------------- # Edit sequences and structures. - #--------------------------------- def edit_sequence_from_context(self): self.parent_group.pymod.show_edit_sequence_window(self.parent_group.pymod_element) def search_string_from_context(self): self.parent_group.pymod.show_search_string_window(self.parent_group.pymod_element) #------------------------------------------------ # Build new sequences and delete old sequences. - #------------------------------------------------ def duplicate_sequence_from_the_left_pane(self): """ Duplicates a single sequence. """ self.parent_group.pymod.duplicate_sequence(self.parent_group.pymod_element) self.parent_group.main_window.gridder() def duplicate_selection(self): for e in self.parent_group.pymod.get_selected_sequences(): self.parent_group.pymod.duplicate_sequence(e) self.parent_group.main_window.gridder() def delete_sequence_from_the_left_pane(self): """ Delete option in the popup menu. """ self.parent_group.pymod_element.delete() self.parent_group.main_window.gridder(clear_selection=True, update_clusters=True, update_menus=True) def delete_many_sequences(self): # Delete the selected sequences. for element in self.parent_group.pymod.get_selected_sequences(): element.delete() # Empty cluster elements will be deleted in the 'gridder' method. self.parent_group.main_window.gridder(clear_selection=True, update_clusters=True, update_menus=True) #------------------------------ # Save and delete alignments. - #------------------------------ def _get_cluster_from_popup_menu(self, pymod_element): # If the element is a cluster, return it. if pymod_element.is_cluster(): return pymod_element # If it's the lead of a collapsed cluster, return its mother (a cluster element). else: return pymod_element.mother def save_alignment_from_left_pan(self): self.parent_group.pymod.alignment_save_dialog(self._get_cluster_from_popup_menu(self.parent_group.pymod_element)) def delete_alignment_from_left_pane(self): self.parent_group.pymod.delete_cluster_dialog(self._get_cluster_from_popup_menu(self.parent_group.pymod_element)) def delete_gap_only_columns_from_left_pane(self): remove_gap_only_columns(self._get_cluster_from_popup_menu(self.parent_group.pymod_element)) self.parent_group.pymod.main_window.gridder(update_clusters=True, update_elements=True) def transfer_alignment_from_left_pane(self): self.parent_group.pymod.transfer_alignment(self._get_cluster_from_popup_menu(self.parent_group.pymod_element)) #---------------------------- # Save PDB chains to files. - #---------------------------- def save_structure_from_left_pane(self): self.parent_group.pymod.save_pdb_chain_to_file_dialog(self.parent_group.pymod_element) ############################################################################################### # Interact with the chain in PyMOL. # ############################################################################################### def center_chain_in_pymol_from_header_entry(self): self.parent_group.pymod.center_chain_in_pymol(self.parent_group.pymod_element) def hide_chain_in_pymol_from_header_entry(self): self.parent_group.pymod.hide_chain_in_pymol(self.parent_group.pymod_element) def show_chain_in_pymol_from_header_entry(self): self.parent_group.pymod.show_chain_in_pymol(self.parent_group.pymod_element) def show_hedgehog_in_pymol_from_header_entry(self): self.parent_group.pymod.show_hedgehog_in_pymol(self.parent_group.pymod_element) def show_het_in_pymol_from_header_entry(self): self.parent_group.pymod.show_het_in_pymol(self.parent_group.pymod_element) def hide_het_in_pymol_from_header_entry(self): self.parent_group.pymod.hide_het_in_pymol(self.parent_group.pymod_element) def show_selected_chains_in_pymol_from_popup_menu(self): for e in self.parent_group.pymod.get_selected_sequences(): self.parent_group.pymod.show_chain_in_pymol(e) def hide_selected_chains_in_pymol_from_popup_menu(self): for e in self.parent_group.pymod.get_selected_sequences(): self.parent_group.pymod.hide_chain_in_pymol(e) def show_hedgehog_chains_in_pymol_from_popup_menu(self): for e in self.parent_group.pymod.get_selected_sequences(): self.parent_group.pymod.show_hedgehog_in_pymol(e) def show_het_chains_in_pymol_from_popup_menu(self): for e in self.parent_group.pymod.get_selected_sequences(): self.parent_group.pymod.show_het_in_pymol(e) def hide_het_chains_in_pymol_from_popup_menu(self): for e in self.parent_group.pymod.get_selected_sequences(): self.parent_group.pymod.hide_het_in_pymol(e) def click_structure_with_middle_button(self, event=None): if self.parent_group.pymod_element.has_structure(): # Shows the structure and centers if the sequence is selected in Pymod. if self.parent_group.pymod_element.selected: self.show_chain_in_pymol_from_header_entry() self.center_chain_in_pymol_from_header_entry() # If the sequence is not selected in Pymod, hide it in PyMOL. else: self.hide_chain_in_pymol_from_header_entry() class Header_context_menu(QtWidgets.QMenu): """ Class for the context menu appearing when the user clicks with the right button on the header of an element. """ def __init__(self, parent): QtWidgets.QMenu.__init__(self, parent) self.parent = parent # Sets the context menu style. bg_color = "gray" # gray, #ABABAB context_menu_style = "color: white; font: %spt %s; font-weight: bold; padding: 0px; background: %s" % (self.parent.get_main_window().font_size, self.parent.get_main_window().font, bg_color) self.setStyleSheet(context_menu_style)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_gui/main_window/_sequence_text_qt.py
.py
25,703
583
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module implementing the widgets showing the sequences of PyMod elements in the right pane of PyMod main window. """ import time # For development only. from pymol.Qt import QtWidgets, QtCore, QtGui from ._header_entry_qt import Header_context_menu from pymod_lib.pymod_gui.shared_gui_components_qt import add_qt_menu_command, highlight_color from pymod_lib.pymod_vars import psipred_element_dict from pymol import cmd ################################################################################################### # Widget for the sequence of an element. # ################################################################################################### class MyQLabel_sequence(QtWidgets.QLabel): """ A custom QLabel for sequences. """ def __init__(self, parent_group): QtWidgets.QLabel.__init__(self, " ") self.setTextFormat(QtCore.Qt.RichText) # Set the text format as 'RichText' in order to display html. self.parent_group = parent_group self.setMouseTracking(True) self.resize_to_content() self.current_pos = 0 self.anchor_residue_number = 0 self.number_of_new_gaps = 0 self.gap_insert_velocity = 0.01 # Gaps (which are placed outside html tags) will be colored in white. self.setStyleSheet("color: #ffffff") self.drag_left_performed = None self.drag_right_performed = None self.set_default_cursor() def get_main_window(self): return self.parent_group.main_window def set_default_cursor(self): # self.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) def set_dragging_cursor(self): # self.setCursor(QtGui.QCursor(QtCore.Qt.ClosedHandCursor)) self.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor)) def build_html_seq(self): """ This method takes the sequence of a PyMod element (stored in its 'my_sequence' attribute) and formats it as html text to be displayed in a QLabel widget of Qt. A sequence like: ARVLPI--CW where the 'ARVL' residues are colored in white (#ffffff) and where the 'PICW' residues are colored in red (#f43030) will be formatted as: <font color='#ffffff'>ARVL</font><font color='#f43030'>PI</font>--<font color='#f43030'>CW</font> each group of contigous residues with the same color will be included in the same 'font' tag. Note that groups of residues with the same color separated by gaps, will be placed in different tags. In this way, gaps ("-" characters) will always be placed outside the 'font' tags and will be colored in white. """ t1 = time.time() # Get the residues of the sequence. if not self.parent_group.pymod_element.is_cluster(): residues = self.parent_group.pymod_element.get_polymer_residues() else: residues = None # Define the function to color a residue. if self.parent_group.pymod_element.color_by == "regular": regular_color = self.parent_group.pymod.all_colors_dict_tkinter[self.parent_group.pymod_element.my_color] def _get_color(residue_count, residues): return regular_color else: def _get_color(residue_count, residues): return residues[residue_count].color_seq seq_text = "" previous_char = None previous_color = None residue_count = 0 for p in self.parent_group.pymod_element.my_sequence: # Inserts residues. if p != "-": color = _get_color(residue_count, residues) residue_count += 1 # Opens the first tag. if previous_color == None: seq_text += "<font color='%s'>%s" % (color, p) # seq_text += "<font color='" + color + "'>" + p # Handle the rest of the tags. else: # Handle a residue. if previous_char != "-": # Continues to insert text in the current tag. if color == previous_color: seq_text += p # Closes the current tag. else: seq_text += "</font><font color='%s'>%s" % (color, p) # seq_text += "</font><font color='" + color + "'>" + p # Opens a new tag when ending a gap. else: seq_text += "<font color='%s'>%s" % (color, p) # seq_text += "<font color='" + color + "'>" + p previous_color = color # Inserts gaps. else: if previous_char == None or previous_char == "-": seq_text += "-" else: seq_text += "</font>-" previous_char = p # Closes the last tag. if p != "-": seq_text += "</font>" if self.parent_group.pymod.DEVELOP: print("- To build an html seq, it took:", time.time() - t1) return seq_text def update_text(self): self.setText(self.build_html_seq()) def resize_to_content(self): self.pixelsWide = self.get_main_window().fm.boundingRect(self.text() + " ").width(); self.pixelsHigh = self.get_main_window().fm.height() def get_html_content(self, html_text): """ Gets an html code, removes tags and return only the tag content. """ return "".join([i for i in html_text if i.isupper() or i == "-"]) ############################################################################################### # Mouse events to get sequence information. # ############################################################################################### def get_mousecurrent_position_on_string(self, event, curr_pos=None): """ When hovering with the mouse over a sequence, it returns the alignment position highlighted by the mouse. """ curr_pos = event.pos().x() # - 3 # Extracts the sequence from the formatted text. seq_only_text = self.get_html_content(self.text()) # Length in pixels of the sequence text (cosidering only sequence characters and not the # html tags used for coloring). lun_pixels = self.get_main_window().fm.width(seq_only_text) # Length of the sequence itself (including gaps). lun_seq = len(seq_only_text) # Position (index + 1) of the hovered character in the sequence. if lun_pixels != 0: seq_index = int(curr_pos/float(lun_pixels)*lun_seq) + 1 else: return "start" if seq_index > lun_seq: return "end" else: return seq_index def get_highlighted_residue(self, alignment_pos_id): """ Gets the highlighted position in the aligned sequence. """ return self.parent_group.pymod_element.get_residue_by_index(alignment_pos_id, aligned_sequence_index=True) def leaveEvent(self, event): """ Called when the mouse leaves a sequence label. """ self.parent_group.main_window.central_widget.textbox_sequence.setText("") self.parent_group.main_window.central_widget.textbox_position.setText("") #--------------------------------------- # Interact with the residues in PyMOL. - #--------------------------------------- def contextMenuEvent(self, event): """ Shows the context menu when right clickings on the sequence of an element. """ if self.parent_group.pymod_element.is_cluster(): return None alignment_id = self.get_mousecurrent_position_on_string(event) if alignment_id in ("start", "end"): return None alignment_id = alignment_id - 1 self.context_menu = Header_context_menu(self) add_qt_menu_command(self.context_menu, self.parent_group.pymod_element.my_header, None) self.context_menu.addSeparator() if self.parent_group.pymod_element.has_structure(): add_qt_menu_command(self.context_menu, "Select Residue in PyMOL", command=lambda a=None, aid=alignment_id: self.select_residue_in_pymol_from_sequence_text(aid)) add_qt_menu_command(self.context_menu, "Center Residue in PyMOL", command=lambda a=None, aid=alignment_id: self.center_residue_in_pymol_from_sequence_text(aid)) self.context_menu.addSeparator() add_qt_menu_command(self.context_menu, "Add Residue Feature", command=lambda a=None, aid=alignment_id: self.add_feature_from_sequence_text(aid)) action = self.context_menu.exec_(self.mapToGlobal(event.pos())) def click_residue_with_middle_button(self, event): alignment_id = self.get_mousecurrent_position_on_string(event) if alignment_id in ("start", "end"): return None alignment_id = alignment_id - 1 if self.parent_group.pymod_element.has_structure(): if self.parent_group.pymod_element.my_sequence[alignment_id] != "-": self.select_residue_in_pymol_from_sequence_text(alignment_id) self.center_residue_in_pymol_from_sequence_text(alignment_id) def select_residue_in_pymol_from_sequence_text(self, alignment_id): res = self.get_highlighted_residue(alignment_id) cmd.select("pymod_selection", res.get_pymol_selector()) # cmd.indicate("pymod_selection") def center_residue_in_pymol_from_sequence_text(self, alignment_id, event=None): res = self.get_highlighted_residue(alignment_id) cmd.center(res.get_pymol_selector()) def add_feature_from_sequence_text(self, alignment_id, event=None): res = self.get_highlighted_residue(alignment_id) self.parent_group.pymod.show_add_feature_window(self.parent_group.pymod_element, res) ############################################################################################### # Mouse events for sequence manipulation. # ############################################################################################### def mousePressEvent(self, event): """ Click on an element sequence. """ # Manipulate sequences. if event.buttons() == QtCore.Qt.LeftButton: self.set_dragging_cursor() res_pos = self.get_mousecurrent_position_on_string(event) # Refreshes the number of new gaps. self.number_of_new_gaps = 0 # Sets the position of the 'anchor' residue (the residue where the original click happened # before the user started to drag). if res_pos in ("start", "end"): self.anchor_residue_number = 0 self.initialize_drag = False return None # Allow to drag sequences only when clicking on residues. self.anchor_residue_number = res_pos if self.parent_group.pymod_element.my_sequence[res_pos-1] in ("-", ".", ":", "*") or self.parent_group.pymod_element.is_cluster(): self.initialize_drag = False else: self.initialize_drag = True # Quickly center the residue in PyMOL. elif event.buttons() == QtCore.Qt.MiddleButton: self.click_residue_with_middle_button(event) domain_str_attr = "name" # "description" def mouseMoveEvent(self, event): #-------------------------------------------------------------------------------------- # Print only sequence name and position in mw.central_widget if no button is pressed. - #-------------------------------------------------------------------------------------- if event.buttons() == QtCore.Qt.NoButton: # Get the highlighted residue object. is_residue = False alignment_pos = self.get_mousecurrent_position_on_string(event) if alignment_pos in ("start", "end"): # type(alignment_pos) is int: residue_information = alignment_pos else: alignment_pos_text = "Alignment Position: %s" % alignment_pos if self.parent_group.pymod_element.is_cluster(): residue_information = alignment_pos_text else: if self.parent_group.pymod_element.my_sequence[alignment_pos-1] != "-": pymod_res = self.get_highlighted_residue(alignment_pos-1) residue_information = "%s %s - %s" % (pymod_res.three_letter_code, pymod_res.db_index, alignment_pos_text) is_residue = True else: residue_information = "Gap - %s" % alignment_pos_text # Get additional information (depending on the color scheme of the element) to show in # the message bar. if is_residue: # Show the CAMPO score. if self.parent_group.pymod_element.color_by == "campo-scores": residue_information += " - CAMPO score: %s" % (pymod_res.campo_score["campo-score"]) # Show the entropy score. elif self.parent_group.pymod_element.color_by == "entropy-scores": residue_information += " - Entropy score: %s" % (pymod_res.entropy_score["entropy-score"]) # Show the prediction confidence. elif self.parent_group.pymod_element.color_by == "secondary-predicted": prediction = pymod_res.psipred_result pred_text = "%s %s" % (prediction["confidence"], psipred_element_dict[prediction["sec-str-element"]]) residue_information += " - PSIPRED confidence: %s" % (pred_text) # Show the DOPE score for the residue. elif self.parent_group.pymod_element.color_by == "dope": score = pymod_res.dope_score["score"] residue_information += " - DOPE score: %s" % (score) # Show the name of the domains. elif self.parent_group.pymod_element.color_by == "domains": res_domains = pymod_res.features["domains"] if len(res_domains) > 1: # More than one domain is assigned to the residue. domain_list_text = " - ".join(["(%s) %s" % (d_i+1, getattr(d, self.domain_str_attr)) for d_i, d in enumerate(res_domains)]) residue_information += " - Domains: %s" % (domain_list_text) elif len(res_domains) == 1: # Only one domain is assigned to the residue. residue_information += " - Domain: %s" % (getattr(res_domains[0], self.domain_str_attr)) # Show the name of the sequence features. elif self.parent_group.pymod_element.color_by == "custom": res_features = [f for f in pymod_res.features["sequence"] if f.show] if len(res_features) > 1: # More than one domain is assigned to the residue. features_list_text = " - ".join(["(%s) %s" % (d_i+1, getattr(d, self.domain_str_attr)) for d_i, d in enumerate(res_features)]) residue_information += " - Features: %s" % (features_list_text) elif len(res_features) == 1: # Only one domain is assigned to the residue. residue_information += " - Feature: %s" % (getattr(res_features[0], self.domain_str_attr)) # Show information on the message bars of the main window. self.parent_group.main_window.central_widget.textbox_sequence.setText(str(self.parent_group.pymod_element.my_header)) self.parent_group.main_window.central_widget.textbox_position.setText(str(residue_information)) #---------------------------------- # We start dragging the sequence. - #---------------------------------- elif event.buttons() == QtCore.Qt.LeftButton and self.initialize_drag: self.my_pos = event.pos().x() residue_index_of_mouse_over = self.get_mousecurrent_position_on_string(event, self.my_pos) if residue_index_of_mouse_over != 'start': if self.anchor_residue_number > 0: # Insert a gap behind any residue but the last. if residue_index_of_mouse_over != 'end': # Perform no action when dragging to the left of the first residue. if residue_index_of_mouse_over < 1: return None # Dragging the sequence on the right introduces a gap. if residue_index_of_mouse_over >= self.anchor_residue_number + self.gap_insert_velocity: self.anchor_residue_number = residue_index_of_mouse_over self.insert_gap_in_text() self.number_of_new_gaps += 1 self.drag_right_performed = True # Dragging the sequence on the left remove previous gap, if present. if residue_index_of_mouse_over < self.anchor_residue_number: if (self.parent_group.pymod_element.my_sequence[residue_index_of_mouse_over-1] == "-" or self.parent_group.pymod_element.my_sequence[residue_index_of_mouse_over] == "-"): if self.parent_group.pymod_element.my_sequence[residue_index_of_mouse_over-1] == "-": self.delete_gap_in_text(residue_index_of_mouse_over, gap_offset=-1) else: self.delete_gap_in_text(residue_index_of_mouse_over, gap_offset=0) self.number_of_new_gaps += self.number_of_new_gaps - 1 self.anchor_residue_number = residue_index_of_mouse_over self.drag_left_performed = True # Insert a gap behind the residue. else: self.anchor_residue_number += 1 self.insert_gap_in_text() self.number_of_new_gaps += 1 self.drag_right_performed = True # If the sequence is a child, the alignment symbols of the mother have to be # adjusted. if (self.drag_left_performed or self.drag_right_performed) and self.parent_group.pymod_element.is_child(): # Updates the mother's sequence. mother = self.parent_group.pymod_element.mother mother.update_stars(adjust_elements=False) # Update the mother's sequence widget. mother.widget_group.sequence_text.update_text() def insert_gap(self, string, index=0): return string[:index] + '-' + string[index:] def delete_gap(self, string, index=0): return string[:index]+ string[index+1:] def insert_gap_in_text(self): #----------------------------------- # Inserts the gap in the sequence. - #----------------------------------- old_seq = self.parent_group.pymod_element.my_sequence new_seq = self.insert_gap(old_seq, self.anchor_residue_number - 2) self.parent_group.pymod_element.my_sequence = new_seq #--------------------------------------------------- # Inserts the gap in the html text of the element. - #--------------------------------------------------- old_html_seq = self.text() new_html_seq = self.build_html_seq() self.setText(new_html_seq) def delete_gap_in_text(self, residue_index_of_mouse_over, gap_offset=0): old_seq = self.parent_group.pymod_element.my_sequence new_seq = self.delete_gap(old_seq, residue_index_of_mouse_over + gap_offset) self.parent_group.pymod_element.my_sequence = new_seq old_html_seq = self.text() new_html_seq = self.build_html_seq() self.setText(new_html_seq) def mouseReleaseEvent(self, event): self.set_default_cursor() # If the element is in a cluster, modifies the sequence text of other elements of the # cluster. if self.parent_group.pymod_element.is_child() and (self.drag_left_performed or self.drag_right_performed): ####################################################################################### # NOTE: an optimal way to do this would be to rstrip all the sequences, then to ljust # # them to the lenght of the "longest" one. However Tkinter is too slow to do this, it # # takes too much time to update all the sequences in big clusters at the same time, # # therefore as long as Tkinter is used, the following code has to be applied. This # # code prevents every sequence of a cluster from being updated every time an indel is # # added, and it tries to update only the necessary sequences. # ####################################################################################### elements_to_update = [self.parent_group.pymod_element] + self.parent_group.pymod_element.get_siblings() max_len = max([len(e.my_sequence.rstrip("-")) for e in elements_to_update]) for element in elements_to_update + [self.parent_group.pymod_element.mother]: element.widget_group.sequence_text.adjust_to_length(adjusted_len=max_len) self.drag_left_performed = None self.drag_right_performed = None def adjust_to_length(self, adjusted_len): if len(self.parent_group.pymod_element.my_sequence) > adjusted_len: # len(self.parent_group.pymod_element.my_sequence): self.rstrip_entry(adjusted_len) elif len(self.parent_group.pymod_element.my_sequence) < adjusted_len: # len(self.parent_group.pymod_element.my_sequence): self.ljust_entry(adjusted_len) def rstrip_entry(self, maxlength, update=True): self.parent_group.pymod_element.my_sequence = self.parent_group.pymod_element.my_sequence.rstrip("-").ljust(maxlength, "-") self.update_text() def ljust_entry(self, maxlength, update=True): self.parent_group.pymod_element.my_sequence = self.parent_group.pymod_element.my_sequence.ljust(maxlength, "-") self.update_text() ################################################################################################### # Widget for the cluster button of an element. # ################################################################################################### class Cluster_button(QtWidgets.QLabel): """ A custom class for cluster buttons in the main window of PyMod. """ fg_color = "white" bd_color = "gray" def __init__(self, parent_group): QtWidgets.QLabel.__init__(self, "-") self.parent_group = parent_group self.setMouseTracking(True) self.set_default_cursor() def set_default_cursor(self): # self.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) def mousePressEvent(self, event): if self.parent_group.pymod_element.is_cluster(): if event.buttons() == QtCore.Qt.LeftButton: self.parent_group.cluster_button_click(None) def set_visibility(self): if self.parent_group.pymod_element.is_cluster(): self.set_cluster_button_style() self.setVisible(True) elif self.parent_group.pymod_element.is_child(): self.set_child_sign_style() self.setVisible(True) def set_cluster_button_style(self): self.setStyleSheet("color: %s; border: 0px solid %s; background-color: %s; padding: 0px 1px" % (self.fg_color, self.bd_color, highlight_color)) if self.parent_group._cluster_button_state: self.setText("-") else: self.setText("+") self.setToolTip('Press to Expand/Shrink') def set_child_sign_style(self): """ Shows an additional entry inside the right-frame for child elements. """ self.setStyleSheet("color: %s; border-left: 1px solid %s; padding: 0px 0px" % (self.fg_color, self.bd_color)) if self.parent_group.pymod_element.is_blast_query(): child_sign = "q" # "|q" elif self.parent_group.pymod_element.is_lead(): child_sign = "l" # "|l" elif self.parent_group.pymod_element.is_bridge(): child_sign = "b" # "|b" else: child_sign = "_" # "|_" self.setText(child_sign) self.setToolTip(None)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_gui/main_window/_main_menu_qt.py
.py
23,319
406
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ A module for building the Qt PyMod main window menu. """ import sys from pymol.Qt import QtWidgets, QtGui from pymod_lib import pymod_vars from pymod_lib.pymod_gui.shared_gui_components_qt import add_qt_menu_command class PyMod_main_window_main_menu: """ A class for the Qt PyMod main window menu. """ def make_main_menu(self): """ This method is called when initializing the main window in order to build its main menu. """ self.menubar = self.menuBar() self.menubar.setNativeMenuBar(False) #--------------- # "File" menu. - #--------------- self.file_menu = self.menubar.addMenu('File') # Sequences submenu. self.sequences_submenu = QtWidgets.QMenu('Sequences and Structures', self) self.file_menu.addMenu(self.sequences_submenu) add_qt_menu_command(self.sequences_submenu, 'Open from File', self.pymod.open_file_from_the_main_menu) add_qt_menu_command(self.sequences_submenu, 'Add Raw Sequence', self.pymod.show_raw_seq_input_window) add_qt_menu_command(self.sequences_submenu, 'Import PyMOL Objects', self.pymod.import_pymol_selections_from_main_menu) # self.file_menu.addSeparator() # Submenu to open alignments. self.alignment_files_submenu = QtWidgets.QMenu('Alignments', self) self.file_menu.addMenu(self.alignment_files_submenu) add_qt_menu_command(self.alignment_files_submenu, 'Open from File', self.pymod.open_alignment_from_main_menu) # Submenu to open results files from external programs. self.external_results_submenu = QtWidgets.QMenu('External Programs Results', self) self.file_menu.addMenu(self.external_results_submenu) self.hhsuite_results_submenu = QtWidgets.QMenu('HH-suite', self) self.external_results_submenu.addMenu(self.hhsuite_results_submenu) add_qt_menu_command(self.hhsuite_results_submenu, 'Template Search (.hhr)', self.pymod.open_hhsuite_hhr_from_main_menu) add_qt_menu_command(self.hhsuite_results_submenu, 'Multiple Sequence Alignment (.a3m)', self.pymod.open_hhsuite_a3m_from_main_menu) self.file_menu.addSeparator() # Workspace submenu. self.sessions_submenu = QtWidgets.QMenu('Sessions', self) self.file_menu.addMenu(self.sessions_submenu) add_qt_menu_command(self.sessions_submenu, 'New', self.pymod.start_new_session_from_main_menu) add_qt_menu_command(self.sessions_submenu, 'Save', self.pymod.save_session_from_main_menu) add_qt_menu_command(self.sessions_submenu, 'Open', self.pymod.open_session_from_main_menu) self.file_menu.addSeparator() # Exit command. add_qt_menu_command(self.file_menu, 'Exit', self.pymod.exit_from_main_menu) #---------------- # "Tools" menu. - #---------------- self.tools_menu = self.menubar.addMenu('Tools') # Database search for homologous sequences. self.database_search_submenu = QtWidgets.QMenu('Database Search', self) self.tools_menu.addMenu(self.database_search_submenu) self.blast_tools_submenu = QtWidgets.QMenu('BLAST', self) self.database_search_submenu.addMenu(self.blast_tools_submenu) add_qt_menu_command(self.blast_tools_submenu, 'Local BLAST', lambda: self.pymod.launch_blast_algorithm("blastp")) add_qt_menu_command(self.blast_tools_submenu, 'Remote BLAST', lambda: self.pymod.launch_blast_algorithm("blast")) add_qt_menu_command(self.database_search_submenu, 'PSI-BLAST', lambda: self.pymod.launch_blast_algorithm("psi-blast")) self.database_search_submenu.addSeparator() add_qt_menu_command(self.database_search_submenu, 'phmmer', lambda: self.pymod.launch_hmmer_algorithm("phmmer")) add_qt_menu_command(self.database_search_submenu, 'jackhmmer', lambda: self.pymod.launch_hmmer_algorithm("jackhmmer")) add_qt_menu_command(self.database_search_submenu, 'hmmsearch', lambda: self.pymod.launch_hmmer_algorithm("hmmsearch")) # Alignment tools self.alignments_tools_submenu = QtWidgets.QMenu('Alignment Tools', self) self.tools_menu.addMenu(self.alignments_tools_submenu) # Sequence alignment tools. self.sequence_alignments_submenu = QtWidgets.QMenu('Sequence Alignment', self) self.alignments_tools_submenu.addMenu(self.sequence_alignments_submenu) add_qt_menu_command(self.sequence_alignments_submenu, 'ClustalW', lambda: self.pymod.launch_alignment_from_the_main_menu("clustalw", "regular")) add_qt_menu_command(self.sequence_alignments_submenu, 'Clustal Omega', lambda: self.pymod.launch_alignment_from_the_main_menu("clustalo", "regular")) add_qt_menu_command(self.sequence_alignments_submenu, 'MUSCLE', lambda: self.pymod.launch_alignment_from_the_main_menu("muscle", "regular")) add_qt_menu_command(self.sequence_alignments_submenu, 'SALIGN (Sequence Alignment)', lambda: self.pymod.launch_alignment_from_the_main_menu("salign-seq", "regular")) # Profile alignment tools. self.sequence_profile_alignments_submenu = QtWidgets.QMenu('Profile Alignment', self) self.alignments_tools_submenu.addMenu(self.sequence_profile_alignments_submenu) add_qt_menu_command(self.sequence_profile_alignments_submenu, 'ClustalW', lambda: self.pymod.launch_alignment_from_the_main_menu("clustalw", "profile")) add_qt_menu_command(self.sequence_profile_alignments_submenu, 'Clustal Omega', lambda: self.pymod.launch_alignment_from_the_main_menu("clustalo", "profile")) add_qt_menu_command(self.sequence_profile_alignments_submenu, 'SALIGN (Sequence Alignment)', lambda: self.pymod.launch_alignment_from_the_main_menu("salign-seq", "profile")) # Structural alignment tools. self.structural_alignment_submenu = QtWidgets.QMenu('Structural Alignment', self) self.alignments_tools_submenu.addMenu(self.structural_alignment_submenu) # add_qt_menu_command(self.structural_alignment_submenu, 'Superpose', self.pymod.superpose_from_main_menu) add_qt_menu_command(self.structural_alignment_submenu, 'CE Alignment', lambda: self.pymod.launch_alignment_from_the_main_menu("ce", "regular")) add_qt_menu_command(self.structural_alignment_submenu, 'SALIGN (Structure Alignment)', lambda: self.pymod.launch_alignment_from_the_main_menu("salign-str", "regular")) # Domain tools. self.domain_analysis_submenu = QtWidgets.QMenu('Domains Analysis', self) self.tools_menu.addMenu(self.domain_analysis_submenu) self.hmmscan_tools_submenu = QtWidgets.QMenu('hmmscan', self) self.domain_analysis_submenu.addMenu(self.hmmscan_tools_submenu) add_qt_menu_command(self.hmmscan_tools_submenu, 'Local hmmscan', lambda: self.pymod.launch_domain_analysis("local")) add_qt_menu_command(self.hmmscan_tools_submenu, 'Remote hmmscan', lambda: self.pymod.launch_domain_analysis("remote")) # Structural analysis. self.structural_analysis_submenu = QtWidgets.QMenu('Structural Analysis', self) self.tools_menu.addMenu(self.structural_analysis_submenu) add_qt_menu_command(self.structural_analysis_submenu, 'Ramachandran Plot', self.pymod.ramachandran_plot_from_main_menu) add_qt_menu_command(self.structural_analysis_submenu, 'Contact Map', self.pymod.contact_map_from_main_menu) add_qt_menu_command(self.structural_analysis_submenu, 'Structural Divergence Plot', self.pymod.sda_from_main_menu) self.structural_analysis_submenu.addSeparator() add_qt_menu_command(self.structural_analysis_submenu, 'Assess with DOPE', self.pymod.dope_from_main_menu) self.structural_analysis_submenu.addSeparator() add_qt_menu_command(self.structural_analysis_submenu, 'PSIPRED', self.pymod.launch_psipred_from_main_menu) # Modeling. self.modeling_submenu = QtWidgets.QMenu('Modeling', self) self.tools_menu.addMenu(self.modeling_submenu) add_qt_menu_command(self.modeling_submenu, "MODELLER (Homology Modeling)", self.pymod.launch_modeller_hm_from_main_menu) add_qt_menu_command(self.modeling_submenu, "MODELLER (Loop Modeling)", self.pymod.launch_modeller_lr_from_main_menu) # Options. self.tools_menu.addSeparator() add_qt_menu_command(self.tools_menu, 'Options', self.pymod.show_pymod_options_window) #--------------------- # "Alignments" menu. - #--------------------- self.alignments_menu = self.menubar.addMenu('Alignments') self.build_alignment_submenu() #----------------- # "Models" menu. - #----------------- # When the plugin is started there are no models. self.models_menu = self.menubar.addMenu('Models') self.build_models_submenu() #-------------------- # "Selection" menu. - #-------------------- self.main_selection_menu = self.menubar.addMenu('Selection') add_qt_menu_command(self.main_selection_menu, 'Select All [Ctrl+a]', self.pymod.select_all_from_main_menu) add_qt_menu_command(self.main_selection_menu, 'Deselect All [Esc]', self.pymod.deselect_all_from_main_menu) # Structures selection submenu. self.selection_structures_menu = QtWidgets.QMenu('Structures', self) self.main_selection_menu.addMenu(self.selection_structures_menu) add_qt_menu_command(self.selection_structures_menu, 'Show All in PyMOL [Ctrl+s]', self.pymod.show_all_structures_from_main_menu) add_qt_menu_command(self.selection_structures_menu, 'Hide All in PyMOL [Ctrl+h]', self.pymod.hide_all_structures_from_main_menu) self.selection_structures_menu.addSeparator() add_qt_menu_command(self.selection_structures_menu, 'Select All', self.pymod.select_all_structures_from_main_menu) add_qt_menu_command(self.selection_structures_menu, 'Deselect All', self.pymod.deselect_all_structures_from_main_menu) # Clusters selection submenu. self.selection_clusters_menu = QtWidgets.QMenu('Clusters', self) self.main_selection_menu.addMenu(self.selection_clusters_menu) add_qt_menu_command(self.selection_clusters_menu, 'Expand All', self.pymod.expand_all_clusters_from_main_menu) add_qt_menu_command(self.selection_clusters_menu, 'Collapse All', self.pymod.collapse_all_clusters_from_main_menu) #------------------ # "Display" menu. - #------------------ self.display_menu = self.menubar.addMenu('Display') if self.pymod.DEVELOP: add_qt_menu_command(self.display_menu, 'Print Selected Sequences', command=self.print_selected) # Color menu. self.main_color_menu = QtWidgets.QMenu('Color all Sequences', self) self.display_menu.addMenu(self.main_color_menu) add_qt_menu_command(self.main_color_menu, 'By Default Color', command=lambda: self.color_selection("all", None, "regular")) self.main_residues_colors_menu = QtWidgets.QMenu('By Residue Properties', self) self.main_color_menu.addMenu(self.main_residues_colors_menu) add_qt_menu_command(self.main_residues_colors_menu, 'Residue Type', command=lambda: self.color_selection("all", None, "residue_type")) add_qt_menu_command(self.main_residues_colors_menu, 'Polarity', command=lambda: self.color_selection("all", None, "polarity")) add_qt_menu_command(self.main_color_menu, 'By Secondary Structure', command=lambda: self.color_selection("all", None, "secondary-auto")) # Font selection. self.font_selection_menu = QtWidgets.QMenu('Font Selection', self) self.display_menu.addMenu(self.font_selection_menu) if self.pymod.DEVELOP: add_qt_menu_command(self.display_menu, 'Font Type and Size', self.pymod.change_font_from_main_menu) # Font size selection. self.font_size_selection_menu = QtWidgets.QMenu('Font Size', self) self.font_selection_menu.addMenu(self.font_size_selection_menu) font_size_action_group = QtWidgets.QActionGroup(self.font_size_selection_menu) font_size_action_group.setExclusive(True) for font_size in ("6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"): action = font_size_action_group.addAction(QtWidgets.QAction(font_size, self.font_size_selection_menu, checkable=True)) self.font_size_selection_menu.addAction(action) if font_size == str(self.font_size): action.setChecked(True) action.triggered.connect(lambda a=None, t=None, s=font_size: self.pymod.change_font_from_action(t, s)) # Font type selection. self.font_type_selection_menu = QtWidgets.QMenu('Font Type', self) self.font_selection_menu.addMenu(self.font_type_selection_menu) font_type_action_group = QtWidgets.QActionGroup(self.font_type_selection_menu) font_type_action_group.setExclusive(True) for font_type in self.get_available_fonts(): action = font_type_action_group.addAction(QtWidgets.QAction(font_type, self.font_type_selection_menu, checkable=True)) self.font_type_selection_menu.addAction(action) if font_type == str(self.font): action.setChecked(True) action.triggered.connect(lambda a=None, t=font_type, s=None: self.pymod.change_font_from_action(t, s)) #--------------- # "Help" menu. - #--------------- self.help_menu = self.menubar.addMenu('Help') if self.pymod.DEVELOP: add_qt_menu_command(self.help_menu, 'Test', self.pymod.launch_default) add_qt_menu_command(self.help_menu, 'Online Documentation', self.pymod.open_online_documentation) add_qt_menu_command(self.help_menu, 'About', self.pymod.show_about_dialog) self.help_menu.addSeparator() add_qt_menu_command(self.help_menu, "Install PyMod Components", self.pymod.launch_components_installation) add_qt_menu_command(self.help_menu, "Check for Database Updates", self.pymod.launch_databases_update) if self.pymod.TEST: self.help_menu.addSeparator() self.examples_menu = QtWidgets.QMenu('Examples', self) self.help_menu.addMenu(self.examples_menu) add_qt_menu_command(self.examples_menu, "Load random sequence from UniProt", lambda a=None: self.pymod.load_uniprot_random()) add_qt_menu_command(self.examples_menu, "Load random PDB entry", lambda a=None: self.pymod.load_pdb_random()) selected_fonts_dict = {"linux": ["Andale Mono", "Courier", "DejaVu Sans Mono", "Liberation Mono", "Monospace", "Ubuntu Mono",], "win32": ["Consolas", # "Courier", # Doesn't seem to get the character size correctly. "Lucida Sans Typewriter"], "darwin": [ # "consolas", "courier", "liberation mono", "lucida console", "menlo", # "monaco", "monofur", "prestige elite", "roboto mono"]} def get_available_fonts(self): # Get the system fonts. font_family_list = [font_name.lower() for font_name in QtGui.QFontDatabase().families()] # Get the fonts available in PyMod. selected_fonts = [font_name.lower() for font_name in self.selected_fonts_dict.get(sys.platform, [])] # Filter the system fonts list. font_family_list = [font_name for font_name in font_family_list if font_name in selected_fonts] font_family_list.insert(0, "courier new") font_family_list.sort() return font_family_list ######################################################################################### # Build submenus which get populated with elements when performing operations in PyMod. # ######################################################################################### def build_alignment_submenu(self): """ Build an "Alignment N" voice in the "Alignments" submenu when alignment N is performed. """ # Delete the old alignment submenu. self.alignments_menu.clear() # Then rebuilds it with the new alignments. alignment_list = self.pymod.get_cluster_elements() if alignment_list != []: for alignment_element in alignment_list: # Adds the alignment submenu for each cluster loaded in PyMod to the PyMod main menu. label_text = alignment_element.my_header single_alignment_submenu = QtWidgets.QMenu(label_text, self) self.alignments_menu.addMenu(single_alignment_submenu) # Save to a file dialog. add_qt_menu_command(single_alignment_submenu, "Save to File", # The first argument in Qt is a 'False' value, therefore we need to add a dummy 'a' variable # in order to pass the 'alignment_element' object. lambda a=None, e=alignment_element: self.pymod.save_alignment_to_file_from_ali_menu(e)) single_alignment_submenu.addSeparator() # Matrices submenu. single_alignment_matrices_submenu = QtWidgets.QMenu('Matrices', self) single_alignment_submenu.addMenu(single_alignment_matrices_submenu) add_qt_menu_command(single_alignment_matrices_submenu, "Sequence Identity Matrix", lambda a=None, e=alignment_element: self.pymod.display_identity_matrix(e)) add_qt_menu_command(single_alignment_matrices_submenu, "RMSD Matrix", lambda a=None, e=alignment_element: self.pymod.display_rmsd_matrix_from_alignments_menu(e)) # Trees. if alignment_element.initial_number_of_sequences > 2: single_alignment_trees_submenu = QtWidgets.QMenu('Trees', self) single_alignment_submenu.addMenu(single_alignment_trees_submenu) if alignment_element.algorithm in pymod_vars.can_show_guide_tree: add_qt_menu_command(single_alignment_trees_submenu, "Show Guide Tree", lambda a=None, e=alignment_element: self.pymod.show_guide_tree_from_alignments_menu(e)) if alignment_element.algorithm in pymod_vars.can_show_dendrogram and alignment_element.tree_file_path is not None: add_qt_menu_command(single_alignment_trees_submenu, "Show SALIGN Dendrogram", lambda a=None, e=alignment_element: self.pymod.show_dendrogram_from_alignments_menu(e)) if len(alignment_element.get_children()) >= 2: add_qt_menu_command(single_alignment_trees_submenu, "Build Tree from Alignment", lambda a=None, e=alignment_element: self.pymod.build_tree_from_alignments_menu(e)) # Evolutionary conservation. single_alignment_evolutionary_submenu = QtWidgets.QMenu('Evolutionary Conservation', self) single_alignment_submenu.addMenu(single_alignment_evolutionary_submenu) single_seq_evolutionary_submenu = QtWidgets.QMenu('Sequence Conservation', self) single_alignment_evolutionary_submenu.addMenu(single_seq_evolutionary_submenu) add_qt_menu_command(single_seq_evolutionary_submenu, "Entropy", lambda a=None, e=alignment_element: self.pymod.launch_entropy_scorer_from_main_menu(e)) add_qt_menu_command(single_seq_evolutionary_submenu, "CAMPO", lambda a=None, e=alignment_element: self.pymod.launch_campo_from_main_menu(e)) add_qt_menu_command(single_seq_evolutionary_submenu, "Pair Conservation", lambda a=None, e=alignment_element: self.pymod.launch_pc_from_main_menu(e)) single_str_evolutionary_submenu = QtWidgets.QMenu('Structural Conservation', self) single_alignment_evolutionary_submenu.addMenu(single_str_evolutionary_submenu) add_qt_menu_command(single_str_evolutionary_submenu, "SCR_FIND", lambda a=None, e=alignment_element: self.pymod.launch_scr_find_from_main_menu(e)) # Render alignment. single_alignment_render_submenu = QtWidgets.QMenu('Render Alignment', self) single_alignment_submenu.addMenu(single_alignment_render_submenu) add_qt_menu_command(single_alignment_render_submenu, "Generate Logo through WebLogo 3", lambda a=None, e=alignment_element: self.pymod.launch_weblogo_from_main_menu(e)) add_qt_menu_command(single_alignment_render_submenu, "Launch ESPript in Web Browser", lambda a=None, e=alignment_element: self.pymod.launch_espript_from_main_menu(e)) else: add_qt_menu_command(self.alignments_menu, "There aren't any alignments") def build_models_submenu(self): """ Build an "Modeling Session n" voice in the "Models" submenu once some models have been built. """ # Delete the old models submenu. self.models_menu.clear() if self.pymod.modeling_session_list != []: for modeling_session in self.pymod.modeling_session_list: # Adds a modeling session submenu to the PyMod main menu. label_text = "Modeling Session %s" % (modeling_session.session_id) modeling_session_submenu = QtWidgets.QMenu(label_text, self) self.models_menu.addMenu(modeling_session_submenu) add_qt_menu_command(modeling_session_submenu, "Export to File", lambda a=None, ms=modeling_session: self.pymod.save_modeling_session(ms)) add_qt_menu_command(modeling_session_submenu, "DOPE Profile", lambda a=None, ms=modeling_session: self.pymod.show_session_profile(ms)) add_qt_menu_command(modeling_session_submenu, "Assessment Table", lambda a=None, ms=modeling_session: self.pymod.show_assessment_table(ms)) else: add_qt_menu_command(self.models_menu, "There aren't any models")
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_gui/main_window/main_window_qt.py
.py
45,008
1,076
# Copyright 2020 by Giacomo Janson, Alessandro Paiardini. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ This module implements the main window of PyMod written in Qt. Other modules in this package provide several main window widgets and mixins used to extend the class written in this file. """ import os import sys from pymol.Qt import QtWidgets, QtCore, QtGui # Import the stylesheet. from .aqua.qsshelper import QSSHelper from pymod_lib.pymod_gui.shared_gui_components_qt import askyesno_qt, small_font_style from ._main_menu_qt import PyMod_main_window_main_menu from ._element_widgets_qt import PyMod_element_widgets_group_qt import pymod_lib.pymod_vars as pmdt from pymol import cmd class PyMod_main_window_qt(QtWidgets.QMainWindow, PyMod_main_window_main_menu): """ A class for the PyQT PyMod main window. """ is_pymod_window = True is_pymod_main_window = True def __init__(self, pymod, parent=None): super().__init__(parent) # Initial settings. self.pymod = pymod self.title = self.pymod.pymod_plugin_name + "." + self.pymod.pymod_revision self.statusBar_message = "Ready" self.left = 50 self.top = 50 self.width = 1100 # 2200, 1100 self.height = 800 # 400 self.bg_color = 'rgb(0, 0, 0)' self.text_color = "rgb(255, 255, 255)" # Fonts and styles. self.font_weight = "bold" self.font_size = 10 # 9, 10, 12 self.font = "courier new" self.vertical_spacing = 1 self.horizontal_spacing = 20 # Creating a menu bar. self.make_main_menu() # create_menu_bar() # Creating central widget and setting it as central. self.central_widget = Centralwid(self) self.setCentralWidget(self.central_widget) self.update_qt_font() # Creating status bar. self.statusBar().showMessage(self.statusBar_message, 3000) self.statusBar().setSizeGripEnabled(1) # Initialize User Interface. self.initUI() # Set the layout. self.central_widget.id_form_layout.setFormAlignment(QtCore.Qt.AlignLeft) self.central_widget.id_form_layout.setVerticalSpacing(self.vertical_spacing) self.central_widget.sequence_ID_groupbox.setLayout(self.central_widget.id_form_layout) self.central_widget.seq_form_layout.setHorizontalSpacing(self.horizontal_spacing) self.central_widget.seq_form_layout.setFormAlignment(QtCore.Qt.AlignLeft) self.central_widget.seq_form_layout.setLabelAlignment(QtCore.Qt.AlignLeft) self.central_widget.seq_form_layout.setVerticalSpacing(self.vertical_spacing) self.central_widget.sequence_SEQ_groupbox.setLayout(self.central_widget.seq_form_layout) # Initializes a clipboard. self.clipboard = QtWidgets.QApplication.clipboard() #---------------- # Key bindings. - #---------------- # Select elements. self.select_all_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+A"), self) self.select_all_shortcut.activated.connect(self.select_all_binding) self.show_all_structures_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+S"), self) self.show_all_structures_shortcut.activated.connect(self.show_all_structures_binding) self.hide_all_structures_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+H"), self) self.hide_all_structures_shortcut.activated.connect(self.hide_all_structures_binding) self.deselect_all_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence("Esc"), self) self.deselect_all_shortcut.activated.connect(self.deselect_all_binding) # Move elements. self.press_up_key_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence("up"), self) self.press_up_key_shortcut.activated.connect(self.press_up_key_binding) self.press_down_key_shortcut = QtWidgets.QShortcut(QtGui.QKeySequence("down"), self) self.press_down_key_shortcut.activated.connect(self.press_down_key_binding) def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) # Loads and sets the Qt stylesheet. module_path = sys.modules[__name__].__file__ self.qss = QSSHelper.open_qss(os.path.join(os.path.dirname(module_path), 'aqua', 'aqua.qss')) self.setStyleSheet(self.qss) self.show() def closeEvent(self, evnt): if evnt.spontaneous(): self.confirm_close(evnt) else: pass def confirm_close(self, evnt=None): """ Asks confirmation when the main window is closed by the user. """ answer = askyesno_qt("Exit PyMod?", "Are you really sure you want to exit PyMod?", parent=self.pymod.get_qt_parent()) if answer: self.pymod.inactivate_session() self.close() # Closes the PyMod main window. else: if evnt is not None: evnt.ignore() ############################################################################################### # Gridding system. # ############################################################################################### def gridder(self, clear_selection=False, update_clusters=True, update_menus=True, update_elements=True): """ Grids the PyMod elements (of both sequences and clusters) widgets in PyMod main window. When new elements are added to PyMod using the 'add_pymod_element_widgets' method of the 'PyMod' class, their PyQT widgets are initializated, but they are not displayed in PyMod main window. This method actually displayes the widgets. """ #--------------------------------------- # Update clusters elements appearance. - #--------------------------------------- if update_clusters: # First updates the cluster sequences and removes clusters with one or zero children. for cluster in self.pymod.get_cluster_elements(): self.pymod.update_cluster_sequences(cluster) #---------------------------- # Assigns the grid indices. - #---------------------------- self.global_grid_row_index = 0 self.global_grid_column_index = 0 for pymod_element in self.pymod.root_element.get_children(): self._set_descendants_grid_indices(pymod_element) #-------------------------------------------- # Grids the widgets with their new indices. - #-------------------------------------------- for pymod_element in self.pymod.root_element.get_children(): self._grid_descendants(pymod_element, update_elements=update_elements) #--------------------------------------------- # Updates other components of the PyMod GUI. - #--------------------------------------------- if clear_selection: self.pymod.deselect_all_sequences() if update_menus: self.build_alignment_submenu() self.build_models_submenu() if self.pymod.DEVELOP: print("- Gridded. Row count id: %s. Row count seq: %s." % (self.central_widget.id_form_layout.rowCount(), self.central_widget.seq_form_layout.rowCount())) ################################################################# # Set elements grid indices. # ################################################################# def _set_descendants_grid_indices(self, pymod_element): if pymod_element.is_mother(): self.global_grid_column_index += 1 self._set_element_grid_indices(pymod_element) for child_element in pymod_element.get_children(): self._set_descendants_grid_indices(child_element) self.global_grid_column_index -= 1 else: self._set_element_grid_indices(pymod_element) def _set_element_grid_indices(self, pymod_element): pymod_element.widget_group.old_grid_row_index = pymod_element.widget_group.grid_row_index if pymod_element.widget_group.show: pymod_element.widget_group.grid_row_index = self.global_grid_row_index self.global_grid_row_index += 1 else: pymod_element.widget_group.grid_row_index = None ################################################################# # Grid widgets in the PyMod main window. # ################################################################# # Grid. def _grid_descendants(self, pymod_element, update_elements=False): # If the element is visible, grid it and update it (if necessary). if pymod_element.widget_group.show: # Shows/updates the widgets in PyMod main window. pymod_element.widget_group.grid_widgets(update_element_text=update_elements) # Proceed on to show the children of the element. if pymod_element.is_mother(): for child_element in pymod_element.get_children(): self._grid_descendants(child_element, update_elements=update_elements) # If the element is hidden, only update it. else: if update_elements: self._update_widgets_recursively(pymod_element) # Update hidden widgets. def _update_widgets_recursively(self, pymod_element): self.update_widgets(pymod_element) if pymod_element.is_mother(): for child_element in pymod_element.get_children(): self._update_widgets_recursively(child_element) def update_widgets(self, pymod_element): pymod_element_widgets_group = pymod_element.widget_group pymod_element_widgets_group.sequence_text.update_text() pymod_element_widgets_group.header_entry.update_title() # Hide. def delete_element_widgets(self, pymod_element): """ Remove the widgets of a PyMod element which has to be deleted. """ pymod_element.widget_group.hide_widgets(save_status=True) # self.hide_element_widgets(pymod_element) ############################################################################################### # Handle PyMod data. # ############################################################################################### def add_pymod_element_widgets(self, pymod_element): """ Add widgets a 'pymod_element'. They will be displayed by default at the bottom of the main window. """ pewp = PyMod_element_widgets_group_qt(main_window=self, pymod_element=pymod_element) pymod_element.widget_group = pewp ############################################################################################### # Key bindings. # ############################################################################################### def select_all_binding(self): self.pymod.select_all_sequences() def deselect_all_binding(self): self.pymod.deselect_all_sequences() def show_all_structures_binding(self): self.pymod.show_all_structures_from_main_menu() def hide_all_structures_binding(self): self.pymod.hide_all_structures_from_main_menu() #################################### # Move elements up and down by one # # position in PyMod main window. # #################################### def press_up_key_binding(self): self.move_elements_from_key_press("up") def press_down_key_binding(self): self.move_elements_from_key_press("down") def move_elements_from_key_press(self, direction): """ Move 'up' or 'down' by a single position the selected elements in PyMod main window. This is not an efficient implementation, but it works. It should be rewritten to make it faster. """ # Gets the elements to move. elements_to_move = self._get_elements_to_move() # Allow to move elements on the bottom of the list. if direction == "down": elements_to_move.reverse() # Temporarily adds 'None' elements to the list, so that multiple elements at the top or # bottom of container lists can be moved correctly. containers_set = set([e.mother for e in elements_to_move if not e.mother.selected]) # in elements_to_move for container in containers_set: container.list_of_children.append(None) container.list_of_children.insert(0, None) # Actually move the elements in their container lists. for element in elements_to_move: if not element.mother.selected: self.move_single_element(direction, element, element.mother.get_children()) # Remove the 'None' values added before. for container in containers_set: container.list_of_children = [e for e in container.list_of_children if e != None] # Shows the the elements in the new order. if elements_to_move != []: self.gridder(update_clusters=False, update_menus=False, update_elements=False) def _get_elements_to_move(self): elements_to_move = [] for e in self.pymod.get_selected_elements(): # If the element is lead of a collapsed cluster, in order to move it in PyMod main # window, its mother will have to be moved. if not e in elements_to_move: # Prevents children from being included two times. elements_to_move.append(e) return elements_to_move # list(set(elements_to_move)) def move_single_element(self, direction, element, container_list): """ Move 'up' or 'down' by a single position a single element in a list. """ change_index = 0 old_index = container_list.index(element) if direction == "up": change_index -= 1 elif direction == "down": # if old_index == len(container_list) - 1: # return None change_index += 1 self.pymod.change_pymod_element_list_index(element, old_index + change_index) def print_selected(self): ael = self.pymod.get_pymod_elements_list() sel = [i for i in ael if i.selected] print("\n# Selected elements: %s/%s." % (len(sel), len(ael))) for e in sel: print ("- %s. sel=%s; has_struct=%s." % (repr(e), e.selected, e.has_structure())) ################################################################# # Check status of clusters. # ################################################################# def is_lead_of_collapsed_cluster(self, pymod_element): return pymod_element.is_child() and pymod_element.is_lead() and pymod_element.mother.widget_group._collapsed_cluster def is_collapsed_cluster(self, pymod_cluster): return pymod_cluster.is_cluster() and pymod_cluster.widget_group._collapsed_cluster ############################################################################################### # Color sequences in the main window. # ############################################################################################### ################################################################# # Color the sequences and structures. # ################################################################# def color_selection(self, mode, target_selection, color_scheme, regular_color=None): """ Used to color a single sequence (and its structure) when "mode" is set to "single", to color mulitple sequences when "mode" is et to "multiple" or to color the list of the currently selected elements in the GUI if the mode is set to "selection". """ # Builds a list of elements to be colored. elements_to_color = [] if mode == "single": elements_to_color.append(target_selection) elif mode == "multiple": elements_to_color.extend(target_selection) elif mode == "selection": elements_to_color.extend(self.pymod.get_selected_sequences()) elif mode == "all": elements_to_color.extend(self.pymod.get_all_sequences()) # Actually proceeds to color the elements. selection_color_dict = {} for seq in elements_to_color: if color_scheme == "regular": self.color_element_by_regular_color(seq, regular_color) elif color_scheme == "polarity": color_dict = self.color_element_by_polarity(seq) elif color_scheme == "residue_type": color_dict = self.color_element_by_residue_type(seq) elif color_scheme == "secondary-observed": color_dict = self.color_element_by_obs_sec_str(seq) elif color_scheme == "secondary-predicted": color_dict = self.color_element_by_pred_sec_str(seq) # Colors elements with 3D structure according to the observed II str, elements with # predicted II str according to the prediction, and leaves the other elements unaltered. elif color_scheme == "secondary-auto": if seq.has_structure(): color_dict = self.color_element_by_obs_sec_str(seq) elif seq.has_predicted_secondary_structure(): color_dict = self.color_element_by_pred_sec_str(seq) elif color_scheme == "campo-scores": color_dict = self.color_element_by_campo_scores(seq) elif color_scheme == "entropy-scores": color_dict = self.color_element_by_entropy_scores(seq) elif color_scheme == "pair-conservation": color_dict = self.color_element_by_pc_scores(seq) elif color_scheme == "dope": color_dict = self.color_element_by_dope(seq) elif color_scheme == "domains": color_dict = self.color_element_by_domains(seq) elif color_scheme == "custom": color_dict = self.color_element_by_custom_scheme(seq) else: raise KeyError("Unknown color scheme: %s" % color_scheme) ########################## # Assigns color schemes. # ########################## def color_element_by_regular_color(self, element, color=None, color_structure=True): """ Colors sequence by "regular" colors, that is, colors uniformly the sequence with some color. """ element.color_by = "regular" if color != None: element.my_color = color return self.color_element(element, color_structure=color_structure) def color_element_by_polarity(self, element, color_structure=True): element.color_by = "polarity" return self.color_element(element, color_structure=color_structure) def color_element_by_residue_type(self, element, color_structure=True): element.color_by = "residue_type" return self.color_element(element, color_structure=color_structure) def color_element_by_obs_sec_str(self, element, color_structure=True): """ Color elements by their observed secondary structure. """ element.color_by = "secondary-observed" # If PyMOL has not been already used to assign sec str to this sequence. if not element.has_assigned_secondary_structure(): self.pymod.assign_secondary_structure(element) return self.color_element(element, color_structure=color_structure) def color_element_by_pred_sec_str(self, element, color_structure=True): """ Colors according by secondary structure predicted by PSIPRED. """ element.color_by = "secondary-predicted" return self.color_element(element, color_structure=color_structure) def color_element_by_campo_scores(self, element, color_structure=True): """ Color by CAMPO scores. """ element.color_by = "campo-scores" return self.color_element(element, color_structure=color_structure) def color_element_by_scr_scores(self, element, color_structure=True): """ Color by CAMPO scores. """ element.color_by = "scr-scores" return self.color_element(element, color_structure=color_structure) def color_element_by_entropy_scores(self, element, color_structure=True): """ Color by CAMPO scores. """ element.color_by = "entropy-scores" return self.color_element(element, color_structure=color_structure) def color_element_by_pc_scores(self, element, color_structure=True): """ Color by pair conservation scores. """ element.color_by = "pair-conservation" return self.color_element(element, color_structure=color_structure) def color_element_by_dope(self, element, color_structure=True): """ Color by DOPE scores. """ element.color_by = "dope" return self.color_element(element, color_structure=color_structure) def color_element_by_domains(self, element, color_structure=True): element.color_by = "domains" return self.color_element(element, color_structure=color_structure) def color_element_by_custom_scheme(self, element, color_structure=True, use_features=True, selected_feature=None): """ Color by a custom color scheme (each residue is colored differently). """ element.color_by = "custom" # Color by features. if use_features: # Show and color all the features of the element. if selected_feature is None: for feature in element.features["sequence"]: feature.show = True for res_idx, res in enumerate(element.get_polymer_residues()): res_features = res.features["sequence"] if res_features: # Sort the features by starting index, so that they can be colored properly. for res_feature in sorted(res_features, key=lambda f: f.start): res.custom_color = res_feature.color else: res.custom_color = res.get_default_color() # Show and color only the feature provided in the 'selected_feature' argument. else: selected_feature.show = True for res_idx, res in enumerate(element.get_polymer_residues()): res_features = res.features["sequence"] if res_features and selected_feature in res_features: res.custom_color = selected_feature.color else: res.custom_color = res.get_default_color() else: pass return self.color_element(element, color_structure=color_structure) ################################################# # Actually colors the sequences and structures. # ################################################# def color_element(self, element, color_structure=True): """ Colors the sequence entry when it is displayed by the 'gridder()' method or when the user changes the color scheme of a sequence. This can color also the PDB file of the element (if the element has one). """ if element.color_by != "custom": # Hide the features of the element. for feature in element.features["sequence"]: feature.show = False # Stores the color scheme, so that the sequence can be colored with it again when the # "custom" coloring scheme has been applied. element.store_current_color() # Assignes a color to each residue. get_residue_color_seq = self.assign_residue_coloring_method(element, "sequence") get_residue_color_str = self.assign_residue_coloring_method(element, "structure") for r in element.get_polymer_residues(): r.color_seq = get_residue_color_seq(r) r.color_str = get_residue_color_str(r) self.color_sequence_text(element) if color_structure and element.has_structure(): self.color_structure(element) ####################### # Coloring sequences. # ####################### def color_sequence_text(self, element): """ Colors the sequence entry in PyMod main window. """ element.widget_group.sequence_text.update_text() ######################## # Coloring structures. # ######################## color_all_atoms_schemes = ("campo-scores", "scr-scores", "entropy-scores", "pair-conservation") def color_structure(self, element, single_residue=False): """ Colors the PDB structure of an element loaded into PyMOL. """ chain_sel = element.get_pymol_selector() # Colors the structure according to some particular color scheme. if element.color_by != "regular": residues_to_color_dict = {} # Color residues one-by-one. Usually it it very slow in PyMOL. if single_residue: for res in element.get_polymer_residues(): color = res.color_str residue_sel = res.get_pymol_selector() cmd.color(color, residue_sel) # Color residues with the same color at the same time. Runs faster than the previous # method. else: for res in element.get_polymer_residues(): color = res.color_str # Gets the right color for the current residue. if color in residues_to_color_dict: residues_to_color_dict[color].append(res.db_index) else: residues_to_color_dict[color] = [res.db_index] for color in residues_to_color_dict: cmd.color(color, chain_sel + " and resi " + self._join_residues_list(residues_to_color_dict[color])) # Colors all the residues of a structure with the same color. else: cmd.color(self.get_regular_structure_color(element.my_color), chain_sel) if not element.color_by in self.color_all_atoms_schemes: cmd.util.cnc(chain_sel) # Colors by atom. #-------------------------------- # Compress PyMOL color strings. - #-------------------------------- compress_color_strings = True def _join_residues_list(self, residues_ids): joined_list = "+".join([str(i) for i in residues_ids]) if not self.compress_color_strings: return joined_list else: return self._compress_pymol_color_string(joined_list) def _compress_pymol_color_string(self, color_string): compressed_color_list = [] for i, n in enumerate(color_string.split("+")): if i == 0: compressed_color_list.append([int(n)]) else: if compressed_color_list[-1][-1] == int(n)-1: compressed_color_list[-1].append(int(n)) else: compressed_color_list.append([int(n)]) return "+".join([self._get_color_unit_string(e) for e in compressed_color_list]) def _get_color_unit_string(self, indices_list): if len(indices_list) == 1: return str(indices_list[0]) elif len(indices_list) == 2: return "%s-%s" % (indices_list[0], indices_list[-1]) elif len(indices_list) > 2: return "%s-%s" % (indices_list[0], indices_list[-1]) else: raise ValueError("Wrong 'indices_list' length: %s" % len(indices_list)) #################################### # Get the colors for the residues. # #################################### def assign_residue_coloring_method(self, element, color_target): if element.color_by == "polarity": if color_target == "sequence": return self.get_polarity_sequence_color elif color_target == "structure": return self.get_polarity_structure_color if element.color_by == "residue_type": if color_target == "sequence": return self.get_residue_type_sequence_color elif color_target == "structure": return self.get_residue_type_structure_color elif element.color_by == "secondary-observed": if color_target == "sequence": return self.get_observed_sec_str_sequence_color elif color_target == "structure": return self.get_observed_sec_str_structure_color elif element.color_by == "secondary-predicted": if color_target == "sequence": return self.get_predicted_sec_str_sequence_color elif color_target == "structure": return self.get_predicted_sec_str_structure_color elif element.color_by == "campo-scores": if color_target == "sequence": return self.get_campo_sequence_color elif color_target == "structure": return self.get_campo_structure_color elif element.color_by == "scr-scores": if color_target == "sequence": return self.get_scr_sequence_color elif color_target == "structure": return self.get_scr_structure_color elif element.color_by == "entropy-scores": if color_target == "sequence": return self.get_entropy_sequence_color elif color_target == "structure": return self.get_entropy_structure_color elif element.color_by == "pair-conservation": if color_target == "sequence": return self.get_pc_sequence_color elif color_target == "structure": return self.get_pc_structure_color elif element.color_by == "dope": if color_target == "sequence": return self.get_dope_sequence_color elif color_target == "structure": return self.get_dope_structure_color elif element.color_by == 'domains': if color_target == "sequence": return self.get_domain_sequence_color elif color_target == "structure": return self.get_domain_structure_color elif element.color_by == "custom": if color_target == "sequence": return self.get_custom_sequence_color elif color_target == "structure": return self.get_custom_structure_color elif element.color_by == "regular": if color_target == "sequence": return self._get_regular_sequence_color elif color_target == "structure": return self._get_regular_structure_color else: raise KeyError("Unknown coloring method: %s." % element.color_by) # Regular colors. def _get_regular_sequence_color(self, res): return self.get_regular_sequence_color(res.pymod_element.my_color) def _get_regular_structure_color(self, res): return self.get_regular_structure_color(res.pymod_element.my_color) def get_regular_sequence_color(self, color): return self.pymod.all_colors_dict_tkinter[color] def get_regular_structure_color(self, color): return color # Residue polarity colors. def get_polarity_sequence_color(self, residue): return self.pymod.all_colors_dict_tkinter.get(self.form_residue_polarity_color_name(residue), "#ffffff") def get_polarity_structure_color(self, residue): return self.form_residue_polarity_color_name(residue) def form_residue_polarity_color_name(self, residue): return "%s_%s" % (pmdt.pymol_polarity_color_name, residue.one_letter_code) # Residue type colors. def get_residue_type_sequence_color(self, residue): return self.pymod.all_colors_dict_tkinter.get(self.form_residue_type_color_name(residue), "#ffffff") def get_residue_type_structure_color(self, residue): return self.form_residue_type_color_name(residue) def form_residue_type_color_name(self, residue): return "%s_%s" % (pmdt.pymol_residue_type_color_name, residue.one_letter_code) # Observed secondary structure colors. def get_observed_sec_str_sequence_color(self, residue): return self.pymod.all_colors_dict_tkinter[self.form_observed_sec_str_color_name(residue)] def get_observed_sec_str_structure_color(self, residue): return self.form_observed_sec_str_color_name(residue) def form_observed_sec_str_color_name(self, residue): return "%s_%s" % (pmdt.pymol_obs_sec_str_name, residue.secondary_structure) # Predicted secondary structure colors. def get_predicted_sec_str_sequence_color(self, residue): return self.pymod.all_colors_dict_tkinter[self.form_predicted_sec_str_color_name(residue)] def get_predicted_sec_str_structure_color(self, residue): return self.form_predicted_sec_str_color_name(residue) def form_predicted_sec_str_color_name(self, residue): return "%s_%s_%s" % (pmdt.pymol_psipred_color_name, residue.psipred_result["confidence"], residue.psipred_result["sec-str-element"]) # CAMPO colors. def get_campo_sequence_color(self, residue): return self.pymod.all_colors_dict_tkinter[self.form_campo_color_name(residue)] def get_campo_structure_color(self, residue): return self.form_campo_color_name(residue) def form_campo_color_name(self, residue): return "%s_%s" % (pmdt.pymol_campo_color_name, residue.campo_score["interval"]) # SCR colors. def get_scr_sequence_color(self, residue): return self.pymod.all_colors_dict_tkinter[self.form_scr_color_name(residue)] def get_scr_structure_color(self, residue): return self.form_scr_color_name(residue) def form_scr_color_name(self, residue): return "%s_%s" % (pmdt.pymol_scr_color_name, residue.scr_score["interval"]) # Entropy scores. def get_entropy_sequence_color(self, residue): return self.pymod.all_colors_dict_tkinter[self.form_entropy_color_name(residue)] def get_entropy_structure_color(self, residue): return self.form_entropy_color_name(residue) def form_entropy_color_name(self, residue): return "%s_%s" % (pmdt.pymol_entropy_color_name, residue.entropy_score["interval"]) # Pair conservation colors. def get_pc_sequence_color(self, residue): return self.pymod.all_colors_dict_tkinter[self.form_pc_color_name(residue)] def get_pc_structure_color(self, residue): return self.form_pc_color_name(residue) def form_pc_color_name(self, residue): return "%s_%s" % (pmdt.pymol_pc_color_name, residue.pc_score) # DOPE colors. def get_dope_sequence_color(self, residue): return self.pymod.all_colors_dict_tkinter[self.form_dope_color_name(residue)] def get_dope_structure_color(self, residue): return self.form_dope_color_name(residue) def form_dope_color_name(self, residue): return "%s_%s" % (pmdt.pymol_dope_color_name, residue.dope_score["interval"]) # Custom colors. def get_custom_sequence_color(self, residue): return self.pymod.all_colors_dict_tkinter[self.form_custom_color_name(residue)] def get_custom_structure_color(self, residue): return self.form_custom_color_name(residue) def form_custom_color_name(self, residue): return residue.custom_color # Domains colors. def get_domain_sequence_color(self, residue): return self.pymod.all_colors_dict_tkinter[self.form_domain_color_name(residue)] def get_domain_structure_color(self, residue): return self.form_domain_color_name(residue) def form_domain_color_name(self, residue): res_domains = residue.features["domains"] if len(res_domains) == 0: return 'grey70' elif len(res_domains) == 1: return res_domains[0].domain_color[0] else: # More than one domain per residue. return 'teal' ################################################################# # Sequences font. # ################################################################# def update_font(self, new_font_type=None, new_font_size=None): """ Updates the font of the sequences displayed in the main window. Called from the 'Font Selection' menu items from the main window. """ if new_font_type: self.font = new_font_type if new_font_size: self.font_size = int(new_font_size) id_frame_stylesheet = "QLabel {font: %spt %s; font-weight: %s; color: white}" % (self.font_size, self.font, self.font_weight) self.central_widget.sequence_ID_groupbox.setStyleSheet(id_frame_stylesheet) seq_frame_stylesheet = "QLabel {font: %spt %s; font-weight: %s; color: white}" % (self.font_size, self.font, self.font_weight) self.central_widget.sequence_SEQ_groupbox.setStyleSheet(seq_frame_stylesheet) self.update_qt_font() def update_qt_font(self): """ Updates the font of the PyMod Qt main window. """ self.qfont = QtGui.QFont(self.font, self.font_size) self.fm = QtGui.QFontMetrics(self.qfont) ############################################################################################### # Messages. # ############################################################################################### def show_info_message(self, title_to_show, message_to_show, parent="auto"): _parent = self.pymod.get_qt_parent() if parent == "auto" else parent QtWidgets.QMessageBox.information(_parent, title_to_show, message_to_show) def show_warning_message(self, title_to_show, message_to_show, parent="auto"): _parent = self.pymod.get_qt_parent() if parent == "auto" else parent QtWidgets.QMessageBox.warning(_parent, title_to_show, message_to_show) def show_error_message(self, title_to_show, message_to_show, parent="auto"): _parent = self.pymod.get_qt_parent() if parent == "auto" else parent QtWidgets.QMessageBox.critical(_parent, title_to_show, message_to_show) class Centralwid(QtWidgets.QWidget): """ Central PyQt window with 2 (left and right) frames and a kind of status bar. """ def __init__(self, main_window): super().__init__() self.style = "background-color: rgb(0, 0, 0); color: rgb(255, 255, 255); font-weight: bold" self.main_window = main_window self.initUI() def initUI(self): #---------------------------- # Left frame (for headers). - #---------------------------- self.sequence_ID_groupbox = QtWidgets.QGroupBox('SEQUENCE ID') # self.sequence_ID_groupbox.setStyleSheet("QLabel {font: 14pt COURIER NEW font-weight: bold} ") id_frame_stylesheet = "QLabel {font: %spt %s; font-weight: %s; color: white}" % (self.main_window.font_size, self.main_window.font, self.main_window.font_weight) self.sequence_ID_groupbox.setStyleSheet(id_frame_stylesheet) self.id_form_layout = QtWidgets.QFormLayout() #self.left_scroll self.left_scroll = QtWidgets.QScrollArea() self.left_scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.left_scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.left_scroll.resize(200, 400) self.left_scroll.setWidget(self.sequence_ID_groupbox) # sequence_ID_groupbox dentro left_scroll area self.left_scroll.setWidgetResizable(True) #self.left_frame self.left_frame = QtWidgets.QFrame(self) self.left_frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.left_frame.resize(200, 400) self.left_frame.setStyleSheet(self.style) self.left_frame.setFrameShadow(QtWidgets.QFrame.Sunken) #self.left_frame_layout self.left_frame_layout = QtWidgets.QVBoxLayout(self) self.left_frame_layout.addWidget(self.left_scroll) self.left_frame.setLayout(self.left_frame_layout) # left_frame_layout dentro left_frame #------------------------------- # Right frame (for sequences). - #------------------------------- # This groupbox self.sequence_SEQ_groupbox = QtWidgets.QGroupBox('SEQUENCES') seq_frame_stylesheet = "QLabel {font: %spt %s; font-weight: %s; color: white}" % (self.main_window.font_size, self.main_window.font, self.main_window.font_weight) self.sequence_SEQ_groupbox.setStyleSheet(seq_frame_stylesheet) self.seq_form_layout = QtWidgets.QFormLayout() #self.right_scroll self.right_scroll = QtWidgets.QScrollArea() self.right_scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.right_scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.right_scroll.resize(900, 400) self.right_scroll.setWidget(self.sequence_SEQ_groupbox) # sequence_ID_groupbox dentro left_scroll area self.right_scroll.setWidgetResizable(True) #self.right_frame self.right_frame = QtWidgets.QFrame(self) self.right_frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.right_frame.resize(900, 400) self.right_frame.setStyleSheet(self.style) self.right_frame.setFrameShadow(QtWidgets.QFrame.Sunken) #self.right_frame_layout self.right_frame_layout = QtWidgets.QVBoxLayout(self) self.right_frame_layout.addWidget(self.right_scroll) self.right_frame.setLayout(self.right_frame_layout) # left_frame_layout dentro left_frame #connect the two Vertical Bars to move them togheter self.left_scroll.verticalScrollBar().valueChanged.connect(self.right_scroll.verticalScrollBar().setValue) self.right_scroll.verticalScrollBar().valueChanged.connect(self.left_scroll.verticalScrollBar().setValue) #---------------------------------- # Bottom part of the main window. - #---------------------------------- self.splitter1 = QtWidgets.QSplitter(QtCore.Qt.Horizontal) self.splitter1.addWidget(self.left_frame) self.splitter1.addWidget(self.right_frame) # creating sequence and position labels self.label_sequence = QtWidgets.QLabel(self) self.label_sequence.setText('Sequence:') self.label_sequence.setStyleSheet(small_font_style) self.textbox_sequence = QtWidgets.QLineEdit(self) self.textbox_sequence.setStyleSheet(self.style + "; " + small_font_style) self.textbox_sequence.setReadOnly(True) self.label_position = QtWidgets.QLabel(self) self.label_position.setText('Position:') self.label_position.setStyleSheet(small_font_style) self.textbox_position = QtWidgets.QLineEdit(self) self.textbox_position.setReadOnly(True) self.textbox_position.setStyleSheet(self.style + "; " + small_font_style) self.textbox_position.setMinimumWidth(675) # Width of the residues message bar width. # creating an horizontal layout with sequence and position labels self.text_layout = QtWidgets.QHBoxLayout() self.text_layout.addWidget(self.label_sequence) self.text_layout.addWidget(self.textbox_sequence) self.text_layout.addWidget(self.label_position) self.text_layout.addWidget(self.textbox_position) # creating a layout with sequence window and labels self.grid = QtWidgets.QVBoxLayout() self.grid.addWidget(self.splitter1) self.grid.addLayout(self.text_layout) self.setLayout(self.grid)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_gui/main_window/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_gui/main_window/_element_widgets_qt.py
.py
17,313
456
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module implementing the "widget group" class for a PyMod element. A "widget group" is a class which allows to control the "header entry" (a PyQT widget for the header of a PyMod element appearning in the left pane of the PyMod main window) and "sequence entry" (a PyQT widget for the sequence of a PyMod element appearning in the right pane of the PyMod main window). The use of a "widget group" class, allows to simultaneously control the objects for the "header entry" and "sequence entry". """ from pymol.Qt import QtCore from ._header_entry_qt import MyQLabel_header from ._sequence_text_qt import MyQLabel_sequence, Cluster_button class PyMod_element_widgets_group_qt(): """ Class for coordinating the widgets belonging to a PyMod element. Represent a group of widgets belonging to a PyMod element. """ unselected_color_dict = {True: "white", False: "red"} def __init__(self, main_window, pymod_element): self.pymod_element = pymod_element self.main_window = main_window self.pymod = self.main_window.pymod self.old_grid_row_index = None self.grid_row_index = None self.show = True self._collapsed_cluster = False #---------------------------- # Builds the header widget. - #---------------------------- self.header_entry = MyQLabel_header(parent_group=self) # By default widget are set as not visible. Visibility will be added in the 'gridder' method # of the PyMod main window. self.header_entry.setVisible(False) self.main_window.central_widget.id_form_layout.addRow(self.header_entry) #----------------------------------- # Builds the sequence text widget. - #----------------------------------- self.sequence_text = MyQLabel_sequence(parent_group=self) self.sequence_text.setVisible(False) self._show_sequence_text = True # Actually not used. #--------------------------------- # Button and signs for clusters. - #--------------------------------- self._cluster_button_state = True self.cluster_button = Cluster_button(parent_group=self) self.cluster_button.setVisible(False) self.main_window.central_widget.seq_form_layout.addRow(self.cluster_button, self.sequence_text) ############################################################################################### # Display widgets. # ############################################################################################### #----------------------- # Control all widgets. - #----------------------- def grid_widgets(self, update_element_text=False): """ Called only by the 'gridder' method. """ # Shows the left pane widgets. self.grid_header(update_element_header=update_element_text) # Updates and shows the right pane widgets: adds the sequence of the element and its cluster # button/sign if present. self.grid_sequence(update_element_text=update_element_text) def hide_widgets(self, save_status=True): """ Called by several methods. """ if save_status: self.show = False self.hide_header() self.hide_sequence(save_status=save_status) #---------- # Header. - #---------- def grid_header(self, update_element_header=False): if update_element_header: self.header_entry.update_title() if self.old_grid_row_index != self.grid_row_index: form_layout = self.main_window.central_widget.id_form_layout i1 = form_layout.itemAt(self.grid_row_index, form_layout.SpanningRole) if i1 is not None: if not i1.widget() is self.header_entry: self.main_window.central_widget.id_form_layout.removeItem(i1) i1.widget().setVisible(False) self.main_window.central_widget.id_form_layout.removeWidget(self.header_entry) form_layout.setWidget(self.grid_row_index, form_layout.SpanningRole, self.header_entry) if not self.header_entry.isVisible(): self.header_entry.setVisible(True) def hide_header(self): if self.header_entry.isVisible(): self.header_entry.setVisible(False) #--------------------------------- # Cluster button and child sign. - #--------------------------------- def change_cluster_button_on_expand(self): self.cluster_button.setText('-') self._cluster_button_state = True if self.pymod_element.is_cluster(): self._collapsed_cluster = False def change_cluster_button_on_collapse(self): self.cluster_button.setText('+') self._cluster_button_state = False if self.pymod_element.is_cluster(): self._collapsed_cluster = True #----------------- # Sequence text. - #----------------- def grid_sequence(self, update_element_text=False, save_status=False): if save_status: self._show_sequence_text = True if update_element_text: self.sequence_text.update_text() # Change the widget position only if its 'grid_row_index' has changed. if self.old_grid_row_index != self.grid_row_index: form_layout = self.main_window.central_widget.seq_form_layout # Get the sequence widget present in the row in which the current widget has to be placed. i1 = form_layout.itemAt(self.grid_row_index, form_layout.FieldRole) # If there is a widget in the target positio, it will be removed to make place for the # current widget. if i1 is not None: # if not i1.widget() is self.sequence_text: # Remove the target sequence widget. i1.widget().setVisible(False) # TODO is this needed? self.main_window.central_widget.seq_form_layout.removeItem(i1) # Remove the current sequence widget. self.main_window.central_widget.seq_form_layout.removeWidget(self.sequence_text) # Cluster buttons. i2 = form_layout.itemAt(self.grid_row_index, form_layout.LabelRole) # Remove the target cluster button widget. i2.widget().setVisible(False) # TODO is this needed? self.main_window.central_widget.seq_form_layout.removeItem(i2) # Remove the current cluster button widget. self.main_window.central_widget.seq_form_layout.removeWidget(self.cluster_button) # Sets the current widgets. form_layout.setWidget(self.grid_row_index, form_layout.FieldRole, self.sequence_text) form_layout.setWidget(self.grid_row_index, form_layout.LabelRole, self.cluster_button) # Show the current widgets. if not self.sequence_text.isVisible(): if not self.pymod_element.is_cluster(): self.sequence_text.setVisible(True) else: self.sequence_text.setVisible(not self._collapsed_cluster) else: if self.pymod_element.is_cluster() and self._collapsed_cluster: self.sequence_text.setVisible(False) if not self.cluster_button.isVisible(): self.cluster_button.set_visibility() def hide_sequence(self, save_status=True): if save_status: self._show_sequence_text = False if self.sequence_text.isVisible(): self.sequence_text.setVisible(False) if self.cluster_button.isVisible(): self.cluster_button.setVisible(False) ############################################################################################### # Selection of elements in the PyMod main window. # ############################################################################################### def toggle_element(self): """ Toggles elements selection state. """ if self.pymod_element.selected: # Inactivate. self.deselect_element() else: # Activate. self.select_element() def deselect_element(self, deselect_all=False): """ Deselects an element. The 'deselect_all' should be set to 'True' only when deselecting all elements from PyMod main menu. """ if not deselect_all: self._deselect_recursively() if self.pymod_element.is_child(): self._deselect_ancestry_recursively(is_in_cluster=True) self._color_headers_on_toggle() else: self._turn_selection_off() def select_element(self, select_all=False): """ Selects an element. """ if not select_all: self._select_recursively() if self.pymod_element.is_child(): self._select_ancestry_recursively(is_in_cluster=True) self._color_headers_on_toggle() else: self._turn_selection_on() def select_collapsed_cluster_descendants(self): for descendant in self.pymod_element.get_descendants() + [self.pymod_element]: descendant.widget_group.select_element(select_all=True) def _deselect_recursively(self, is_in_cluster=False): """ Deselect an element and all its children recursively. """ self._turn_selection_off(is_in_cluster) if self.pymod_element.is_mother(): for c in self.pymod_element.get_children(): c.widget_group._deselect_recursively(is_in_cluster) def _select_recursively(self, is_in_cluster=False): """ Select an element and all its children recursively. """ self._turn_selection_on(is_in_cluster) if self.pymod_element.is_mother(): for c in self.pymod_element.get_children(): c.widget_group._select_recursively(is_in_cluster) def _deselect_ancestry_recursively(self, is_in_cluster=False): """ Deselects the ancestry an element (that is, its mother and its mother's mother, and so on recursively). """ if not self.pymod_element.is_child(): return None mother = self.pymod_element.mother # Modify the mother and the siblings according to what happens to the children. if mother.selected: mother.widget_group._turn_selection_off(is_in_cluster=True) if mother.is_child(): mother.widget_group._deselect_ancestry_recursively(is_in_cluster=True) def _select_ancestry_recursively(self, is_in_cluster=False): """ Selects the ancestry of an element recursively. """ # If the mother is not selected and if by selecting this child, all the children # are selected, also selects the mother. if not self.pymod_element.is_child(): return None child = self.pymod_element mother = self.pymod_element.mother if not mother.selected: # If it is the last inactivated children in the cluster, by selecting it, all the # elements in the cluster will be selected and the mother will also be selected. siblings = child.get_siblings() if not False in [c.selected for c in siblings]: mother.widget_group._turn_selection_on() if mother.is_child(): mother.widget_group._select_ancestry_recursively(is_in_cluster=False) def _set_header_color(self, color): self.header_entry.setStyleSheet("color: %s" % color) def _turn_selection_on(self, is_in_cluster=False): """ Selects an element. """ self.pymod_element.selected = True self._set_header_color("green") def _turn_selection_off(self, is_in_cluster=False): """ Deselects an element. """ self.pymod_element.selected = False self._set_header_color("red") def _color_headers_on_toggle(self): """ Adjust the color of unselected headers in a cluster. """ is_in_cluster = False ancestor = self.pymod_element.get_ancestor() if ancestor and not ancestor.selected: descendants = ancestor.get_descendants() for d in descendants: if d.selected: is_in_cluster = True break # Descendants. for d in descendants: if not d.selected: d.widget_group._set_header_color(self.unselected_color_dict[is_in_cluster]) # Ancestor. ancestor.widget_group._set_header_color(self.unselected_color_dict[is_in_cluster]) ############################################################################################### # Control clusters. # ############################################################################################### #------------------------- # Cluster button events. - #------------------------- def cluster_button_click(self, event): """ Creates the mouse event for clicking cluster buttons. It is used to toggle the children of the cluster. """ if self._cluster_button_state: self.collapse_cluster() else: self.expand_cluster() def _toggle_cluster_click(self, cluster_lead_action, cluster_element_action): pymod_cluster = self.pymod_element cluster_lead = pymod_cluster.get_lead() # If the cluster has a cluster lead. if cluster_lead: cluster_lead_action(cluster_lead) cluster_element_action(pymod_cluster) #-------------------------------- # Expand and collapse clusters. - #-------------------------------- # Expand. def expand_cluster(self): self._toggle_cluster_click(self._expand_cluster_lead, self._expand_cluster_element) def _expand_cluster_element(self, pymod_cluster): pymod_cluster_widgets_group = pymod_cluster.widget_group pymod_cluster_widgets_group.change_cluster_button_on_expand() # Shows the text of the collapsed cluster. pymod_cluster_widgets_group.grid_sequence(update_element_text=True, save_status=True) # Show the children of the collapsed cluster. for child in pymod_cluster.get_children(): self._show_descendants(child) self.main_window.gridder(clear_selection=False, update_clusters=True, update_menus=False, update_elements=False) def _expand_cluster_lead(self, cluster_lead): pass def _show_descendants(self, pymod_element): pymod_element_widgets_group = pymod_element.widget_group if pymod_element.is_cluster(): # If the element is not a collapsed cluster, then show it and all its children. if not pymod_element_widgets_group._collapsed_cluster: pymod_element_widgets_group.show = True for child in pymod_element.get_children(): self._show_descendants(child) # If the element is a collapsed cluster. else: pass else: pymod_element_widgets_group.show = True # Collapse. def collapse_cluster(self): self._toggle_cluster_click(self._collapse_cluster_lead, self._collapse_cluster_element) def _collapse_cluster_element(self, pymod_cluster): pymod_cluster_widgets_group = pymod_cluster.widget_group pymod_cluster_widgets_group.change_cluster_button_on_collapse() # Hide the cluster element sequence. pymod_cluster_widgets_group.hide_sequence() # Hide all the descendants widgets. for child in pymod_cluster.get_descendants(): child.widget_group.hide_widgets() self.main_window.gridder(clear_selection=False, update_clusters=True, update_menus=False, update_elements=False) def _collapse_cluster_lead(self, cluster_lead): pass ############################################################################################### # Check coloring schemes. # ############################################################################################### def can_be_colored_by_secondary_structure(self): """ Returns 'True' if the element has an associated structure or has a secondary structure prediction. """ return self.pymod_element.has_structure() or self.pymod_element.has_predicted_secondary_structure()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_gui/main_window/aqua/qsshelper.py
.py
921
27
import os import re class QSSHelper: def __init__(self): pass @staticmethod def open_qss(path): """ opens a Qt stylesheet with a path relative to the project Note: it changes the urls in the Qt stylesheet (in memory), and makes these urls relative to the project Warning: the urls in the Qt stylesheet should have the forward slash ('/') as the pathname separator """ with open(path) as f: qss = f.read() pattern = r'url\((.*?)\);' for url in sorted(set(re.findall(pattern, qss)), key=len, reverse=True): directory, basename = os.path.split(path) new_url = os.path.join(directory, *url.split('/')) new_url = os.path.normpath(new_url) new_url = new_url.replace(os.path.sep, '/') qss = qss.replace(url, new_url) return qss
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_gui/main_window/aqua/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pymod_plot_qt.py
.py
41,762
1,014
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module for a PyQt window with plots built with the pyqtgraph library (http://www.pyqtgraph.org/). NumPy and pyqtgraph are required. The PyMod plugin package integrates a modified version of pyqtgraph (which can be imported through 'import pymod_lib.pymod_plot.pyqtgraph'). This version includes a series of modifications to make pyqtgraph compatible with the current PyMOL versions (see the comment lines starting with "PYMOD FIX" in the package). """ import io import math import numpy as np from pymol.Qt import QtWidgets, QtCore, QtGui from pymod_lib.pymod_plot import pyqtgraph from pymod_lib.pymod_gui.shared_gui_components_qt import asksaveasfile_qt, small_font_style from pymod_lib.pymod_os_specific import check_valid_pyqt ############################################################################### # Plotting window in Pyqt for PyMod, using pyqtgraph. # ############################################################################### class PyMod_plot_window_qt(QtWidgets.QMainWindow): """ Class for a PyQt window with a plot built using the pyqtgraph library and a series of widgets to control the plot and interact with it. """ is_pymod_window = True #--------------------------------- # Configure the plotting window. - #--------------------------------- control_colors = "black" plot_colors = ["#0000ff", "#00ff00", "#ff0000", "#00ffff", "#ff00ff", "#ffff00", "#000000", "#cccccc"] def __init__(self, *args, **kwargs): super(PyMod_plot_window_qt, self).__init__(*args, **kwargs) # Central widget. self.central_widget = QtWidgets.QWidget() self.setCentralWidget(self.central_widget) self.central_widget_layout = QtWidgets.QGridLayout() self.central_widget.setLayout(self.central_widget_layout) #------------------------------------------------ # Upper frame (contains the plot and controls). - #------------------------------------------------ expanding_size_policy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) preferred_size_policy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) # The upper frame contains three frames: info, plot and controls frames. # The infor and controls frames will be displayed only if the 'use_controls' # argument is set to 'True' when calling the 'build_plotting_area' method. self.upper_frame = QtWidgets.QFrame() self.upper_frame.setStyleSheet("background-color: #646464") self.upper_frame_layout = QtWidgets.QGridLayout() self.upper_frame.setLayout(self.upper_frame_layout) self.upper_frame.setSizePolicy(expanding_size_policy) self.central_widget_layout.addWidget(self.upper_frame, 0, 0) # Info frame, it contains the messagebar of the plot. self.info_frame = QtWidgets.QFrame() self.info_frame_layout = QtWidgets.QHBoxLayout() self.info_frame.setLayout(self.info_frame_layout) self.info_frame.setSizePolicy(preferred_size_policy) self.info_label = QtWidgets.QLabel("") self.info_frame_layout.addWidget(self.info_label) # Plot frame. self.plot_frame = QtWidgets.QFrame() # self.plot_frame.setStyleSheet("background-color: red") self.plot_frame_layout = QtWidgets.QGridLayout() self.plot_frame.setLayout(self.plot_frame_layout) self.plot_frame.setSizePolicy(expanding_size_policy) self.build_plot_widget() # Controls frame. self.controls_frame = QtWidgets.QWidget() self.controls_frame.setStyleSheet("background-color: #747474") self.controls_frame_layout = QtWidgets.QGridLayout() self.controls_frame.setLayout(self.controls_frame_layout) self.controls_frame_layout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) self.controls_scrollarea = QtWidgets.QScrollArea() self.controls_scrollarea.setWidgetResizable(True) self.controls_scrollarea.setWidget(self.controls_frame) self.labels_title = QtWidgets.QLabel("Plots list") # Middle splitter. self.middle_splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal) self.middle_splitter.setSizePolicy(expanding_size_policy) #--------------------------------------- # Lower frame (contains some options). - #--------------------------------------- self.lower_frame = QtWidgets.QFrame() self.lower_frame_layout = QtWidgets.QGridLayout() self.lower_frame.setLayout(self.lower_frame_layout) self.central_widget_layout.addWidget(self.lower_frame, 1, 0) # View buttons. self.view_label = QtWidgets.QLabel("View:") self.lower_frame_layout.addWidget(self.view_label, 0, 0) self.home_view_button = QtWidgets.QPushButton("Fit to data") self.home_view_button.clicked.connect(self.on_home_button_click) self.lower_frame_layout.addWidget(self.home_view_button, 0, 1) # On click behaviour. The buttons will be shown later, in the # 'build_plotting_area' metohd. self.interact_buttons_group = QtWidgets.QButtonGroup() self.on_click_label = QtWidgets.QLabel("Interact on click:") self.interact_button = QtWidgets.QPushButton("Yes") self.interact_button.setCheckable(True) self.interact_buttons_group.addButton(self.interact_button) self.interact_button.clicked.connect(self.on_interact_button_click) self.no_interaction_button = QtWidgets.QPushButton("No") self.no_interaction_button.setCheckable(True) self.no_interaction_button.setChecked(True) self.interact_buttons_group.addButton(self.no_interaction_button) self.no_interaction_button.clicked.connect(self.on_no_interaction_button_click) # Show/hide all buttons. They will be shown later, in the 'build_plotting_area' # method. self.show_label = QtWidgets.QLabel("Show:") self.show_all_button = QtWidgets.QPushButton("All") self.show_all_button.clicked.connect(self.show_all_command) self.hide_all_button = QtWidgets.QPushButton("None") self.hide_all_button.clicked.connect(self.hide_all_command) self.lower_frame_layout.setAlignment(QtCore.Qt.AlignLeft) #--------------------- # Build a main menu. - #--------------------- self.save_to_csv_action = QtWidgets.QAction('Save to CSV', self) self.save_to_csv_action.triggered.connect(lambda a=None: self.save_to_csv_event()) self.save_to_png_action = QtWidgets.QAction('Save to PNG', self) self.save_to_png_action.triggered.connect(lambda a=None: self.save_to_png_event()) self.main_menubar = self.menuBar() self.file_menu = self.main_menubar.addMenu('File') def build_plot_widget(self): """ Build and configure the PlotWidget of the plotting window. """ self.plot_count = 0 self.plot_items = {} self.plot_color_index = 0 self.interact_mode = False self.selected_plot_item = None self.previous_highlight_dot = None self.previous_highlight_plot_id = None self.all_points = [] self.all_points_info = [] # PlotWidget from pyqtgraph. self.graphWidget = pyqtgraph.PlotWidget() # Configure the PlotWidget. self.graphWidget.setBackground('w') # self.graphWidget.setForeground(self.control_colors) self.graphWidget.hideButtons() self.plot_frame_layout.addWidget(self.graphWidget, 0, 0) def initialize(self, pymod, title): self.pymod = pymod self.setWindowTitle(title) #---------------------------------------------------------------- # Configure the plotting area, add plots and iteract with them. - #---------------------------------------------------------------- def build_plotting_area(self, use_controls=True, use_all_controls_buttons=True, messagebar_initial_text=None, update_messagebar=False, messagebar_text_on_update="", messagebar_vars_on_update=(), on_click_action=None, x_label_text="x", y_label_text="y", label_size=None, use_save_to_csv=True, hide_x_ticks=False, hide_y_ticks=False, # hide_x_label=False, # hide_y_label=False, highlight_points=True, ): """ Configures the plotting area of the window. # Arguments use_controls: adds to the plotting window a right column with checkbuttons to show/hide the lines plots in the drawing area. use_all_controls_buttons: adds to the plotting control column 'Show All' and 'Hide All' buttons. messagebar_initial_text: initial text to be displayed in the messagebar of the plotting window. update_messagebar: if 'True', the messagebar will be updated when clicking some point of the scatterplots. messagebar_text_on_update: text to be shown when the messagebar is update. If it contains the "__plot_name__", "__x__", "__y__" string, they will be substituted with the name of the plot, the x value and y value of the point respectively. If some 'additional_data' is provided for a plot, its data will also be used to update the messagebar. Each element of an 'additional_data' list has to correspond to a data point of a plot and must be a dictionary in which the keys are strings representing the names of the additional data series. If, for example, these dictionaries have a key named 'info' and if the 'messagebar_text_on_update' contains the string "__info__", it will be substituted with the value associated to the 'info' key of that 'additional_data' point. on_click_action: function to be called when a point of a scatterplot is clicked. This function must have the following argument: point_data: a dictionary with additional data for the point or a 'None' value. x_label_text: text for the x-axis label. y_label_text: text for the y-axis label. label_size: font size for the axis labels. use_save_to_csv: if 'True' add to the plotting window menu a command to save data in the csv format. hide_x_ticks: if 'True', hide the ticks and numbers of the x-axis. hide_y_ticks: if 'True', hide the ticks and numbers of the y-axis. highlight_points: if 'True', the scatterplot points will be highlighted when they are clicked with the mouse. """ # Stores the arguments. self.use_controls = use_controls if self.use_controls: self.upper_frame_layout.addWidget(self.info_frame, 0, 0) self.middle_splitter.addWidget(self.plot_frame) self.middle_splitter.addWidget(self.controls_scrollarea) self.upper_frame_layout.addWidget(self.middle_splitter, 1, 0) self.controls_scrollarea.resize(230, self.controls_scrollarea.sizeHint().height()) self.controls_frame_layout.addWidget(self.labels_title, 0, 0, 1, 2) self.lower_frame_layout.addWidget(self.on_click_label, 0, 2) self.lower_frame_layout.addWidget(self.interact_button, 0, 3) self.lower_frame_layout.addWidget(self.no_interaction_button, 0, 4) else: self.upper_frame_layout.addWidget(self.plot_frame, 0, 0) self.use_all_controls_buttons = use_all_controls_buttons if self.use_controls and self.use_all_controls_buttons: self.lower_frame_layout.addWidget(self.show_label, 0, 5) self.lower_frame_layout.addWidget(self.show_all_button, 0, 6) self.lower_frame_layout.addWidget(self.hide_all_button, 0, 7) self.messagebar_initial_text = messagebar_initial_text if self.messagebar_initial_text is not None: self.info_label.setText(self.messagebar_initial_text) self.update_messagebar = update_messagebar self.on_click_action = on_click_action if self.on_click_action is not None: if not hasattr(self.on_click_action, "__call__"): raise TypeError("'on_click_action' must be a function.") self.messagebar_text_on_update = messagebar_text_on_update self.messagebar_vars_on_update = messagebar_vars_on_update self.use_save_to_csv = use_save_to_csv if self.use_save_to_csv: self.file_menu.addAction(self.save_to_csv_action) self.file_menu.addAction(self.save_to_png_action) self.highlight_points = highlight_points # Configure the PlotWidget. self.graphWidget.setMenuEnabled(False) if label_size is not None: kwargs = {"font-size": "%spx" % label_size} font = QtGui.QFont() font.setPixelSize(label_size) # curve_pen = pyqtgraph.mkPen(width=2, color="r") # Color and width of the curve. else: kwargs = {} self.graphWidget.setLabel("left", y_label_text, **kwargs) self.graphWidget.setLabel("bottom", x_label_text, **kwargs) if label_size is not None: self.graphWidget.getAxis("left").tickFont = font self.graphWidget.getAxis("bottom").tickFont = font # self.graphWidget.getAxis("left").setPen(curve_pen) if hide_x_ticks: self.graphWidget.getAxis("bottom").setStyle(showValues=False, tickLength=0) if hide_y_ticks: self.graphWidget.getAxis("left").setStyle(showValues=False, tickLength=0) if self.on_click_action is not None: self.graphWidget.getViewBox().scene().sigMouseClicked.connect(self.on_scene_click) def on_scene_click(self, event): """ Called whenever clicking on some region of the plot. """ if not self.interact_mode: return None plot_point = self.graphWidget.getViewBox().mapSceneToView(event.scenePos()) if hasattr(self.selected_plot_item, "_pymod_id"): self.on_point_click(plot_point) self.selected_plot_item = None def on_curve_click(self, item): """ Sets the currently highlighted curve. """ self.selected_plot_item = item def on_point_click(self, plot_point): """ Called when a scatterplot point is clicked on the graph. If 'update_messagebar' if set to 'True', the messagebar will be updated. If an 'on_click_action' was provided, this function will also be executed. """ if not self.interact_mode: return None plot_point_xy = (plot_point.x(), plot_point.y()) min_dist = get_point_dist(self.all_points[0], plot_point_xy) min_id = 0 for i, pi in enumerate(self.all_points): di = get_point_dist(pi, plot_point_xy) if di < min_dist: min_dist = di min_id = i plot_id, point_id = self.all_points_info[min_id] # Gets the data coordinates of the point. x_data = self.plot_items[plot_id]["x_data"][point_id] y_data = self.plot_items[plot_id]["y_data"][point_id] # Shows a circle around the selected point on the curve. if self.previous_highlight_dot is not None: self.graphWidget.removeItem(self.previous_highlight_dot) self.previous_highlight_dot = self.graphWidget.plot([x_data], [y_data], symbol="o", symbolSize=12, symbolBrush="y") self.previous_highlight_plot_id = plot_id # Updates the message bar in the upper part of the plotting window. if self.update_messagebar: # Label of the plot. plot_label = self.plot_items[plot_id]["label"] # Build the new message. updated_text = self.messagebar_text_on_update.replace("__plot_name__", plot_label) updated_text = updated_text.replace("__x__", str(x_data)) updated_text = updated_text.replace("__y__", str(y_data)) # Additional data. plot_additional_data = self.plot_items[plot_id]["additional_data"] if plot_additional_data is not None: point_additional_data = plot_additional_data[point_id] for data_key in point_additional_data: updated_text = updated_text.replace("__%s__" % data_key, str(point_additional_data[data_key])) else: point_additional_data = None # Set the new message. self.info_label.setText(updated_text) # Calls the custom function. if self.on_click_action is not None: self.on_click_action(point_additional_data) def add_plot(self, x_data, y_data, label=None, additional_data=None): """ Adds a plot to the pyqtgraph PlotWidget. """ # Check and prepare the data. if len(x_data) != len(y_data): raise ValueError(("The x series and the y series do not have the same" " number of elements (%s and %s respectively)" % (len(x_data), len(y_data)))) if additional_data: if not len(x_data) == len(additional_data): raise ValueError(("The 'additional_data' series does not have the" " same number of elements of the data to plot" " (%s and %s respectively)" % (len(x_data), len(additional_data)))) _x_data, _y_data = self.remove_none(x_data, y_data) # Add the plot to the PlotWidget. plot_color = self.plot_colors[self.plot_color_index] self.change_plot_color_index() curve_pen = pyqtgraph.mkPen(width=2, color=plot_color) # Color and width of the curve. plot_item = self.graphWidget.plot(_x_data, _y_data, name=label, connect="finite", pen=curve_pen, clickable=True) plot_item._pymod_id = self.plot_count plot_item.curve._pymod_id = self.plot_count plot_item.curve.setClickable(True) # plot_item.curve.sigClicked.connect(self.on_curve_click) plot_item.sigClicked.connect(self.on_curve_click) # Store information about the plot. self.plot_items[self.plot_count] = {} # The 'plot' key will store the pyqtgraph object for the plot. self.plot_items[self.plot_count]["plot"] = plot_item # The 'state' will be 1 if the plot is shown, and 0 it is hidden. self.plot_items[self.plot_count]["state"] = 1 # Add a label. if label is None: label = "Plot %s" % self.plot_count self.plot_items[self.plot_count]["label"] = label # Data. self.plot_items[self.plot_count]["x_data"] = x_data self.plot_items[self.plot_count]["y_data"] = y_data # Additional data. self.plot_items[self.plot_count]["additional_data"] = additional_data # Stores all the data in a single list. for idx, (xi, yi) in enumerate(zip(x_data, y_data)): if yi is not None: self.all_points.append((xi, yi)) self.all_points_info.append((self.plot_count, idx)) # Add a checkbox in the controls frame. Used for showing/hiding the plot. if self.use_controls: plot_checkbox = QtWidgets.QCheckBox(label) plot_checkbox.setStyleSheet(small_font_style) plot_checkbox.setChecked(True) plot_checkbox.clicked.connect(lambda a=None, i=self.plot_count: self.toggle_plot(i)) plot_color_label = QtWidgets.QLabel("---") # \u2796") # "\u25CF" plot_color_label.setStyleSheet("color: %s; font-weight: bold" % plot_color) self.controls_frame_layout.addWidget(plot_color_label, self.plot_count+1, 0, 1, 1) self.controls_frame_layout.addWidget(plot_checkbox, self.plot_count+1, 1, 1, 1) self.plot_items[self.plot_count]["checkbox"] = plot_checkbox # Increase the plot counter. self.plot_count += 1 def change_plot_color_index(self): if self.plot_color_index == len(self.plot_colors) - 1: self.plot_color_index = 0 else: self.plot_color_index += 1 def remove_none(self, x_values, y_values): """ Used to remove 'None' values for a data series ('None' values are not supported by pyqtgraph, which supports numpy nan values instead). """ _x_values = [] _y_values = [] has_valid_pyqt = check_valid_pyqt() # nan values are supported by PyQt. if has_valid_pyqt: for xi, yi in zip(x_values, y_values): if yi is None: _y_values.append(np.nan) else: _y_values.append(yi) _x_values.append(xi) # nan values are not supported by PyQt. else: for xi, yi in zip(x_values, y_values): if yi is None: pass else: _x_values.append(xi) _y_values.append(yi) return _x_values, _y_values def toggle_plot(self, plot_idx): """ Called when clicking on some checkbox on the control frame on the right of the plotting window. """ plot_info = self.plot_items[plot_idx] if plot_info["state"] == 1: self.graphWidget.removeItem(plot_info["plot"]) plot_info["state"] = 0 if self.previous_highlight_plot_id == plot_idx: self.remove_highlight_dot() else: self.graphWidget.addItem(plot_info["plot"]) plot_info["state"] = 1 def remove_highlight_dot(self): self.graphWidget.removeItem(self.previous_highlight_dot) self.previous_highlight_dot = None self.previous_highlight_plot_id = None #---------------------------------------------------------------- # Events called when pressing the control buttons of the window.- #---------------------------------------------------------------- def on_home_button_click(self): self.graphWidget.autoBtnClicked() def on_interact_button_click(self): self.interact_mode = True def on_no_interaction_button_click(self): if self.previous_highlight_plot_id is not None: self.remove_highlight_dot() self.interact_mode = False def show_all_command(self): for plot_idx in self.plot_items: plot_info = self.plot_items[plot_idx] if plot_info["state"] == 0: self.graphWidget.addItem(plot_info["plot"]) plot_info["state"] = 1 plot_info["checkbox"].setChecked(True) def hide_all_command(self): for plot_idx in self.plot_items: plot_info = self.plot_items[plot_idx] if plot_info["state"] == 1: self.graphWidget.removeItem(plot_info["plot"]) plot_info["state"] = 0 plot_info["checkbox"].setChecked(False) if self.previous_highlight_plot_id == plot_idx: self.remove_highlight_dot() #----------------------- # Save to file events. - #----------------------- def save_to_csv_event(self): output_filepath = asksaveasfile_qt("Save to CSV file", parent=self.pymod.get_qt_parent(), name_filter="*.csv") if not output_filepath: return None try: self._save_to_csv_file(output_filepath) except Exception as e: print("- WARNING: could not write a csv file: %s" % str(e)) def _save_to_csv_file(self, output_filepath): output = io.StringIO() # Writes the header string. header_string = [] for plot_idx in range(self.plot_count): header_string.append(self.plot_items[plot_idx]["label"]) header_string.append(self.plot_items[plot_idx]["label"] + " info") header_string = ",".join(header_string) print(header_string, file=output) # Write each data point information. max_points_count = max([len(self.plot_items[idx]["x_data"]) for idx in range(self.plot_count)]) for point_i in range(0, max_points_count): line_string = [] for plot_idx in range(self.plot_count): try: # Get the y value. point_y = self.plot_items[plot_idx]["y_data"][point_i] point_val = str(point_y) if point_y is not None else "" # Get the additional data for the point. adata = self.plot_items[plot_idx]["additional_data"] point_additional_data = "" if adata is not None: point_adata = self.plot_items[plot_idx]["additional_data"][point_i] if "export_label" in point_adata: if point_adata["export_label"] != None: point_additional_data = str(point_adata["export_label"]) line_string.extend([point_val, point_additional_data]) except IndexError: line_string.extend(["", ""]) line_string = ",".join(line_string) print(line_string, file=output) contents = output.getvalue() output.close() output_file_handler = open(output_filepath, "w") print(contents, file=output_file_handler) output_file_handler.close() def save_to_png_event(self): output_filepath = asksaveasfile_qt("Save to PNG file", parent=self.pymod.get_qt_parent(), name_filter="*.png") if not output_filepath: return None try: from pymod_lib.pymod_plot.pyqtgraph.exporters import ImageExporter # Create an exporter instance, as an argument give it the whole plot. exporter = ImageExporter(self.graphWidget.plotItem) # Save to file. exporter.export(output_filepath) except Exception as e: print("- WARNING: could not write a pgn file: %s" % str(e)) def get_point_dist(point_i, point_j): return math.sqrt((point_i[0]-point_j[0])**2 + (point_i[1]-point_j[1])**2) ############################################################################### # Builds a plot showing a distance tree. # ############################################################################### # The following code has been adapted from the 'draw' method of the 'Phylo' module # of Biopython. # Copyright (C) 2009 by Eric Talevich (eric.talevich@gmail.com) ''' Biopython License Agreement Permission to use, copy, modify, and distribute this software and its documentation with or without modifications and for any purpose and without fee is hereby granted, provided that any copyright notices appear in all copies and that both those copyright notices and this permission notice appear in supporting documentation, and that the names of the contributors or copyright holders not be used in advertising or publicity pertaining to distribution of the software without specific prior permission. THE CONTRIBUTORS AND COPYRIGHT HOLDERS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ''' def draw_tree(tree, pymod, label_func=str, do_show=True, show_confidence=True, tree_lines_width=1, tree_color="#000000", labels_font_size="12px", labels_color="#404040"): """ Draws a distance tree contained in a 'Tree' class object of Bio.Phylo using PyMod plotting engine. It mainly uses the algorithm implemented in the 'draw' method of 'Phylo'. """ ############################################################################# # Arrays that store lines for the plot of clades horizontal_linecollections = [] vertical_linecollections = [] # Layout def get_x_positions(tree): """Create a mapping of each clade to its horizontal position. Dict of {clade: x-coord} """ depths = tree.depths() # If there are no branch lengths, assume unit branch lengths if not max(depths.values()): depths = tree.depths(unit_branch_lengths=True) return depths def get_y_positions(tree): """Create a mapping of each clade to its vertical position. Dict of {clade: y-coord}. Coordinates are negative, and integers for tips. """ maxheight = tree.count_terminals() # Rows are defined by the tips heights = dict((tip, maxheight - i) for i, tip in enumerate(reversed(tree.get_terminals()))) # Internal nodes: place at midpoint of children def calc_row(clade): for subclade in clade: if subclade not in heights: calc_row(subclade) # Closure over heights heights[clade] = (heights[clade.clades[0]] + heights[clade.clades[-1]]) / 2.0 if tree.root.clades: calc_row(tree.root) return heights ############################################################################# x_posns = get_x_positions(tree) y_posns = get_y_positions(tree) # Add margins around the tree to prevent overlapping the axes xmax = max(x_posns.values()) xlim = (-0.05 * xmax, 1.25 * xmax) # Also invert the y-axis (origin at the top) # Add a small vertical margin, but avoid including 0 and N+1 on the y axis ylim = (0.2, max(y_posns.values()) + 0.8) # (max(y_posns.values()) + 0.8, 0.2) # Aesthetics plot_title = "Distance tree" if hasattr(tree, 'name') and tree.name: plot_title = tree.name # Builds the plot window and initializes the plotting area. cp = PyMod_plot_window_qt(pymod.main_window) cp.initialize(pymod=pymod, title=plot_title) cp.build_plotting_area(use_controls=False, x_label_text="Branch length", y_label_text="Taxum", hide_y_ticks=True, use_all_controls_buttons=False, use_save_to_csv=False) cp.show() ############################################################################# def draw_clade_lines(use_linecollection=True, orientation='horizontal', y_here=0, x_start=0, x_here=0, y_bot=0, y_top=0, color='black', lw='.1'): """Create a line with or without a line collection object. Graphical formatting of the lines representing clades in the plot can be customized by altering this function. """ if orientation == 'horizontal': horizontal_linecollections.append([x_start, y_here, x_here, y_here]) elif orientation == 'vertical': vertical_linecollections.append([x_here, y_bot, x_here, y_top]) def draw_clade(clade, x_start, color, lw): """Recursively draw a tree, down from the given clade.""" x_here = x_posns[clade] y_here = y_posns[clade] # phyloXML-only graphics annotations if hasattr(clade, 'color') and clade.color is not None: color = clade.color.to_hex() if hasattr(clade, 'width') and clade.width is not None: lw = 1 # GX: clade.width * plt.rcParams['lines.linewidth'] # Draw a horizontal line from start to here draw_clade_lines(use_linecollection=True, orientation='horizontal', y_here=y_here, x_start=x_start, x_here=x_here, color=color, lw=lw) #---------------------------------------------------- # Add node/taxon labels label = label_func(clade) if label not in (None, clade.__class__.__name__): html = "<span style='color: %s; font-size: %s'> %s</span>" % (labels_color, labels_font_size, label) text = pyqtgraph.TextItem(text=" %s" % label, anchor=(0, 0.5), html=html) cp.graphWidget.addItem(text) # text.setFont(QtGui.QFont(None, 8)) text.setPos(x_here, y_here) # Add label above the branch (optional) show_confidence = False def conf2str(conf): if int(conf) == conf: return str(int(conf)) return str(conf) if show_confidence: def format_branch_label(clade): if hasattr(clade, 'confidences'): # phyloXML supports multiple confidences return '/'.join(conf2str(cnf.value) for cnf in clade.confidences) if clade.confidence: return conf2str(clade.confidence) return None else: def format_branch_label(clade): return None conf_label = format_branch_label(clade) if conf_label: # cp.draw_label(conf_label, [0.5 * (x_start + x_here), y_here]) # TODO: update this too. pass #---------------------------------------------------- if clade.clades: # Draw a vertical line connecting all children y_top = y_posns[clade.clades[0]] y_bot = y_posns[clade.clades[-1]] # Only apply widths to horizontal lines, like Archaeopteryx draw_clade_lines(use_linecollection=True, orientation='vertical', x_here=x_here, y_bot=y_bot, y_top=y_top, color=color, lw=lw) # Draw descendents for child in clade: draw_clade(child, x_here, color, lw) ############################################################################# draw_clade(tree.root, 0, 'k', 1) def get_plot_data_from_coords(coords_list): x_list = [] y_list = [] for coords in coords_list: x_list.extend([coords[0], coords[2]]) y_list.extend([coords[1], coords[3]]) return x_list, y_list # If line collections were used to create clade lines, here they are added # to the pyqtgraph plot. tree_pen = pyqtgraph.mkPen(width=tree_lines_width, color=tree_color) # Color and width of the tree. x_list, y_list = get_plot_data_from_coords(horizontal_linecollections) # for coords in horizontal_linecollections: # cp.draw_line(coords) cp.graphWidget.plot(x_list, y_list, connect="pairs", pen=tree_pen) x_list, y_list = get_plot_data_from_coords(vertical_linecollections) cp.graphWidget.plot(x_list, y_list, connect="pairs", pen=tree_pen) ############################################################################### # Builds a plot showing a dendrogram from MODELLER. # ############################################################################### def draw_modeller_dendrogram(dendrogram_filepath, pymod, tree_lines_width=1, tree_color="#000000", labels_font_size="12px", labels_color="#404040"): """ Draw 'dendrogram_file' for SALIGN tree file using PyMod plot engine based on pyqtgraph. """ with open(dendrogram_filepath, 'r') as fp: content = fp.read() width = max([len(sline) for sline in content.splitlines()]) height = len(content.splitlines()) # Builds the plot window and initializes the plotting area. cp = PyMod_plot_window_qt(pymod.main_window) cp.initialize(pymod=pymod, title="MODELLER Dendrogram") cp.build_plotting_area(use_controls=False, x_label_text="Branch length", y_label_text="Taxum", hide_y_ticks=True, hide_x_ticks=True, use_all_controls_buttons=False, use_save_to_csv=False) cp.show() # Functions used to draw the dendrogram. x_list = [] y_list = [] def add_single_line_data(coords): x_list.extend([coords[0], coords[2]]) y_list.extend([coords[1], coords[3]]) def draw_single_label(label, coords): html = "<span style='color: %s; font-size: %s'> %s</span>" % (labels_color, labels_font_size, label) text = pyqtgraph.TextItem(text=" %s" % label, anchor=(0, 0.5), html=html) cp.graphWidget.addItem(text) text.setPos(coords[0], coords[1]) def draw_lines_recursively(sline, y=0, offset=0): if not sline.strip(): return if sline.lstrip().startswith('.-'): # leaf x1=sline.find('.-') x2=sline.find('- ')+1 if not x2 or x1>x2: x2=x1 add_single_line_data([offset+x1,y,offset+x2,y]) draw_single_label(sline[x2:].strip(),[offset+x2+1,y]) elif sline.lstrip().startswith('+-') and sline[-2:]=='-+': x1=sline.find('+-') x2=len(sline)-1 add_single_line_data([offset+x1,y,offset+x2,y]) for j,c in enumerate(sline): if c=='+': x=j y1=height-i-0.1 y2=height-i+0.1 add_single_line_data([offset+x,y1,offset+x,y2]) elif sline.lstrip()[0] in '0123456789': x1=0 for j,c in enumerate(sline): if j and sline[j-1]==' ': x1=j*1 elif j+1==len(sline): draw_single_label(sline[x1:],[offset+x1,y]) elif j+1<len(sline) and sline[j+1]==' ': draw_single_label(sline[x1:j],[offset+x1,y]) elif sline.lstrip().startswith('|'): # branch x=sline.find('|') y1=height-i-1 y2=height-i+1 add_single_line_data([offset+x,y1,offset+x,y2]) if x+1<len(sline): draw_lines_recursively(sline[x+1:],y,offset=x+1+offset) # Actually draw the dendrogram. for i, sline in enumerate(content.splitlines()): draw_lines_recursively(sline, y=height-i) tree_pen = pyqtgraph.mkPen(width=tree_lines_width, color=tree_color) # Color and width of the tree. cp.graphWidget.plot(x_list, y_list, connect="pairs", pen=tree_pen) ############################################################################### # Minimal example for pyqtgraph. # ############################################################################### if __name__ == "__main__": from pymol.Qt import QtWidgets from pymod_lib.pymod_plot.pyqtgraph import PlotWidget, plot import pymod_lib.pymod_plot.pyqtgraph as pg class Plot_window(QtWidgets.QMainWindow): def __init__(self, *args, **kwargs): super(Plot_window, self).__init__(*args, **kwargs) self.graphWidget = pg.PlotWidget() self.setCentralWidget(self.graphWidget) hour = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] temperature = [30, 32, 34, 32, 33, 31, 29, 32, 35, 45] # plot data: x, y values self.graphWidget.plot(hour, temperature) w = Plot_window(self.main_window) w.show()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/pgcollections.py
.py
15,679
485
# -*- coding: utf-8 -*- """ advancedTypes.py - Basic data structures not included with python Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. Includes: - OrderedDict - Dictionary which preserves the order of its elements - BiDict, ReverseDict - Bi-directional dictionaries - ThreadsafeDict, ThreadsafeList - Self-mutexed data structures """ import threading import sys import copy try: from collections import OrderedDict except ImportError: # fallback: try to use the ordereddict backport when using python 2.6 from ordereddict import OrderedDict try: from collections.abc import Sequence except ImportError: # fallback for python < 3.3 from collections import Sequence class ReverseDict(dict): """extends dict so that reverse lookups are possible by requesting the key as a list of length 1: d = BiDict({'x': 1, 'y': 2}) d['x'] 1 d[[2]] 'y' """ def __init__(self, data=None): if data is None: data = {} self.reverse = {} for k in data: self.reverse[data[k]] = k dict.__init__(self, data) def __getitem__(self, item): if type(item) is list: return self.reverse[item[0]] else: return dict.__getitem__(self, item) def __setitem__(self, item, value): self.reverse[value] = item dict.__setitem__(self, item, value) def __deepcopy__(self, memo): raise Exception("deepcopy not implemented") class BiDict(dict): """extends dict so that reverse lookups are possible by adding each reverse combination to the dict. This only works if all values and keys are unique.""" def __init__(self, data=None): if data is None: data = {} dict.__init__(self) for k in data: self[data[k]] = k def __setitem__(self, item, value): dict.__setitem__(self, item, value) dict.__setitem__(self, value, item) def __deepcopy__(self, memo): raise Exception("deepcopy not implemented") class ThreadsafeDict(dict): """Extends dict so that getitem, setitem, and contains are all thread-safe. Also adds lock/unlock functions for extended exclusive operations Converts all sub-dicts and lists to threadsafe as well. """ def __init__(self, *args, **kwargs): self.mutex = threading.RLock() dict.__init__(self, *args, **kwargs) for k in self: if type(self[k]) is dict: self[k] = ThreadsafeDict(self[k]) def __getitem__(self, attr): self.lock() try: val = dict.__getitem__(self, attr) finally: self.unlock() return val def __setitem__(self, attr, val): if type(val) is dict: val = ThreadsafeDict(val) self.lock() try: dict.__setitem__(self, attr, val) finally: self.unlock() def __contains__(self, attr): self.lock() try: val = dict.__contains__(self, attr) finally: self.unlock() return val def __len__(self): self.lock() try: val = dict.__len__(self) finally: self.unlock() return val def clear(self): self.lock() try: dict.clear(self) finally: self.unlock() def lock(self): self.mutex.acquire() def unlock(self): self.mutex.release() def __deepcopy__(self, memo): raise Exception("deepcopy not implemented") class ThreadsafeList(list): """Extends list so that getitem, setitem, and contains are all thread-safe. Also adds lock/unlock functions for extended exclusive operations Converts all sub-lists and dicts to threadsafe as well. """ def __init__(self, *args, **kwargs): self.mutex = threading.RLock() list.__init__(self, *args, **kwargs) for k in self: self[k] = mkThreadsafe(self[k]) def __getitem__(self, attr): self.lock() try: val = list.__getitem__(self, attr) finally: self.unlock() return val def __setitem__(self, attr, val): val = makeThreadsafe(val) self.lock() try: list.__setitem__(self, attr, val) finally: self.unlock() def __contains__(self, attr): self.lock() try: val = list.__contains__(self, attr) finally: self.unlock() return val def __len__(self): self.lock() try: val = list.__len__(self) finally: self.unlock() return val def lock(self): self.mutex.acquire() def unlock(self): self.mutex.release() def __deepcopy__(self, memo): raise Exception("deepcopy not implemented") def makeThreadsafe(obj): if type(obj) is dict: return ThreadsafeDict(obj) elif type(obj) is list: return ThreadsafeList(obj) elif type(obj) in [str, int, float, bool, tuple]: return obj else: raise Exception("Not sure how to make object of type %s thread-safe" % str(type(obj))) class Locker(object): def __init__(self, lock): self.lock = lock self.lock.acquire() def __del__(self): try: self.lock.release() except: pass class CaselessDict(OrderedDict): """Case-insensitive dict. Values can be set and retrieved using keys of any case. Note that when iterating, the original case is returned for each key.""" def __init__(self, *args): OrderedDict.__init__(self, {}) ## requirement for the empty {} here seems to be a python bug? self.keyMap = OrderedDict([(k.lower(), k) for k in OrderedDict.keys(self)]) if len(args) == 0: return elif len(args) == 1 and isinstance(args[0], dict): for k in args[0]: self[k] = args[0][k] else: raise Exception("CaselessDict may only be instantiated with a single dict.") #def keys(self): #return self.keyMap.values() def __setitem__(self, key, val): kl = key.lower() if kl in self.keyMap: OrderedDict.__setitem__(self, self.keyMap[kl], val) else: OrderedDict.__setitem__(self, key, val) self.keyMap[kl] = key def __getitem__(self, key): kl = key.lower() if kl not in self.keyMap: raise KeyError(key) return OrderedDict.__getitem__(self, self.keyMap[kl]) def __contains__(self, key): return key.lower() in self.keyMap def update(self, d): for k, v in d.items(): self[k] = v def copy(self): return CaselessDict(OrderedDict.copy(self)) def __delitem__(self, key): kl = key.lower() if kl not in self.keyMap: raise KeyError(key) OrderedDict.__delitem__(self, self.keyMap[kl]) del self.keyMap[kl] def __deepcopy__(self, memo): raise Exception("deepcopy not implemented") def clear(self): OrderedDict.clear(self) self.keyMap.clear() class ProtectedDict(dict): """ A class allowing read-only 'view' of a dict. The object can be treated like a normal dict, but will never modify the original dict it points to. Any values accessed from the dict will also be read-only. """ def __init__(self, data): self._data_ = data ## List of methods to directly wrap from _data_ wrapMethods = ['_cmp_', '__contains__', '__eq__', '__format__', '__ge__', '__gt__', '__le__', '__len__', '__lt__', '__ne__', '__reduce__', '__reduce_ex__', '__repr__', '__str__', 'count', 'has_key', 'iterkeys', 'keys', ] ## List of methods which wrap from _data_ but return protected results protectMethods = ['__getitem__', '__iter__', 'get', 'items', 'values'] ## List of methods to disable disableMethods = ['__delitem__', '__setitem__', 'clear', 'pop', 'popitem', 'setdefault', 'update'] ## Template methods def wrapMethod(methodName): return lambda self, *a, **k: getattr(self._data_, methodName)(*a, **k) def protectMethod(methodName): return lambda self, *a, **k: protect(getattr(self._data_, methodName)(*a, **k)) def error(self, *args, **kargs): raise Exception("Can not modify read-only list.") ## Directly (and explicitly) wrap some methods from _data_ ## Many of these methods can not be intercepted using __getattribute__, so they ## must be implemented explicitly for methodName in wrapMethods: locals()[methodName] = wrapMethod(methodName) ## Wrap some methods from _data_ with the results converted to protected objects for methodName in protectMethods: locals()[methodName] = protectMethod(methodName) ## Disable any methods that could change data in the list for methodName in disableMethods: locals()[methodName] = error ## Add a few extra methods. def copy(self): raise Exception("It is not safe to copy protected dicts! (instead try deepcopy, but be careful.)") def itervalues(self): for v in self._data_.values(): yield protect(v) def iteritems(self): for k, v in self._data_.items(): yield (k, protect(v)) def deepcopy(self): return copy.deepcopy(self._data_) def __deepcopy__(self, memo): return copy.deepcopy(self._data_, memo) class ProtectedList(Sequence): """ A class allowing read-only 'view' of a list or dict. The object can be treated like a normal list, but will never modify the original list it points to. Any values accessed from the list will also be read-only. Note: It would be nice if we could inherit from list or tuple so that isinstance checks would work. However, doing this causes tuple(obj) to return unprotected results (importantly, this means unpacking into function arguments will also fail) """ def __init__(self, data): self._data_ = data #self.__mro__ = (ProtectedList, object) ## List of methods to directly wrap from _data_ wrapMethods = ['__contains__', '__eq__', '__format__', '__ge__', '__gt__', '__le__', '__len__', '__lt__', '__ne__', '__reduce__', '__reduce_ex__', '__repr__', '__str__', 'count', 'index'] ## List of methods which wrap from _data_ but return protected results protectMethods = ['__getitem__', '__getslice__', '__mul__', '__reversed__', '__rmul__'] ## List of methods to disable disableMethods = ['__delitem__', '__delslice__', '__iadd__', '__imul__', '__setitem__', '__setslice__', 'append', 'extend', 'insert', 'pop', 'remove', 'reverse', 'sort'] ## Template methods def wrapMethod(methodName): return lambda self, *a, **k: getattr(self._data_, methodName)(*a, **k) def protectMethod(methodName): return lambda self, *a, **k: protect(getattr(self._data_, methodName)(*a, **k)) def error(self, *args, **kargs): raise Exception("Can not modify read-only list.") ## Directly (and explicitly) wrap some methods from _data_ ## Many of these methods can not be intercepted using __getattribute__, so they ## must be implemented explicitly for methodName in wrapMethods: locals()[methodName] = wrapMethod(methodName) ## Wrap some methods from _data_ with the results converted to protected objects for methodName in protectMethods: locals()[methodName] = protectMethod(methodName) ## Disable any methods that could change data in the list for methodName in disableMethods: locals()[methodName] = error ## Add a few extra methods. def __iter__(self): for item in self._data_: yield protect(item) def __add__(self, op): if isinstance(op, ProtectedList): return protect(self._data_.__add__(op._data_)) elif isinstance(op, list): return protect(self._data_.__add__(op)) else: raise TypeError("Argument must be a list.") def __radd__(self, op): if isinstance(op, ProtectedList): return protect(op._data_.__add__(self._data_)) elif isinstance(op, list): return protect(op.__add__(self._data_)) else: raise TypeError("Argument must be a list.") def deepcopy(self): return copy.deepcopy(self._data_) def __deepcopy__(self, memo): return copy.deepcopy(self._data_, memo) def poop(self): raise Exception("This is a list. It does not poop.") class ProtectedTuple(Sequence): """ A class allowing read-only 'view' of a tuple. The object can be treated like a normal tuple, but its contents will be returned as protected objects. Note: It would be nice if we could inherit from list or tuple so that isinstance checks would work. However, doing this causes tuple(obj) to return unprotected results (importantly, this means unpacking into function arguments will also fail) """ def __init__(self, data): self._data_ = data ## List of methods to directly wrap from _data_ wrapMethods = ['__contains__', '__eq__', '__format__', '__ge__', '__getnewargs__', '__gt__', '__hash__', '__le__', '__len__', '__lt__', '__ne__', '__reduce__', '__reduce_ex__', '__repr__', '__str__', 'count', 'index'] ## List of methods which wrap from _data_ but return protected results protectMethods = ['__getitem__', '__getslice__', '__iter__', '__add__', '__mul__', '__reversed__', '__rmul__'] ## Template methods def wrapMethod(methodName): return lambda self, *a, **k: getattr(self._data_, methodName)(*a, **k) def protectMethod(methodName): return lambda self, *a, **k: protect(getattr(self._data_, methodName)(*a, **k)) ## Directly (and explicitly) wrap some methods from _data_ ## Many of these methods can not be intercepted using __getattribute__, so they ## must be implemented explicitly for methodName in wrapMethods: locals()[methodName] = wrapMethod(methodName) ## Wrap some methods from _data_ with the results converted to protected objects for methodName in protectMethods: locals()[methodName] = protectMethod(methodName) ## Add a few extra methods. def deepcopy(self): return copy.deepcopy(self._data_) def __deepcopy__(self, memo): return copy.deepcopy(self._data_, memo) def protect(obj): if isinstance(obj, dict): return ProtectedDict(obj) elif isinstance(obj, list): return ProtectedList(obj) elif isinstance(obj, tuple): return ProtectedTuple(obj) else: return obj if __name__ == '__main__': d = {'x': 1, 'y': [1,2], 'z': ({'a': 2, 'b': [3,4], 'c': (5,6)}, 1, 2)} dp = protect(d) l = [1, 'x', ['a', 'b'], ('c', 'd'), {'x': 1, 'y': 2}] lp = protect(l) t = (1, 'x', ['a', 'b'], ('c', 'd'), {'x': 1, 'y': 2}) tp = protect(t)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/SRTTransform.py
.py
7,960
261
# -*- coding: utf-8 -*- from .Qt import QtCore, QtGui from .Point import Point import numpy as np class SRTTransform(QtGui.QTransform): """Transform that can always be represented as a combination of 3 matrices: scale * rotate * translate This transform has no shear; angles are always preserved. """ def __init__(self, init=None): QtGui.QTransform.__init__(self) self.reset() if init is None: return elif isinstance(init, dict): self.restoreState(init) elif isinstance(init, SRTTransform): self._state = { 'pos': Point(init._state['pos']), 'scale': Point(init._state['scale']), 'angle': init._state['angle'] } self.update() elif isinstance(init, QtGui.QTransform): self.setFromQTransform(init) elif isinstance(init, QtGui.QMatrix4x4): self.setFromMatrix4x4(init) else: raise Exception("Cannot create SRTTransform from input type: %s" % str(type(init))) def getScale(self): return self._state['scale'] def getAngle(self): ## deprecated; for backward compatibility return self.getRotation() def getRotation(self): return self._state['angle'] def getTranslation(self): return self._state['pos'] def reset(self): self._state = { 'pos': Point(0,0), 'scale': Point(1,1), 'angle': 0.0 ## in degrees } self.update() def setFromQTransform(self, tr): p1 = Point(tr.map(0., 0.)) p2 = Point(tr.map(1., 0.)) p3 = Point(tr.map(0., 1.)) dp2 = Point(p2-p1) dp3 = Point(p3-p1) ## detect flipped axes if dp2.angle(dp3) > 0: #da = 180 da = 0 sy = -1.0 else: da = 0 sy = 1.0 self._state = { 'pos': Point(p1), 'scale': Point(dp2.length(), dp3.length() * sy), 'angle': (np.arctan2(dp2[1], dp2[0]) * 180. / np.pi) + da } self.update() def setFromMatrix4x4(self, m): m = SRTTransform3D(m) angle, axis = m.getRotation() if angle != 0 and (axis[0] != 0 or axis[1] != 0 or axis[2] != 1): print("angle: %s axis: %s" % (str(angle), str(axis))) raise Exception("Can only convert 4x4 matrix to 3x3 if rotation is around Z-axis.") self._state = { 'pos': Point(m.getTranslation()), 'scale': Point(m.getScale()), 'angle': angle } self.update() def translate(self, *args): """Acceptable arguments are: x, y [x, y] Point(x,y)""" t = Point(*args) self.setTranslate(self._state['pos']+t) def setTranslate(self, *args): """Acceptable arguments are: x, y [x, y] Point(x,y)""" self._state['pos'] = Point(*args) self.update() def scale(self, *args): """Acceptable arguments are: x, y [x, y] Point(x,y)""" s = Point(*args) self.setScale(self._state['scale'] * s) def setScale(self, *args): """Acceptable arguments are: x, y [x, y] Point(x,y)""" self._state['scale'] = Point(*args) self.update() def rotate(self, angle): """Rotate the transformation by angle (in degrees)""" self.setRotate(self._state['angle'] + angle) def setRotate(self, angle): """Set the transformation rotation to angle (in degrees)""" self._state['angle'] = angle self.update() def __truediv__(self, t): """A / B == B^-1 * A""" dt = t.inverted()[0] * self return SRTTransform(dt) def __div__(self, t): return self.__truediv__(t) def __mul__(self, t): return SRTTransform(QtGui.QTransform.__mul__(self, t)) def saveState(self): p = self._state['pos'] s = self._state['scale'] #if s[0] == 0: #raise Exception('Invalid scale: %s' % str(s)) return {'pos': (p[0], p[1]), 'scale': (s[0], s[1]), 'angle': self._state['angle']} def restoreState(self, state): self._state['pos'] = Point(state.get('pos', (0,0))) self._state['scale'] = Point(state.get('scale', (1.,1.))) self._state['angle'] = state.get('angle', 0) self.update() def update(self): QtGui.QTransform.reset(self) ## modifications to the transform are multiplied on the right, so we need to reverse order here. QtGui.QTransform.translate(self, *self._state['pos']) QtGui.QTransform.rotate(self, self._state['angle']) QtGui.QTransform.scale(self, *self._state['scale']) def __repr__(self): return str(self.saveState()) def matrix(self): return np.array([[self.m11(), self.m12(), self.m13()],[self.m21(), self.m22(), self.m23()],[self.m31(), self.m32(), self.m33()]]) if __name__ == '__main__': from . import widgets import GraphicsView from .functions import * app = QtGui.QApplication([]) win = QtGui.QMainWindow() win.show() cw = GraphicsView.GraphicsView() #cw.enableMouse() win.setCentralWidget(cw) s = QtGui.QGraphicsScene() cw.setScene(s) win.resize(600,600) cw.enableMouse() cw.setRange(QtCore.QRectF(-100., -100., 200., 200.)) class Item(QtGui.QGraphicsItem): def __init__(self): QtGui.QGraphicsItem.__init__(self) self.b = QtGui.QGraphicsRectItem(20, 20, 20, 20, self) self.b.setPen(QtGui.QPen(mkPen('y'))) self.t1 = QtGui.QGraphicsTextItem(self) self.t1.setHtml('<span style="color: #F00">R</span>') self.t1.translate(20, 20) self.l1 = QtGui.QGraphicsLineItem(10, 0, -10, 0, self) self.l2 = QtGui.QGraphicsLineItem(0, 10, 0, -10, self) self.l1.setPen(QtGui.QPen(mkPen('y'))) self.l2.setPen(QtGui.QPen(mkPen('y'))) def boundingRect(self): return QtCore.QRectF() def paint(self, *args): pass #s.addItem(b) #s.addItem(t1) item = Item() s.addItem(item) l1 = QtGui.QGraphicsLineItem(10, 0, -10, 0) l2 = QtGui.QGraphicsLineItem(0, 10, 0, -10) l1.setPen(QtGui.QPen(mkPen('r'))) l2.setPen(QtGui.QPen(mkPen('r'))) s.addItem(l1) s.addItem(l2) tr1 = SRTTransform() tr2 = SRTTransform() tr3 = QtGui.QTransform() tr3.translate(20, 0) tr3.rotate(45) print("QTransform -> Transform:", SRTTransform(tr3)) print("tr1:", tr1) tr2.translate(20, 0) tr2.rotate(45) print("tr2:", tr2) dt = tr2/tr1 print("tr2 / tr1 = ", dt) print("tr2 * tr1 = ", tr2*tr1) tr4 = SRTTransform() tr4.scale(-1, 1) tr4.rotate(30) print("tr1 * tr4 = ", tr1*tr4) w1 = widgets.TestROI((19,19), (22, 22), invertible=True) #w2 = widgets.TestROI((0,0), (150, 150)) w1.setZValue(10) s.addItem(w1) #s.addItem(w2) w1Base = w1.getState() #w2Base = w2.getState() def update(): tr1 = w1.getGlobalTransform(w1Base) #tr2 = w2.getGlobalTransform(w2Base) item.setTransform(tr1) #def update2(): #tr1 = w1.getGlobalTransform(w1Base) #tr2 = w2.getGlobalTransform(w2Base) #t1.setTransform(tr1) #w1.setState(w1Base) #w1.applyGlobalTransform(tr2) w1.sigRegionChanged.connect(update) #w2.sigRegionChanged.connect(update2) from .SRTTransform3D import SRTTransform3D
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/Transform3D.py
.py
1,867
53
# -*- coding: utf-8 -*- from .Qt import QtCore, QtGui from . import functions as fn from .Vector import Vector import numpy as np class Transform3D(QtGui.QMatrix4x4): """ Extension of QMatrix4x4 with some helpful methods added. """ def __init__(self, *args): if len(args) == 1: if isinstance(args[0], (list, tuple, np.ndarray)): args = [x for y in args[0] for x in y] if len(args) != 16: raise TypeError("Single argument to Transform3D must have 16 elements.") elif isinstance(args[0], QtGui.QMatrix4x4): args = list(args[0].copyDataTo()) QtGui.QMatrix4x4.__init__(self, *args) def matrix(self, nd=3): if nd == 3: return np.array(self.copyDataTo()).reshape(4,4) elif nd == 2: m = np.array(self.copyDataTo()).reshape(4,4) m[2] = m[3] m[:,2] = m[:,3] return m[:3,:3] else: raise Exception("Argument 'nd' must be 2 or 3") def map(self, obj): """ Extends QMatrix4x4.map() to allow mapping (3, ...) arrays of coordinates """ if isinstance(obj, np.ndarray) and obj.shape[0] in (2,3): if obj.ndim >= 2: return fn.transformCoordinates(self, obj) elif obj.ndim == 1: v = QtGui.QMatrix4x4.map(self, Vector(obj)) return np.array([v.x(), v.y(), v.z()])[:obj.shape[0]] elif isinstance(obj, (list, tuple)): v = QtGui.QMatrix4x4.map(self, Vector(obj)) return type(obj)([v.x(), v.y(), v.z()])[:len(obj)] else: return QtGui.QMatrix4x4.map(self, obj) def inverted(self): inv, b = QtGui.QMatrix4x4.inverted(self) return Transform3D(inv), b
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/ordereddict.py
.py
4,532
132
# Copyright (c) 2009 Raymond Hettinger # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import sys if sys.version[0] > '2': from collections import OrderedDict else: from UserDict import DictMixin class OrderedDict(dict, DictMixin): def __init__(self, *args, **kwds): if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__end except AttributeError: self.clear() self.update(*args, **kwds) def clear(self): self.__end = end = [] end += [None, end, end] # sentinel node for doubly linked list self.__map = {} # key --> [key, prev, next] dict.clear(self) def __setitem__(self, key, value): if key not in self: end = self.__end curr = end[1] curr[2] = end[1] = self.__map[key] = [key, curr, end] dict.__setitem__(self, key, value) def __delitem__(self, key): dict.__delitem__(self, key) key, prev, next = self.__map.pop(key) prev[2] = next next[1] = prev def __iter__(self): end = self.__end curr = end[2] while curr is not end: yield curr[0] curr = curr[2] def __reversed__(self): end = self.__end curr = end[1] while curr is not end: yield curr[0] curr = curr[1] def popitem(self, last=True): if not self: raise KeyError('dictionary is empty') if last: key = reversed(self).next() else: key = iter(self).next() value = self.pop(key) return key, value def __reduce__(self): items = [[k, self[k]] for k in self] tmp = self.__map, self.__end del self.__map, self.__end inst_dict = vars(self).copy() self.__map, self.__end = tmp if inst_dict: return (self.__class__, (items,), inst_dict) return self.__class__, (items,) def keys(self): return list(self) setdefault = DictMixin.setdefault update = DictMixin.update pop = DictMixin.pop values = DictMixin.values items = DictMixin.items iterkeys = DictMixin.iterkeys itervalues = DictMixin.itervalues iteritems = DictMixin.iteritems def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) def copy(self): return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): d = cls() for key in iterable: d[key] = value return d def __eq__(self, other): if isinstance(other, OrderedDict): if len(self) != len(other): return False for p, q in zip(self.items(), other.items()): if p != q: return False return True return dict.__eq__(self, other) def __ne__(self, other): return not self == other
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/python2_3.py
.py
542
26
# -*- coding: utf-8 -*- """ Helper functions that smooth out the differences between python 2 and 3. """ import sys def asUnicode(x): if sys.version_info[0] == 2: if isinstance(x, unicode): return x elif isinstance(x, str): return x.decode('UTF-8') else: return unicode(x) else: return str(x) if sys.version_info[0] == 3: basestring = str xrange = range else: import __builtin__ basestring = __builtin__.basestring xrange = __builtin__.xrange
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/ptime.py
.py
1,039
38
# -*- coding: utf-8 -*- """ ptime.py - Precision time function made os-independent (should have been taken care of by python) Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. """ import sys if sys.version_info[0] < 3: from time import clock from time import time as system_time else: from time import perf_counter as clock from time import time as system_time START_TIME = None time = None def winTime(): """Return the current time in seconds with high precision (windows version, use Manager.time() to stay platform independent).""" return clock() - START_TIME #return systime.time() def unixTime(): """Return the current time in seconds with high precision (unix version, use Manager.time() to stay platform independent).""" return system_time() if sys.platform.startswith('win'): cstart = clock() ### Required to start the clock in windows START_TIME = system_time() - cstart time = winTime else: time = unixTime
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/Qt.py
.py
10,195
349
# -*- coding: utf-8 -*- """ This module exists to smooth out some of the differences between PySide and PyQt4: * Automatically import either PyQt4 or PySide depending on availability * Allow to import QtCore/QtGui pyqtgraph.Qt without specifying which Qt wrapper you want to use. * Declare QtCore.Signal, .Slot in PyQt4 * Declare loadUiType function for Pyside """ import os, sys, re, time from .python2_3 import asUnicode PYSIDE = 'PySide' PYSIDE2 = 'PySide2' PYQT4 = 'PyQt4' PYQT5 = 'PyQt5' QT_LIB = os.getenv('PYQTGRAPH_QT_LIB') ## Automatically determine which Qt package to use (unless specified by ## environment variable). ## This is done by first checking to see whether one of the libraries ## is already imported. If not, then attempt to import PyQt4, then PySide. if QT_LIB is None: libOrder = [PYQT4, PYSIDE, PYQT5, PYSIDE2] for lib in libOrder: if lib in sys.modules: QT_LIB = lib break if QT_LIB is None: for lib in libOrder: try: __import__(lib) QT_LIB = lib break except ImportError: pass if QT_LIB is None: raise Exception("PyQtGraph requires one of PyQt4, PyQt5, PySide or PySide2; none of these packages could be imported.") class FailedImport(object): """Used to defer ImportErrors until we are sure the module is needed. """ def __init__(self, err): self.err = err def __getattr__(self, attr): raise self.err def _isQObjectAlive(obj): """An approximation of PyQt's isQObjectAlive(). """ try: if hasattr(obj, 'parent'): obj.parent() elif hasattr(obj, 'parentItem'): obj.parentItem() else: raise Exception("Cannot determine whether Qt object %s is still alive." % obj) except RuntimeError: return False else: return True # Make a loadUiType function like PyQt has # Credit: # http://stackoverflow.com/questions/4442286/python-code-genration-with-pyside-uic/14195313#14195313 class _StringIO(object): """Alternative to built-in StringIO needed to circumvent unicode/ascii issues""" def __init__(self): self.data = [] def write(self, data): self.data.append(data) def getvalue(self): return ''.join(map(asUnicode, self.data)).encode('utf8') def _loadUiType(uiFile): """ PySide lacks a "loadUiType" command like PyQt4's, so we have to convert the ui file to py code in-memory first and then execute it in a special frame to retrieve the form_class. from stackoverflow: http://stackoverflow.com/a/14195313/3781327 seems like this might also be a legitimate solution, but I'm not sure how to make PyQt4 and pyside look the same... http://stackoverflow.com/a/8717832 """ if QT_LIB == "PYSIDE": import pysideuic else: import pyside2uic as pysideuic import xml.etree.ElementTree as xml parsed = xml.parse(uiFile) widget_class = parsed.find('widget').get('class') form_class = parsed.find('class').text with open(uiFile, 'r') as f: o = _StringIO() frame = {} pysideuic.compileUi(f, o, indent=0) pyc = compile(o.getvalue(), '<string>', 'exec') exec(pyc, frame) #Fetch the base_class and form class based on their type in the xml from designer form_class = frame['Ui_%s'%form_class] base_class = eval('QtGui.%s'%widget_class) return form_class, base_class if QT_LIB == PYSIDE: from PySide import QtGui, QtCore try: from PySide import QtOpenGL except ImportError as err: QtOpenGL = FailedImport(err) try: from PySide import QtSvg except ImportError as err: QtSvg = FailedImport(err) try: from PySide import QtTest except ImportError as err: QtTest = FailedImport(err) try: from PySide import shiboken isQObjectAlive = shiboken.isValid except ImportError: # use approximate version isQObjectAlive = _isQObjectAlive import PySide VERSION_INFO = 'PySide ' + PySide.__version__ + ' Qt ' + QtCore.__version__ elif QT_LIB == PYQT4: from PyQt4 import QtGui, QtCore, uic try: from PyQt4 import QtSvg except ImportError as err: QtSvg = FailedImport(err) try: from PyQt4 import QtOpenGL except ImportError as err: QtOpenGL = FailedImport(err) try: from PyQt4 import QtTest except ImportError as err: QtTest = FailedImport(err) VERSION_INFO = 'PyQt4 ' + QtCore.PYQT_VERSION_STR + ' Qt ' + QtCore.QT_VERSION_STR elif QT_LIB == PYQT5: # We're using PyQt5 which has a different structure so we're going to use a shim to # recreate the Qt4 structure for Qt5 from PyQt5 import QtGui, QtCore, QtWidgets, uic # PyQt5, starting in v5.5, calls qAbort when an exception is raised inside # a slot. To maintain backward compatibility (and sanity for interactive # users), we install a global exception hook to override this behavior. ver = QtCore.PYQT_VERSION_STR.split('.') if int(ver[1]) >= 5: if sys.excepthook == sys.__excepthook__: sys_excepthook = sys.excepthook def pyqt5_qabort_override(*args, **kwds): return sys_excepthook(*args, **kwds) sys.excepthook = pyqt5_qabort_override try: from PyQt5 import QtSvg except ImportError as err: QtSvg = FailedImport(err) try: from PyQt5 import QtOpenGL except ImportError as err: QtOpenGL = FailedImport(err) try: from PyQt5 import QtTest QtTest.QTest.qWaitForWindowShown = QtTest.QTest.qWaitForWindowExposed except ImportError as err: QtTest = FailedImport(err) VERSION_INFO = 'PyQt5 ' + QtCore.PYQT_VERSION_STR + ' Qt ' + QtCore.QT_VERSION_STR elif QT_LIB == PYSIDE2: from PySide2 import QtGui, QtCore, QtWidgets try: from PySide2 import QtSvg except ImportError as err: QtSvg = FailedImport(err) try: from PySide2 import QtOpenGL except ImportError as err: QtOpenGL = FailedImport(err) try: from PySide2 import QtTest QtTest.QTest.qWaitForWindowShown = QtTest.QTest.qWaitForWindowExposed except ImportError as err: QtTest = FailedImport(err) try: import shiboken2 isQObjectAlive = shiboken2.isValid except ImportError: # use approximate version isQObjectAlive = _isQObjectAlive import PySide2 VERSION_INFO = 'PySide2 ' + PySide2.__version__ + ' Qt ' + QtCore.__version__ else: raise ValueError("Invalid Qt lib '%s'" % QT_LIB) # common to PyQt5 and PySide2 if QT_LIB in [PYQT5, PYSIDE2]: # We're using Qt5 which has a different structure so we're going to use a shim to # recreate the Qt4 structure __QGraphicsItem_scale = QtWidgets.QGraphicsItem.scale def scale(self, *args): if args: sx, sy = args tr = self.transform() tr.scale(sx, sy) self.setTransform(tr) else: return __QGraphicsItem_scale(self) QtWidgets.QGraphicsItem.scale = scale def rotate(self, angle): tr = self.transform() tr.rotate(angle) self.setTransform(tr) QtWidgets.QGraphicsItem.rotate = rotate def translate(self, dx, dy): tr = self.transform() tr.translate(dx, dy) self.setTransform(tr) QtWidgets.QGraphicsItem.translate = translate def setMargin(self, i): self.setContentsMargins(i, i, i, i) QtWidgets.QGridLayout.setMargin = setMargin def setResizeMode(self, *args): self.setSectionResizeMode(*args) QtWidgets.QHeaderView.setResizeMode = setResizeMode QtGui.QApplication = QtWidgets.QApplication QtGui.QGraphicsScene = QtWidgets.QGraphicsScene QtGui.QGraphicsObject = QtWidgets.QGraphicsObject QtGui.QGraphicsWidget = QtWidgets.QGraphicsWidget QtGui.QApplication.setGraphicsSystem = None # Import all QtWidgets objects into QtGui for o in dir(QtWidgets): if o.startswith('Q'): setattr(QtGui, o, getattr(QtWidgets,o) ) # Common to PySide and PySide2 if QT_LIB in [PYSIDE, PYSIDE2]: QtVersion = QtCore.__version__ loadUiType = _loadUiType # PySide does not implement qWait if not isinstance(QtTest, FailedImport): if not hasattr(QtTest.QTest, 'qWait'): @staticmethod def qWait(msec): start = time.time() QtGui.QApplication.processEvents() while time.time() < start + msec * 0.001: QtGui.QApplication.processEvents() QtTest.QTest.qWait = qWait # Common to PyQt4 and 5 if QT_LIB in [PYQT4, PYQT5]: QtVersion = QtCore.QT_VERSION_STR import sip def isQObjectAlive(obj): return not sip.isdeleted(obj) loadUiType = uic.loadUiType QtCore.Signal = QtCore.pyqtSignal # USE_XXX variables are deprecated USE_PYSIDE = QT_LIB == PYSIDE USE_PYQT4 = QT_LIB == PYQT4 USE_PYQT5 = QT_LIB == PYQT5 ## Make sure we have Qt >= 4.7 versionReq = [4, 7] m = re.match(r'(\d+)\.(\d+).*', QtVersion) if m is not None and list(map(int, m.groups())) < versionReq: print(list(map(int, m.groups()))) raise Exception('pyqtgraph requires Qt version >= %d.%d (your version is %s)' % (versionReq[0], versionReq[1], QtVersion)) QAPP = None def mkQApp(name=None): """ Creates new QApplication or returns current instance if existing. ============== ======================================================== **Arguments:** name (str) Application name, passed to Qt ============== ======================================================== """ global QAPP QAPP = QtGui.QApplication.instance() if QAPP is None: QAPP = QtGui.QApplication(sys.argv or ["pyqtgraph"]) if name is not None: QAPP.setApplicationName(name) return QAPP
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/debug.py
.py
40,699
1,209
# -*- coding: utf-8 -*- """ debug.py - Functions to aid in debugging Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. """ from __future__ import print_function import sys, traceback, time, gc, re, types, weakref, inspect, os, cProfile, threading from . import ptime from numpy import ndarray from .Qt import QtCore, QtGui from .util.mutex import Mutex from .util import cprint __ftraceDepth = 0 def ftrace(func): """Decorator used for marking the beginning and end of function calls. Automatically indents nested calls. """ def w(*args, **kargs): global __ftraceDepth pfx = " " * __ftraceDepth print(pfx + func.__name__ + " start") __ftraceDepth += 1 try: rv = func(*args, **kargs) finally: __ftraceDepth -= 1 print(pfx + func.__name__ + " done") return rv return w class Tracer(object): """ Prints every function enter/exit. Useful for debugging crashes / lockups. """ def __init__(self): self.count = 0 self.stack = [] def trace(self, frame, event, arg): self.count += 1 # If it has been a long time since we saw the top of the stack, # print a reminder if self.count % 1000 == 0: print("----- current stack: -----") for line in self.stack: print(line) if event == 'call': line = " " * len(self.stack) + ">> " + self.frameInfo(frame) print(line) self.stack.append(line) elif event == 'return': self.stack.pop() line = " " * len(self.stack) + "<< " + self.frameInfo(frame) print(line) if len(self.stack) == 0: self.count = 0 return self.trace def stop(self): sys.settrace(None) def start(self): sys.settrace(self.trace) def frameInfo(self, fr): filename = fr.f_code.co_filename funcname = fr.f_code.co_name lineno = fr.f_lineno callfr = sys._getframe(3) callline = "%s %d" % (callfr.f_code.co_name, callfr.f_lineno) args, _, _, value_dict = inspect.getargvalues(fr) if len(args) and args[0] == 'self': instance = value_dict.get('self', None) if instance is not None: cls = getattr(instance, '__class__', None) if cls is not None: funcname = cls.__name__ + "." + funcname return "%s: %s %s: %s" % (callline, filename, lineno, funcname) def warnOnException(func): """Decorator that catches/ignores exceptions and prints a stack trace.""" def w(*args, **kwds): try: func(*args, **kwds) except: printExc('Ignored exception:') return w def getExc(indent=4, prefix='| ', skip=1): lines = formatException(*sys.exc_info(), skip=skip) lines2 = [] for l in lines: lines2.extend(l.strip('\n').split('\n')) lines3 = [" "*indent + prefix + l for l in lines2] return '\n'.join(lines3) def printExc(msg='', indent=4, prefix='|'): """Print an error message followed by an indented exception backtrace (This function is intended to be called within except: blocks)""" exc = getExc(indent, prefix + ' ', skip=2) print("[%s] %s\n" % (time.strftime("%H:%M:%S"), msg)) print(" "*indent + prefix + '='*30 + '>>') print(exc) print(" "*indent + prefix + '='*30 + '<<') def printTrace(msg='', indent=4, prefix='|'): """Print an error message followed by an indented stack trace""" trace = backtrace(1) #exc = getExc(indent, prefix + ' ') print("[%s] %s\n" % (time.strftime("%H:%M:%S"), msg)) print(" "*indent + prefix + '='*30 + '>>') for line in trace.split('\n'): print(" "*indent + prefix + " " + line) print(" "*indent + prefix + '='*30 + '<<') def backtrace(skip=0): return ''.join(traceback.format_stack()[:-(skip+1)]) def formatException(exctype, value, tb, skip=0): """Return a list of formatted exception strings. Similar to traceback.format_exception, but displays the entire stack trace rather than just the portion downstream of the point where the exception is caught. In particular, unhandled exceptions that occur during Qt signal handling do not usually show the portion of the stack that emitted the signal. """ lines = traceback.format_exception(exctype, value, tb) lines = [lines[0]] + traceback.format_stack()[:-(skip+1)] + [' --- exception caught here ---\n'] + lines[1:] return lines def printException(exctype, value, traceback): """Print an exception with its full traceback. Set `sys.excepthook = printException` to ensure that exceptions caught inside Qt signal handlers are printed with their full stack trace. """ print(''.join(formatException(exctype, value, traceback, skip=1))) def listObjs(regex='Q', typ=None): """List all objects managed by python gc with class name matching regex. Finds 'Q...' classes by default.""" if typ is not None: return [x for x in gc.get_objects() if isinstance(x, typ)] else: return [x for x in gc.get_objects() if re.match(regex, type(x).__name__)] def findRefPath(startObj, endObj, maxLen=8, restart=True, seen={}, path=None, ignore=None): """Determine all paths of object references from startObj to endObj""" refs = [] if path is None: path = [endObj] if ignore is None: ignore = {} ignore[id(sys._getframe())] = None ignore[id(path)] = None ignore[id(seen)] = None prefix = " "*(8-maxLen) #print prefix + str(map(type, path)) prefix += " " if restart: #gc.collect() seen.clear() gc.collect() newRefs = [r for r in gc.get_referrers(endObj) if id(r) not in ignore] ignore[id(newRefs)] = None #fo = allFrameObjs() #newRefs = [] #for r in gc.get_referrers(endObj): #try: #if r not in fo: #newRefs.append(r) #except: #newRefs.append(r) for r in newRefs: #print prefix+"->"+str(type(r)) if type(r).__name__ in ['frame', 'function', 'listiterator']: #print prefix+" FRAME" continue try: if any([r is x for x in path]): #print prefix+" LOOP", objChainString([r]+path) continue except: print(r) print(path) raise if r is startObj: refs.append([r]) print(refPathString([startObj]+path)) continue if maxLen == 0: #print prefix+" END:", objChainString([r]+path) continue ## See if we have already searched this node. ## If not, recurse. tree = None try: cache = seen[id(r)] if cache[0] >= maxLen: tree = cache[1] for p in tree: print(refPathString(p+path)) except KeyError: pass ignore[id(tree)] = None if tree is None: tree = findRefPath(startObj, r, maxLen-1, restart=False, path=[r]+path, ignore=ignore) seen[id(r)] = [maxLen, tree] ## integrate any returned results if len(tree) == 0: #print prefix+" EMPTY TREE" continue else: for p in tree: refs.append(p+[r]) #seen[id(r)] = [maxLen, refs] return refs def objString(obj): """Return a short but descriptive string for any object""" try: if type(obj) in [int, float]: return str(obj) elif isinstance(obj, dict): if len(obj) > 5: return "<dict {%s,...}>" % (",".join(list(obj.keys())[:5])) else: return "<dict {%s}>" % (",".join(list(obj.keys()))) elif isinstance(obj, str): if len(obj) > 50: return '"%s..."' % obj[:50] else: return obj[:] elif isinstance(obj, ndarray): return "<ndarray %s %s>" % (str(obj.dtype), str(obj.shape)) elif hasattr(obj, '__len__'): if len(obj) > 5: return "<%s [%s,...]>" % (type(obj).__name__, ",".join([type(o).__name__ for o in obj[:5]])) else: return "<%s [%s]>" % (type(obj).__name__, ",".join([type(o).__name__ for o in obj])) else: return "<%s %s>" % (type(obj).__name__, obj.__class__.__name__) except: return str(type(obj)) def refPathString(chain): """Given a list of adjacent objects in a reference path, print the 'natural' path names (ie, attribute names, keys, and indexes) that follow from one object to the next .""" s = objString(chain[0]) i = 0 while i < len(chain)-1: #print " -> ", i i += 1 o1 = chain[i-1] o2 = chain[i] cont = False if isinstance(o1, list) or isinstance(o1, tuple): if any([o2 is x for x in o1]): s += "[%d]" % o1.index(o2) continue #print " not list" if isinstance(o2, dict) and hasattr(o1, '__dict__') and o2 == o1.__dict__: i += 1 if i >= len(chain): s += ".__dict__" continue o3 = chain[i] for k in o2: if o2[k] is o3: s += '.%s' % k cont = True continue #print " not __dict__" if isinstance(o1, dict): try: if o2 in o1: s += "[key:%s]" % objString(o2) continue except TypeError: pass for k in o1: if o1[k] is o2: s += "[%s]" % objString(k) cont = True continue #print " not dict" #for k in dir(o1): ## Not safe to request attributes like this. #if getattr(o1, k) is o2: #s += ".%s" % k #cont = True #continue #print " not attr" if cont: continue s += " ? " sys.stdout.flush() return s def objectSize(obj, ignore=None, verbose=False, depth=0, recursive=False): """Guess how much memory an object is using""" ignoreTypes = ['MethodType', 'UnboundMethodType', 'BuiltinMethodType', 'FunctionType', 'BuiltinFunctionType'] ignoreTypes = [getattr(types, key) for key in ignoreTypes if hasattr(types, key)] ignoreRegex = re.compile('(method-wrapper|Flag|ItemChange|Option|Mode)') if ignore is None: ignore = {} indent = ' '*depth try: hash(obj) hsh = obj except: hsh = "%s:%d" % (str(type(obj)), id(obj)) if hsh in ignore: return 0 ignore[hsh] = 1 try: size = sys.getsizeof(obj) except TypeError: size = 0 if isinstance(obj, ndarray): try: size += len(obj.data) except: pass if recursive: if type(obj) in [list, tuple]: if verbose: print(indent+"list:") for o in obj: s = objectSize(o, ignore=ignore, verbose=verbose, depth=depth+1) if verbose: print(indent+' +', s) size += s elif isinstance(obj, dict): if verbose: print(indent+"list:") for k in obj: s = objectSize(obj[k], ignore=ignore, verbose=verbose, depth=depth+1) if verbose: print(indent+' +', k, s) size += s #elif isinstance(obj, QtCore.QObject): #try: #childs = obj.children() #if verbose: #print indent+"Qt children:" #for ch in childs: #s = objectSize(obj, ignore=ignore, verbose=verbose, depth=depth+1) #size += s #if verbose: #print indent + ' +', ch.objectName(), s #except: #pass #if isinstance(obj, types.InstanceType): gc.collect() if verbose: print(indent+'attrs:') for k in dir(obj): if k in ['__dict__']: continue o = getattr(obj, k) if type(o) in ignoreTypes: continue strtyp = str(type(o)) if ignoreRegex.search(strtyp): continue #if isinstance(o, types.ObjectType) and strtyp == "<type 'method-wrapper'>": #continue #if verbose: #print indent, k, '?' refs = [r for r in gc.get_referrers(o) if type(r) != types.FrameType] if len(refs) == 1: s = objectSize(o, ignore=ignore, verbose=verbose, depth=depth+1) size += s if verbose: print(indent + " +", k, s) #else: #if verbose: #print indent + ' -', k, len(refs) return size class GarbageWatcher(object): """ Convenient dictionary for holding weak references to objects. Mainly used to check whether the objects have been collect yet or not. Example: gw = GarbageWatcher() gw['objName'] = obj gw['objName2'] = obj2 gw.check() """ def __init__(self): self.objs = weakref.WeakValueDictionary() self.allNames = [] def add(self, obj, name): self.objs[name] = obj self.allNames.append(name) def __setitem__(self, name, obj): self.add(obj, name) def check(self): """Print a list of all watched objects and whether they have been collected.""" gc.collect() dead = self.allNames[:] alive = [] for k in self.objs: dead.remove(k) alive.append(k) print("Deleted objects:", dead) print("Live objects:", alive) def __getitem__(self, item): return self.objs[item] class Profiler(object): """Simple profiler allowing measurement of multiple time intervals. By default, profilers are disabled. To enable profiling, set the environment variable `PYQTGRAPHPROFILE` to a comma-separated list of fully-qualified names of profiled functions. Calling a profiler registers a message (defaulting to an increasing counter) that contains the time elapsed since the last call. When the profiler is about to be garbage-collected, the messages are passed to the outer profiler if one is running, or printed to stdout otherwise. If `delayed` is set to False, messages are immediately printed instead. Example: def function(...): profiler = Profiler() ... do stuff ... profiler('did stuff') ... do other stuff ... profiler('did other stuff') # profiler is garbage-collected and flushed at function end If this function is a method of class C, setting `PYQTGRAPHPROFILE` to "C.function" (without the module name) will enable this profiler. For regular functions, use the qualified name of the function, stripping only the initial "pyqtgraph." prefix from the module. """ _profilers = os.environ.get("PYQTGRAPHPROFILE", None) _profilers = _profilers.split(",") if _profilers is not None else [] _depth = 0 _msgs = [] disable = False # set this flag to disable all or individual profilers at runtime class DisabledProfiler(object): def __init__(self, *args, **kwds): pass def __call__(self, *args): pass def finish(self): pass def mark(self, msg=None): pass _disabledProfiler = DisabledProfiler() def __new__(cls, msg=None, disabled='env', delayed=True): """Optionally create a new profiler based on caller's qualname. """ if disabled is True or (disabled == 'env' and len(cls._profilers) == 0): return cls._disabledProfiler # determine the qualified name of the caller function caller_frame = sys._getframe(1) try: caller_object_type = type(caller_frame.f_locals["self"]) except KeyError: # we are in a regular function qualifier = caller_frame.f_globals["__name__"].split(".", 1)[-1] else: # we are in a method qualifier = caller_object_type.__name__ func_qualname = qualifier + "." + caller_frame.f_code.co_name if disabled == 'env' and func_qualname not in cls._profilers: # don't do anything return cls._disabledProfiler # create an actual profiling object cls._depth += 1 obj = super(Profiler, cls).__new__(cls) obj._name = msg or func_qualname obj._delayed = delayed obj._markCount = 0 obj._finished = False obj._firstTime = obj._lastTime = ptime.time() obj._newMsg("> Entering " + obj._name) return obj def __call__(self, msg=None): """Register or print a new message with timing information. """ if self.disable: return if msg is None: msg = str(self._markCount) self._markCount += 1 newTime = ptime.time() self._newMsg(" %s: %0.4f ms", msg, (newTime - self._lastTime) * 1000) self._lastTime = newTime def mark(self, msg=None): self(msg) def _newMsg(self, msg, *args): msg = " " * (self._depth - 1) + msg if self._delayed: self._msgs.append((msg, args)) else: self.flush() print(msg % args) def __del__(self): self.finish() def finish(self, msg=None): """Add a final message; flush the message list if no parent profiler. """ if self._finished or self.disable: return self._finished = True if msg is not None: self(msg) self._newMsg("< Exiting %s, total time: %0.4f ms", self._name, (ptime.time() - self._firstTime) * 1000) type(self)._depth -= 1 if self._depth < 1: self.flush() def flush(self): if self._msgs: print("\n".join([m[0]%m[1] for m in self._msgs])) type(self)._msgs = [] def profile(code, name='profile_run', sort='cumulative', num=30): """Common-use for cProfile""" cProfile.run(code, name) stats = pstats.Stats(name) stats.sort_stats(sort) stats.print_stats(num) return stats #### Code for listing (nearly) all objects in the known universe #### http://utcc.utoronto.ca/~cks/space/blog/python/GetAllObjects # Recursively expand slist's objects # into olist, using seen to track # already processed objects. def _getr(slist, olist, first=True): i = 0 for e in slist: oid = id(e) typ = type(e) if oid in olist or typ is int: ## or e in olist: ## since we're excluding all ints, there is no longer a need to check for olist keys continue olist[oid] = e if first and (i%1000) == 0: gc.collect() tl = gc.get_referents(e) if tl: _getr(tl, olist, first=False) i += 1 # The public function. def get_all_objects(): """Return a list of all live Python objects (excluding int and long), not including the list itself.""" gc.collect() gcl = gc.get_objects() olist = {} _getr(gcl, olist) del olist[id(olist)] del olist[id(gcl)] del olist[id(sys._getframe())] return olist def lookup(oid, objects=None): """Return an object given its ID, if it exists.""" if objects is None: objects = get_all_objects() return objects[oid] class ObjTracker(object): """ Tracks all objects under the sun, reporting the changes between snapshots: what objects are created, deleted, and persistent. This class is very useful for tracking memory leaks. The class goes to great (but not heroic) lengths to avoid tracking its own internal objects. Example: ot = ObjTracker() # takes snapshot of currently existing objects ... do stuff ... ot.diff() # prints lists of objects created and deleted since ot was initialized ... do stuff ... ot.diff() # prints lists of objects created and deleted since last call to ot.diff() # also prints list of items that were created since initialization AND have not been deleted yet # (if done correctly, this list can tell you about objects that were leaked) arrays = ot.findPersistent('ndarray') ## returns all objects matching 'ndarray' (string match, not instance checking) ## that were considered persistent when the last diff() was run describeObj(arrays[0]) ## See if we can determine who has references to this array """ allObjs = {} ## keep track of all objects created and stored within class instances allObjs[id(allObjs)] = None def __init__(self): self.startRefs = {} ## list of objects that exist when the tracker is initialized {oid: weakref} ## (If it is not possible to weakref the object, then the value is None) self.startCount = {} self.newRefs = {} ## list of objects that have been created since initialization self.persistentRefs = {} ## list of objects considered 'persistent' when the last diff() was called self.objTypes = {} ObjTracker.allObjs[id(self)] = None self.objs = [self.__dict__, self.startRefs, self.startCount, self.newRefs, self.persistentRefs, self.objTypes] self.objs.append(self.objs) for v in self.objs: ObjTracker.allObjs[id(v)] = None self.start() def findNew(self, regex): """Return all objects matching regex that were considered 'new' when the last diff() was run.""" return self.findTypes(self.newRefs, regex) def findPersistent(self, regex): """Return all objects matching regex that were considered 'persistent' when the last diff() was run.""" return self.findTypes(self.persistentRefs, regex) def start(self): """ Remember the current set of objects as the comparison for all future calls to diff() Called automatically on init, but can be called manually as well. """ refs, count, objs = self.collect() for r in self.startRefs: self.forgetRef(self.startRefs[r]) self.startRefs.clear() self.startRefs.update(refs) for r in refs: self.rememberRef(r) self.startCount.clear() self.startCount.update(count) #self.newRefs.clear() #self.newRefs.update(refs) def diff(self, **kargs): """ Compute all differences between the current object set and the reference set. Print a set of reports for created, deleted, and persistent objects """ refs, count, objs = self.collect() ## refs contains the list of ALL objects ## Which refs have disappeared since call to start() (these are only displayed once, then forgotten.) delRefs = {} for i in list(self.startRefs.keys()): if i not in refs: delRefs[i] = self.startRefs[i] del self.startRefs[i] self.forgetRef(delRefs[i]) for i in list(self.newRefs.keys()): if i not in refs: delRefs[i] = self.newRefs[i] del self.newRefs[i] self.forgetRef(delRefs[i]) #print "deleted:", len(delRefs) ## Which refs have appeared since call to start() or diff() persistentRefs = {} ## created since start(), but before last diff() createRefs = {} ## created since last diff() for o in refs: if o not in self.startRefs: if o not in self.newRefs: createRefs[o] = refs[o] ## object has been created since last diff() else: persistentRefs[o] = refs[o] ## object has been created since start(), but before last diff() (persistent) #print "new:", len(newRefs) ## self.newRefs holds the entire set of objects created since start() for r in self.newRefs: self.forgetRef(self.newRefs[r]) self.newRefs.clear() self.newRefs.update(persistentRefs) self.newRefs.update(createRefs) for r in self.newRefs: self.rememberRef(self.newRefs[r]) #print "created:", len(createRefs) ## self.persistentRefs holds all objects considered persistent. self.persistentRefs.clear() self.persistentRefs.update(persistentRefs) print("----------- Count changes since start: ----------") c1 = count.copy() for k in self.startCount: c1[k] = c1.get(k, 0) - self.startCount[k] typs = list(c1.keys()) typs.sort(key=lambda a: c1[a]) for t in typs: if c1[t] == 0: continue num = "%d" % c1[t] print(" " + num + " "*(10-len(num)) + str(t)) print("----------- %d Deleted since last diff: ------------" % len(delRefs)) self.report(delRefs, objs, **kargs) print("----------- %d Created since last diff: ------------" % len(createRefs)) self.report(createRefs, objs, **kargs) print("----------- %d Created since start (persistent): ------------" % len(persistentRefs)) self.report(persistentRefs, objs, **kargs) def __del__(self): self.startRefs.clear() self.startCount.clear() self.newRefs.clear() self.persistentRefs.clear() del ObjTracker.allObjs[id(self)] for v in self.objs: del ObjTracker.allObjs[id(v)] @classmethod def isObjVar(cls, o): return type(o) is cls or id(o) in cls.allObjs def collect(self): print("Collecting list of all objects...") gc.collect() objs = get_all_objects() frame = sys._getframe() del objs[id(frame)] ## ignore the current frame del objs[id(frame.f_code)] ignoreTypes = [int] refs = {} count = {} for k in objs: o = objs[k] typ = type(o) oid = id(o) if ObjTracker.isObjVar(o) or typ in ignoreTypes: continue try: ref = weakref.ref(obj) except: ref = None refs[oid] = ref typ = type(o) typStr = typeStr(o) self.objTypes[oid] = typStr ObjTracker.allObjs[id(typStr)] = None count[typ] = count.get(typ, 0) + 1 print("All objects: %d Tracked objects: %d" % (len(objs), len(refs))) return refs, count, objs def forgetRef(self, ref): if ref is not None: del ObjTracker.allObjs[id(ref)] def rememberRef(self, ref): ## Record the address of the weakref object so it is not included in future object counts. if ref is not None: ObjTracker.allObjs[id(ref)] = None def lookup(self, oid, ref, objs=None): if ref is None or ref() is None: try: obj = lookup(oid, objects=objs) except: obj = None else: obj = ref() return obj def report(self, refs, allobjs=None, showIDs=False): if allobjs is None: allobjs = get_all_objects() count = {} rev = {} for oid in refs: obj = self.lookup(oid, refs[oid], allobjs) if obj is None: typ = "[del] " + self.objTypes[oid] else: typ = typeStr(obj) if typ not in rev: rev[typ] = [] rev[typ].append(oid) c = count.get(typ, [0,0]) count[typ] = [c[0]+1, c[1]+objectSize(obj)] typs = list(count.keys()) typs.sort(key=lambda a: count[a][1]) for t in typs: line = " %d\t%d\t%s" % (count[t][0], count[t][1], t) if showIDs: line += "\t"+",".join(map(str,rev[t])) print(line) def findTypes(self, refs, regex): allObjs = get_all_objects() ids = {} objs = [] r = re.compile(regex) for k in refs: if r.search(self.objTypes[k]): objs.append(self.lookup(k, refs[k], allObjs)) return objs def describeObj(obj, depth=4, path=None, ignore=None): """ Trace all reference paths backward, printing a list of different ways this object can be accessed. Attempts to answer the question "who has a reference to this object" """ if path is None: path = [obj] if ignore is None: ignore = {} ## holds IDs of objects used within the function. ignore[id(sys._getframe())] = None ignore[id(path)] = None gc.collect() refs = gc.get_referrers(obj) ignore[id(refs)] = None printed=False for ref in refs: if id(ref) in ignore: continue if id(ref) in list(map(id, path)): print("Cyclic reference: " + refPathString([ref]+path)) printed = True continue newPath = [ref]+path if len(newPath) >= depth: refStr = refPathString(newPath) if '[_]' not in refStr: ## ignore '_' references generated by the interactive shell print(refStr) printed = True else: describeObj(ref, depth, newPath, ignore) printed = True if not printed: print("Dead end: " + refPathString(path)) def typeStr(obj): """Create a more useful type string by making <instance> types report their class.""" typ = type(obj) if typ == getattr(types, 'InstanceType', None): return "<instance of %s>" % obj.__class__.__name__ else: return str(typ) def searchRefs(obj, *args): """Pseudo-interactive function for tracing references backward. **Arguments:** obj: The initial object from which to start searching args: A set of string or int arguments. each integer selects one of obj's referrers to be the new 'obj' each string indicates an action to take on the current 'obj': t: print the types of obj's referrers l: print the lengths of obj's referrers (if they have __len__) i: print the IDs of obj's referrers o: print obj ro: return obj rr: return list of obj's referrers Examples:: searchRefs(obj, 't') ## Print types of all objects referring to obj searchRefs(obj, 't', 0, 't') ## ..then select the first referrer and print the types of its referrers searchRefs(obj, 't', 0, 't', 'l') ## ..also print lengths of the last set of referrers searchRefs(obj, 0, 1, 'ro') ## Select index 0 from obj's referrer, then select index 1 from the next set of referrers, then return that object """ ignore = {id(sys._getframe()): None} gc.collect() refs = gc.get_referrers(obj) ignore[id(refs)] = None refs = [r for r in refs if id(r) not in ignore] for a in args: #fo = allFrameObjs() #refs = [r for r in refs if r not in fo] if type(a) is int: obj = refs[a] gc.collect() refs = gc.get_referrers(obj) ignore[id(refs)] = None refs = [r for r in refs if id(r) not in ignore] elif a == 't': print(list(map(typeStr, refs))) elif a == 'i': print(list(map(id, refs))) elif a == 'l': def slen(o): if hasattr(o, '__len__'): return len(o) else: return None print(list(map(slen, refs))) elif a == 'o': print(obj) elif a == 'ro': return obj elif a == 'rr': return refs def allFrameObjs(): """Return list of frame objects in current stack. Useful if you want to ignore these objects in refernece searches""" f = sys._getframe() objs = [] while f is not None: objs.append(f) objs.append(f.f_code) #objs.append(f.f_locals) #objs.append(f.f_globals) #objs.append(f.f_builtins) f = f.f_back return objs def findObj(regex): """Return a list of objects whose typeStr matches regex""" allObjs = get_all_objects() objs = [] r = re.compile(regex) for i in allObjs: obj = allObjs[i] if r.search(typeStr(obj)): objs.append(obj) return objs def listRedundantModules(): """List modules that have been imported more than once via different paths.""" mods = {} for name, mod in sys.modules.items(): if not hasattr(mod, '__file__'): continue mfile = os.path.abspath(mod.__file__) if mfile[-1] == 'c': mfile = mfile[:-1] if mfile in mods: print("module at %s has 2 names: %s, %s" % (mfile, name, mods[mfile])) else: mods[mfile] = name def walkQObjectTree(obj, counts=None, verbose=False, depth=0): """ Walk through a tree of QObjects, doing nothing to them. The purpose of this function is to find dead objects and generate a crash immediately rather than stumbling upon them later. Prints a count of the objects encountered, for fun. (or is it?) """ if verbose: print(" "*depth + typeStr(obj)) report = False if counts is None: counts = {} report = True typ = str(type(obj)) try: counts[typ] += 1 except KeyError: counts[typ] = 1 for child in obj.children(): walkQObjectTree(child, counts, verbose, depth+1) return counts QObjCache = {} def qObjectReport(verbose=False): """Generate a report counting all QObjects and their types""" global qObjCache count = {} for obj in findObj('PyQt'): if isinstance(obj, QtCore.QObject): oid = id(obj) if oid not in QObjCache: QObjCache[oid] = typeStr(obj) + " " + obj.objectName() try: QObjCache[oid] += " " + obj.parent().objectName() QObjCache[oid] += " " + obj.text() except: pass print("check obj", oid, str(QObjCache[oid])) if obj.parent() is None: walkQObjectTree(obj, count, verbose) typs = list(count.keys()) typs.sort() for t in typs: print(count[t], "\t", t) class PrintDetector(object): """Find code locations that print to stdout.""" def __init__(self): self.stdout = sys.stdout sys.stdout = self def remove(self): sys.stdout = self.stdout def __del__(self): self.remove() def write(self, x): self.stdout.write(x) traceback.print_stack() def flush(self): self.stdout.flush() def listQThreads(): """Prints Thread IDs (Qt's, not OS's) for all QThreads.""" thr = findObj('[Tt]hread') thr = [t for t in thr if isinstance(t, QtCore.QThread)] import sip for t in thr: print("--> ", t) print(" Qt ID: 0x%x" % sip.unwrapinstance(t)) def pretty(data, indent=''): """Format nested dict/list/tuple structures into a more human-readable string This function is a bit better than pprint for displaying OrderedDicts. """ ret = "" ind2 = indent + " " if isinstance(data, dict): ret = indent+"{\n" for k, v in data.items(): ret += ind2 + repr(k) + ": " + pretty(v, ind2).strip() + "\n" ret += indent+"}\n" elif isinstance(data, list) or isinstance(data, tuple): s = repr(data) if len(s) < 40: ret += indent + s else: if isinstance(data, list): d = '[]' else: d = '()' ret = indent+d[0]+"\n" for i, v in enumerate(data): ret += ind2 + str(i) + ": " + pretty(v, ind2).strip() + "\n" ret += indent+d[1]+"\n" else: ret += indent + repr(data) return ret class ThreadTrace(object): """ Used to debug freezing by starting a new thread that reports on the location of other threads periodically. """ def __init__(self, interval=10.0): self.interval = interval self.lock = Mutex() self._stop = False self.start() def stop(self): with self.lock: self._stop = True def start(self, interval=None): if interval is not None: self.interval = interval self._stop = False self.thread = threading.Thread(target=self.run) self.thread.daemon = True self.thread.start() def run(self): while True: with self.lock: if self._stop is True: return print("\n============= THREAD FRAMES: ================") for id, frame in sys._current_frames().items(): if id == threading.current_thread().ident: continue print("<< thread %d >>" % id) traceback.print_stack(frame) print("===============================================\n") time.sleep(self.interval) class ThreadColor(object): """ Wrapper on stdout/stderr that colors text by the current thread ID. *stream* must be 'stdout' or 'stderr'. """ colors = {} lock = Mutex() def __init__(self, stream): self.stream = getattr(sys, stream) self.err = stream == 'stderr' setattr(sys, stream, self) def write(self, msg): with self.lock: cprint.cprint(self.stream, self.color(), msg, -1, stderr=self.err) def flush(self): with self.lock: self.stream.flush() def color(self): tid = threading.current_thread() if tid not in self.colors: c = (len(self.colors) % 15) + 1 self.colors[tid] = c return self.colors[tid] def enableFaulthandler(): """ Enable faulthandler for all threads. If the faulthandler package is available, this function disables and then re-enables fault handling for all threads (this is necessary to ensure any new threads are handled correctly), and returns True. If faulthandler is not available, then returns False. """ try: import faulthandler # necessary to disable first or else new threads may not be handled. faulthandler.disable() faulthandler.enable(all_threads=True) return True except ImportError: return False
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/units.py
.py
1,402
64
# -*- coding: utf-8 -*- ## Very simple unit support: ## - creates variable names like 'mV' and 'kHz' ## - the value assigned to the variable corresponds to the scale prefix ## (mV = 0.001) ## - the actual units are purely cosmetic for making code clearer: ## ## x = 20*pA is identical to x = 20*1e-12 ## No unicode variable names (μ,Ω) allowed until python 3 SI_PREFIXES = 'yzafpnum kMGTPEZY' UNITS = 'm,s,g,W,J,V,A,F,T,Hz,Ohm,S,N,C,px,b,B'.split(',') allUnits = {} def addUnit(p, n): g = globals() v = 1000**n for u in UNITS: g[p+u] = v allUnits[p+u] = v for p in SI_PREFIXES: if p == ' ': p = '' n = 0 elif p == 'u': n = -2 else: n = SI_PREFIXES.index(p) - 8 addUnit(p, n) cm = 0.01 def evalUnits(unitStr): """ Evaluate a unit string into ([numerators,...], [denominators,...]) Examples: N m/s^2 => ([N, m], [s, s]) A*s / V => ([A, s], [V,]) """ pass def formatUnits(units): """ Format a unit specification ([numerators,...], [denominators,...]) into a string (this is the inverse of evalUnits) """ pass def simplify(units): """ Cancel units that appear in both numerator and denominator, then attempt to replace groups of units with single units where possible (ie, J/s => W) """ pass
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/Point.py
.py
4,633
162
# -*- coding: utf-8 -*- """ Point.py - Extension of QPointF which adds a few missing methods. Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. """ from .Qt import QtCore import numpy as np def clip(x, mn, mx): if x > mx: return mx if x < mn: return mn return x class Point(QtCore.QPointF): """Extension of QPointF which adds a few missing methods.""" def __init__(self, *args): if len(args) == 1: if isinstance(args[0], QtCore.QSizeF): QtCore.QPointF.__init__(self, float(args[0].width()), float(args[0].height())) return elif isinstance(args[0], float) or isinstance(args[0], int): QtCore.QPointF.__init__(self, float(args[0]), float(args[0])) return elif hasattr(args[0], '__getitem__'): QtCore.QPointF.__init__(self, float(args[0][0]), float(args[0][1])) return elif len(args) == 2: QtCore.QPointF.__init__(self, args[0], args[1]) return QtCore.QPointF.__init__(self, *args) def __len__(self): return 2 def __reduce__(self): return (Point, (self.x(), self.y())) def __getitem__(self, i): if i == 0: return self.x() elif i == 1: return self.y() else: raise IndexError("Point has no index %s" % str(i)) def __setitem__(self, i, x): if i == 0: return self.setX(x) elif i == 1: return self.setY(x) else: raise IndexError("Point has no index %s" % str(i)) def __radd__(self, a): return self._math_('__radd__', a) def __add__(self, a): return self._math_('__add__', a) def __rsub__(self, a): return self._math_('__rsub__', a) def __sub__(self, a): return self._math_('__sub__', a) def __rmul__(self, a): return self._math_('__rmul__', a) def __mul__(self, a): return self._math_('__mul__', a) def __rdiv__(self, a): return self._math_('__rdiv__', a) def __div__(self, a): return self._math_('__div__', a) def __truediv__(self, a): return self._math_('__truediv__', a) def __rtruediv__(self, a): return self._math_('__rtruediv__', a) def __rpow__(self, a): return self._math_('__rpow__', a) def __pow__(self, a): return self._math_('__pow__', a) def _math_(self, op, x): #print "point math:", op #try: #fn = getattr(QtCore.QPointF, op) #pt = fn(self, x) #print fn, pt, self, x #return Point(pt) #except AttributeError: x = Point(x) return Point(getattr(self[0], op)(x[0]), getattr(self[1], op)(x[1])) def length(self): """Returns the vector length of this Point.""" try: return (self[0]**2 + self[1]**2) ** 0.5 except OverflowError: try: return self[1] / np.sin(np.arctan2(self[1], self[0])) except OverflowError: return np.inf def norm(self): """Returns a vector in the same direction with unit length.""" return self / self.length() def angle(self, a): """Returns the angle in degrees between this vector and the vector a.""" n1 = self.length() n2 = a.length() if n1 == 0. or n2 == 0.: return None ## Probably this should be done with arctan2 instead.. ang = np.arccos(clip(self.dot(a) / (n1 * n2), -1.0, 1.0)) ### in radians c = self.cross(a) if c > 0: ang *= -1. return ang * 180. / np.pi def dot(self, a): """Returns the dot product of a and this Point.""" a = Point(a) return self[0]*a[0] + self[1]*a[1] def cross(self, a): a = Point(a) return self[0]*a[1] - self[1]*a[0] def proj(self, b): """Return the projection of this vector onto the vector b""" b1 = b / b.length() return self.dot(b1) * b1 def __repr__(self): return "Point(%f, %f)" % (self[0], self[1]) def min(self): return min(self[0], self[1]) def max(self): return max(self[0], self[1]) def copy(self): return Point(self) def toQPoint(self): return QtCore.QPoint(*self)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exceptionHandling.py
.py
4,149
107
# -*- coding: utf-8 -*- """This module installs a wrapper around sys.excepthook which allows multiple new exception handlers to be registered. Optionally, the wrapper also stops exceptions from causing long-term storage of local stack frames. This has two major effects: - Unhandled exceptions will no longer cause memory leaks (If an exception occurs while a lot of data is present on the stack, such as when loading large files, the data would ordinarily be kept until the next exception occurs. We would rather release this memory as soon as possible.) - Some debuggers may have a hard time handling uncaught exceptions The module also provides a callback mechanism allowing others to respond to exceptions. """ import sys, time #from lib.Manager import logMsg import traceback #from log import * #logging = False callbacks = [] clear_tracebacks = False def register(fn): """ Register a callable to be invoked when there is an unhandled exception. The callback will be passed the output of sys.exc_info(): (exception type, exception, traceback) Multiple callbacks will be invoked in the order they were registered. """ callbacks.append(fn) def unregister(fn): """Unregister a previously registered callback.""" callbacks.remove(fn) def setTracebackClearing(clear=True): """ Enable or disable traceback clearing. By default, clearing is disabled and Python will indefinitely store unhandled exception stack traces. This function is provided since Python's default behavior can cause unexpected retention of large memory-consuming objects. """ global clear_tracebacks clear_tracebacks = clear class ExceptionHandler(object): def __call__(self, *args): ## Start by extending recursion depth just a bit. ## If the error we are catching is due to recursion, we don't want to generate another one here. recursionLimit = sys.getrecursionlimit() try: sys.setrecursionlimit(recursionLimit+100) ## call original exception handler first (prints exception) global original_excepthook, callbacks, clear_tracebacks try: print("===== %s =====" % str(time.strftime("%Y.%m.%d %H:%m:%S", time.localtime(time.time())))) except Exception: sys.stderr.write("Warning: stdout is broken! Falling back to stderr.\n") sys.stdout = sys.stderr ret = original_excepthook(*args) for cb in callbacks: try: cb(*args) except Exception: print(" --------------------------------------------------------------") print(" Error occurred during exception callback %s" % str(cb)) print(" --------------------------------------------------------------") traceback.print_exception(*sys.exc_info()) ## Clear long-term storage of last traceback to prevent memory-hogging. ## (If an exception occurs while a lot of data is present on the stack, ## such as when loading large files, the data would ordinarily be kept ## until the next exception occurs. We would rather release this memory ## as soon as possible.) if clear_tracebacks is True: sys.last_traceback = None finally: sys.setrecursionlimit(recursionLimit) def implements(self, interface=None): ## this just makes it easy for us to detect whether an ExceptionHook is already installed. if interface is None: return ['ExceptionHandler'] else: return interface == 'ExceptionHandler' ## replace built-in excepthook only if this has not already been done if not (hasattr(sys.excepthook, 'implements') and sys.excepthook.implements('ExceptionHandler')): original_excepthook = sys.excepthook sys.excepthook = ExceptionHandler()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/__init__.py
.py
18,237
473
# -*- coding: utf-8 -*- """ PyQtGraph - Scientific Graphics and GUI Library for Python www.pyqtgraph.org """ __version__ = '0.11.0.dev0' ### import all the goodies and add some helper functions for easy CLI use ## 'Qt' is a local module; it is intended mainly to cover up the differences ## between PyQt4 and PySide. from .Qt import QtGui, mkQApp ## not really safe--If we accidentally create another QApplication, the process hangs (and it is very difficult to trace the cause) #if QtGui.QApplication.instance() is None: #app = QtGui.QApplication([]) import numpy ## pyqtgraph requires numpy ## (import here to avoid massive error dump later on if numpy is not available) import os, sys ## check python version ## Allow anything >= 2.7 if sys.version_info[0] < 2 or (sys.version_info[0] == 2 and sys.version_info[1] < 6): raise Exception("Pyqtgraph requires Python version 2.6 or greater (this is %d.%d)" % (sys.version_info[0], sys.version_info[1])) ## helpers for 2/3 compatibility from . import python2_3 ## in general openGL is poorly supported with Qt+GraphicsView. ## we only enable it where the performance benefit is critical. ## Note this only applies to 2D graphics; 3D graphics always use OpenGL. if 'linux' in sys.platform: ## linux has numerous bugs in opengl implementation useOpenGL = False elif 'darwin' in sys.platform: ## openGL can have a major impact on mac, but also has serious bugs useOpenGL = False if QtGui.QApplication.instance() is not None: print('Warning: QApplication was created before pyqtgraph was imported; there may be problems (to avoid bugs, call QApplication.setGraphicsSystem("raster") before the QApplication is created).') if QtGui.QApplication.setGraphicsSystem: QtGui.QApplication.setGraphicsSystem('raster') ## work around a variety of bugs in the native graphics system else: useOpenGL = False ## on windows there's a more even performance / bugginess tradeoff. CONFIG_OPTIONS = { 'useOpenGL': useOpenGL, ## by default, this is platform-dependent (see widgets/GraphicsView). Set to True or False to explicitly enable/disable opengl. 'leftButtonPan': True, ## if false, left button drags a rubber band for zooming in viewbox # foreground/background take any arguments to the 'mkColor' in /pyqtgraph/functions.py 'foreground': 'd', ## default foreground color for axes, labels, etc. 'background': 'k', ## default background for GraphicsWidget 'antialias': False, 'editorCommand': None, ## command used to invoke code editor from ConsoleWidgets 'useWeave': False, ## Use weave to speed up some operations, if it is available 'weaveDebug': False, ## Print full error message if weave compile fails 'exitCleanup': True, ## Attempt to work around some exit crash bugs in PyQt and PySide 'enableExperimental': False, ## Enable experimental features (the curious can search for this key in the code) 'crashWarning': False, # If True, print warnings about situations that may result in a crash 'imageAxisOrder': 'col-major', # For 'row-major', image data is expected in the standard (row, col) order. # For 'col-major', image data is expected in reversed (col, row) order. # The default is 'col-major' for backward compatibility, but this may # change in the future. } def setConfigOption(opt, value): if opt not in CONFIG_OPTIONS: raise KeyError('Unknown configuration option "%s"' % opt) if opt == 'imageAxisOrder' and value not in ('row-major', 'col-major'): raise ValueError('imageAxisOrder must be either "row-major" or "col-major"') CONFIG_OPTIONS[opt] = value def setConfigOptions(**opts): """Set global configuration options. Each keyword argument sets one global option. """ for k,v in opts.items(): setConfigOption(k, v) def getConfigOption(opt): """Return the value of a single global configuration option. """ return CONFIG_OPTIONS[opt] def systemInfo(): print("sys.platform: %s" % sys.platform) print("sys.version: %s" % sys.version) from .Qt import VERSION_INFO print("qt bindings: %s" % VERSION_INFO) global __version__ rev = None if __version__ is None: ## this code was probably checked out from bzr; look up the last-revision file lastRevFile = os.path.join(os.path.dirname(__file__), '..', '.bzr', 'branch', 'last-revision') if os.path.exists(lastRevFile): with open(lastRevFile, 'r') as fd: rev = fd.read().strip() print("pyqtgraph: %s; %s" % (__version__, rev)) print("config:") import pprint pprint.pprint(CONFIG_OPTIONS) ## Rename orphaned .pyc files. This is *probably* safe :) ## We only do this if __version__ is None, indicating the code was probably pulled ## from the repository. def renamePyc(startDir): ### Used to rename orphaned .pyc files ### When a python file changes its location in the repository, usually the .pyc file ### is left behind, possibly causing mysterious and difficult to track bugs. ### Note that this is no longer necessary for python 3.2; from PEP 3147: ### "If the py source file is missing, the pyc file inside __pycache__ will be ignored. ### This eliminates the problem of accidental stale pyc file imports." printed = False startDir = os.path.abspath(startDir) for path, dirs, files in os.walk(startDir): if '__pycache__' in path: continue for f in files: fileName = os.path.join(path, f) base, ext = os.path.splitext(fileName) py = base + ".py" if ext == '.pyc' and not os.path.isfile(py): if not printed: print("NOTE: Renaming orphaned .pyc files:") printed = True n = 1 while True: name2 = fileName + ".renamed%d" % n if not os.path.exists(name2): break n += 1 print(" " + fileName + " ==>") print(" " + name2) os.rename(fileName, name2) path = os.path.split(__file__)[0] if __version__ is None and not hasattr(sys, 'frozen') and sys.version_info[0] == 2: ## If we are frozen, there's a good chance we don't have the original .py files anymore. renamePyc(path) ## Import almost everything to make it available from a single namespace ## don't import the more complex systems--canvas, parametertree, flowchart, dockarea ## these must be imported separately. #from . import frozenSupport #def importModules(path, globals, locals, excludes=()): #"""Import all modules residing within *path*, return a dict of name: module pairs. #Note that *path* MUST be relative to the module doing the import. #""" #d = os.path.join(os.path.split(globals['__file__'])[0], path) #files = set() #for f in frozenSupport.listdir(d): #if frozenSupport.isdir(os.path.join(d, f)) and f not in ['__pycache__', 'tests']: #files.add(f) #elif f[-3:] == '.py' and f != '__init__.py': #files.add(f[:-3]) #elif f[-4:] == '.pyc' and f != '__init__.pyc': #files.add(f[:-4]) #mods = {} #path = path.replace(os.sep, '.') #for modName in files: #if modName in excludes: #continue #try: #if len(path) > 0: #modName = path + '.' + modName #print( "from .%s import * " % modName) #mod = __import__(modName, globals, locals, ['*'], 1) #mods[modName] = mod #except: #import traceback #traceback.print_stack() #sys.excepthook(*sys.exc_info()) #print("[Error importing module: %s]" % modName) #return mods #def importAll(path, globals, locals, excludes=()): #"""Given a list of modules, import all names from each module into the global namespace.""" #mods = importModules(path, globals, locals, excludes) #for mod in mods.values(): #if hasattr(mod, '__all__'): #names = mod.__all__ #else: #names = [n for n in dir(mod) if n[0] != '_'] #for k in names: #if hasattr(mod, k): #globals[k] = getattr(mod, k) # Dynamic imports are disabled. This causes too many problems. #importAll('graphicsItems', globals(), locals()) #importAll('widgets', globals(), locals(), #excludes=['MatplotlibWidget', 'RawImageWidget', 'RemoteGraphicsView']) from .graphicsItems.VTickGroup import * from .graphicsItems.GraphicsWidget import * from .graphicsItems.ScaleBar import * from .graphicsItems.PlotDataItem import * from .graphicsItems.GraphItem import * from .graphicsItems.TextItem import * from .graphicsItems.GraphicsLayout import * from .graphicsItems.UIGraphicsItem import * from .graphicsItems.GraphicsObject import * from .graphicsItems.PlotItem import * from .graphicsItems.ROI import * from .graphicsItems.InfiniteLine import * from .graphicsItems.HistogramLUTItem import * from .graphicsItems.GridItem import * from .graphicsItems.GradientLegend import * from .graphicsItems.GraphicsItem import * from .graphicsItems.BarGraphItem import * from .graphicsItems.ViewBox import * from .graphicsItems.ArrowItem import * from .graphicsItems.ImageItem import * from .graphicsItems.AxisItem import * from .graphicsItems.DateAxisItem import * from .graphicsItems.LabelItem import * from .graphicsItems.CurvePoint import * from .graphicsItems.GraphicsWidgetAnchor import * from .graphicsItems.PlotCurveItem import * from .graphicsItems.ButtonItem import * from .graphicsItems.GradientEditorItem import * from .graphicsItems.MultiPlotItem import * from .graphicsItems.ErrorBarItem import * from .graphicsItems.IsocurveItem import * from .graphicsItems.LinearRegionItem import * from .graphicsItems.FillBetweenItem import * from .graphicsItems.LegendItem import * from .graphicsItems.ScatterPlotItem import * from .graphicsItems.ItemGroup import * from .widgets.MultiPlotWidget import * from .widgets.ScatterPlotWidget import * from .widgets.ColorMapWidget import * from .widgets.FileDialog import * from .widgets.ValueLabel import * from .widgets.HistogramLUTWidget import * from .widgets.CheckTable import * from .widgets.BusyCursor import * from .widgets.PlotWidget import * from .widgets.ComboBox import * from .widgets.GradientWidget import * from .widgets.DataFilterWidget import * from .widgets.SpinBox import * from .widgets.JoystickButton import * from .widgets.GraphicsLayoutWidget import * from .widgets.TreeWidget import * from .widgets.PathButton import * from .widgets.VerticalLabel import * from .widgets.FeedbackButton import * from .widgets.ColorButton import * from .widgets.DataTreeWidget import * from .widgets.DiffTreeWidget import * from .widgets.GraphicsView import * from .widgets.LayoutWidget import * from .widgets.TableWidget import * from .widgets.ProgressDialog import * from .widgets.GroupBox import GroupBox from .widgets.RemoteGraphicsView import RemoteGraphicsView from .imageview import * from .WidgetGroup import * from .Point import Point from .Vector import Vector from .SRTTransform import SRTTransform from .Transform3D import Transform3D from .SRTTransform3D import SRTTransform3D from .functions import * from .graphicsWindows import * from .SignalProxy import * from .colormap import * from .ptime import time from .Qt import isQObjectAlive ############################################################## ## PyQt and PySide both are prone to crashing on exit. ## There are two general approaches to dealing with this: ## 1. Install atexit handlers that assist in tearing down to avoid crashes. ## This helps, but is never perfect. ## 2. Terminate the process before python starts tearing down ## This is potentially dangerous ## Attempts to work around exit crashes: import atexit _cleanupCalled = False def cleanup(): global _cleanupCalled if _cleanupCalled: return if not getConfigOption('exitCleanup'): return ViewBox.quit() ## tell ViewBox that it doesn't need to deregister views anymore. ## Workaround for Qt exit crash: ## ALL QGraphicsItems must have a scene before they are deleted. ## This is potentially very expensive, but preferred over crashing. ## Note: this appears to be fixed in PySide as of 2012.12, but it should be left in for a while longer.. app = QtGui.QApplication.instance() if app is None or not isinstance(app, QtGui.QApplication): # app was never constructed is already deleted or is an # QCoreApplication/QGuiApplication and not a full QApplication return import gc s = QtGui.QGraphicsScene() for o in gc.get_objects(): try: if isinstance(o, QtGui.QGraphicsItem) and isQObjectAlive(o) and o.scene() is None: if getConfigOption('crashWarning'): sys.stderr.write('Error: graphics item without scene. ' 'Make sure ViewBox.close() and GraphicsView.close() ' 'are properly called before app shutdown (%s)\n' % (o,)) s.addItem(o) except (RuntimeError, ReferenceError): ## occurs if a python wrapper no longer has its underlying C++ object continue _cleanupCalled = True atexit.register(cleanup) # Call cleanup when QApplication quits. This is necessary because sometimes # the QApplication will quit before the atexit callbacks are invoked. # Note: cannot connect this function until QApplication has been created, so # instead we have GraphicsView.__init__ call this for us. _cleanupConnected = False def _connectCleanup(): global _cleanupConnected if _cleanupConnected: return QtGui.QApplication.instance().aboutToQuit.connect(cleanup) _cleanupConnected = True ## Optional function for exiting immediately (with some manual teardown) def exit(): """ Causes python to exit without garbage-collecting any objects, and thus avoids calling object destructor methods. This is a sledgehammer workaround for a variety of bugs in PyQt and Pyside that cause crashes on exit. This function does the following in an attempt to 'safely' terminate the process: * Invoke atexit callbacks * Close all open file handles * os._exit() Note: there is some potential for causing damage with this function if you are using objects that _require_ their destructors to be called (for example, to properly terminate log files, disconnect from devices, etc). Situations like this are probably quite rare, but use at your own risk. """ ## first disable our own cleanup function; won't be needing it. setConfigOptions(exitCleanup=False) ## invoke atexit callbacks atexit._run_exitfuncs() ## close file handles if sys.platform == 'darwin': for fd in range(3, 4096): if fd in [7]: # trying to close 7 produces an illegal instruction on the Mac. continue try: os.close(fd) except OSError: pass else: os.closerange(3, 4096) ## just guessing on the maximum descriptor count.. os._exit(0) ## Convenience functions for command-line use plots = [] images = [] QAPP = None def plot(*args, **kargs): """ Create and return a :class:`PlotWindow <pyqtgraph.PlotWindow>` (this is just a window with :class:`PlotWidget <pyqtgraph.PlotWidget>` inside), plot data in it. Accepts a *title* argument to set the title of the window. All other arguments are used to plot data. (see :func:`PlotItem.plot() <pyqtgraph.PlotItem.plot>`) """ mkQApp() #if 'title' in kargs: #w = PlotWindow(title=kargs['title']) #del kargs['title'] #else: #w = PlotWindow() #if len(args)+len(kargs) > 0: #w.plot(*args, **kargs) pwArgList = ['title', 'labels', 'name', 'left', 'right', 'top', 'bottom', 'background'] pwArgs = {} dataArgs = {} for k in kargs: if k in pwArgList: pwArgs[k] = kargs[k] else: dataArgs[k] = kargs[k] w = PlotWindow(**pwArgs) if len(args) > 0 or len(dataArgs) > 0: w.plot(*args, **dataArgs) plots.append(w) w.show() return w def image(*args, **kargs): """ Create and return an :class:`ImageWindow <pyqtgraph.ImageWindow>` (this is just a window with :class:`ImageView <pyqtgraph.ImageView>` widget inside), show image data inside. Will show 2D or 3D image data. Accepts a *title* argument to set the title of the window. All other arguments are used to show data. (see :func:`ImageView.setImage() <pyqtgraph.ImageView.setImage>`) """ mkQApp() w = ImageWindow(*args, **kargs) images.append(w) w.show() return w show = image ## for backward compatibility def dbg(*args, **kwds): """ Create a console window and begin watching for exceptions. All arguments are passed to :func:`ConsoleWidget.__init__() <pyqtgraph.console.ConsoleWidget.__init__>`. """ mkQApp() from . import console c = console.ConsoleWidget(*args, **kwds) c.catchAllExceptions() c.show() global consoles try: consoles.append(c) except NameError: consoles = [c] return c def stack(*args, **kwds): """ Create a console window and show the current stack trace. All arguments are passed to :func:`ConsoleWidget.__init__() <pyqtgraph.console.ConsoleWidget.__init__>`. """ mkQApp() from . import console c = console.ConsoleWidget(*args, **kwds) c.setStack() c.show() global consoles try: consoles.append(c) except NameError: consoles = [c] return c
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/colormap.py
.py
9,998
260
import numpy as np from .Qt import QtGui, QtCore from .python2_3 import basestring from .functions import mkColor class ColorMap(object): """ A ColorMap defines a relationship between a scalar value and a range of colors. ColorMaps are commonly used for false-coloring monochromatic images, coloring scatter-plot points, and coloring surface plots by height. Each color map is defined by a set of colors, each corresponding to a particular scalar value. For example: | 0.0 -> black | 0.2 -> red | 0.6 -> yellow | 1.0 -> white The colors for intermediate values are determined by interpolating between the two nearest colors in either RGB or HSV color space. To provide user-defined color mappings, see :class:`GradientWidget <pyqtgraph.GradientWidget>`. """ ## color interpolation modes RGB = 1 HSV_POS = 2 HSV_NEG = 3 ## boundary modes CLIP = 1 REPEAT = 2 MIRROR = 3 ## return types BYTE = 1 FLOAT = 2 QCOLOR = 3 enumMap = { 'rgb': RGB, 'hsv+': HSV_POS, 'hsv-': HSV_NEG, 'clip': CLIP, 'repeat': REPEAT, 'mirror': MIRROR, 'byte': BYTE, 'float': FLOAT, 'qcolor': QCOLOR, } def __init__(self, pos, color, mode=None): """ =============== ============================================================== **Arguments:** pos Array of positions where each color is defined color Array of colors. Values are interpreted via :func:`mkColor() <pyqtgraph.mkColor>`. mode Array of color modes (ColorMap.RGB, HSV_POS, or HSV_NEG) indicating the color space that should be used when interpolating between stops. Note that the last mode value is ignored. By default, the mode is entirely RGB. =============== ============================================================== """ self.pos = np.array(pos) order = np.argsort(self.pos) self.pos = self.pos[order] self.color = np.apply_along_axis( func1d = lambda x: mkColor(x).getRgb(), axis = -1, arr = color, )[order] if mode is None: mode = np.ones(len(pos)) self.mode = mode self.stopsCache = {} def map(self, data, mode='byte'): """ Return an array of colors corresponding to the values in *data*. Data must be either a scalar position or an array (any shape) of positions. The *mode* argument determines the type of data returned: =========== =============================================================== byte (default) Values are returned as 0-255 unsigned bytes. float Values are returned as 0.0-1.0 floats. qcolor Values are returned as an array of QColor objects. =========== =============================================================== """ if isinstance(mode, basestring): mode = self.enumMap[mode.lower()] if mode == self.QCOLOR: pos, color = self.getStops(self.BYTE) else: pos, color = self.getStops(mode) # don't need this--np.interp takes care of it. #data = np.clip(data, pos.min(), pos.max()) # Interpolate # TODO: is griddata faster? # interp = scipy.interpolate.griddata(pos, color, data) if np.isscalar(data): interp = np.empty((color.shape[1],), dtype=color.dtype) else: if not isinstance(data, np.ndarray): data = np.array(data) interp = np.empty(data.shape + (color.shape[1],), dtype=color.dtype) for i in range(color.shape[1]): interp[...,i] = np.interp(data, pos, color[:,i]) # Convert to QColor if requested if mode == self.QCOLOR: if np.isscalar(data): return QtGui.QColor(*interp) else: return [QtGui.QColor(*x) for x in interp] else: return interp def mapToQColor(self, data): """Convenience function; see :func:`map() <pyqtgraph.ColorMap.map>`.""" return self.map(data, mode=self.QCOLOR) def mapToByte(self, data): """Convenience function; see :func:`map() <pyqtgraph.ColorMap.map>`.""" return self.map(data, mode=self.BYTE) def mapToFloat(self, data): """Convenience function; see :func:`map() <pyqtgraph.ColorMap.map>`.""" return self.map(data, mode=self.FLOAT) def getGradient(self, p1=None, p2=None): """Return a QLinearGradient object spanning from QPoints p1 to p2.""" if p1 == None: p1 = QtCore.QPointF(0,0) if p2 == None: p2 = QtCore.QPointF(self.pos.max()-self.pos.min(),0) g = QtGui.QLinearGradient(p1, p2) pos, color = self.getStops(mode=self.BYTE) color = [QtGui.QColor(*x) for x in color] g.setStops(list(zip(pos, color))) #if self.colorMode == 'rgb': #ticks = self.listTicks() #g.setStops([(x, QtGui.QColor(t.color)) for t,x in ticks]) #elif self.colorMode == 'hsv': ## HSV mode is approximated for display by interpolating 10 points between each stop #ticks = self.listTicks() #stops = [] #stops.append((ticks[0][1], ticks[0][0].color)) #for i in range(1,len(ticks)): #x1 = ticks[i-1][1] #x2 = ticks[i][1] #dx = (x2-x1) / 10. #for j in range(1,10): #x = x1 + dx*j #stops.append((x, self.getColor(x))) #stops.append((x2, self.getColor(x2))) #g.setStops(stops) return g def getColors(self, mode=None): """Return list of all color stops converted to the specified mode. If mode is None, then no conversion is done.""" if isinstance(mode, basestring): mode = self.enumMap[mode.lower()] color = self.color if mode in [self.BYTE, self.QCOLOR] and color.dtype.kind == 'f': color = (color * 255).astype(np.ubyte) elif mode == self.FLOAT and color.dtype.kind != 'f': color = color.astype(float) / 255. if mode == self.QCOLOR: color = [QtGui.QColor(*x) for x in color] return color def getStops(self, mode): ## Get fully-expanded set of RGBA stops in either float or byte mode. if mode not in self.stopsCache: color = self.color if mode == self.BYTE and color.dtype.kind == 'f': color = (color * 255).astype(np.ubyte) elif mode == self.FLOAT and color.dtype.kind != 'f': color = color.astype(float) / 255. ## to support HSV mode, we need to do a little more work.. #stops = [] #for i in range(len(self.pos)): #pos = self.pos[i] #color = color[i] #imode = self.mode[i] #if imode == self.RGB: #stops.append((x,color)) #else: #ns = self.stopsCache[mode] = (self.pos, color) return self.stopsCache[mode] def getLookupTable(self, start=0.0, stop=1.0, nPts=512, alpha=None, mode='byte'): """ Return an RGB(A) lookup table (ndarray). =============== ============================================================================= **Arguments:** start The starting value in the lookup table (default=0.0) stop The final value in the lookup table (default=1.0) nPts The number of points in the returned lookup table. alpha True, False, or None - Specifies whether or not alpha values are included in the table. If alpha is None, it will be automatically determined. mode Determines return type: 'byte' (0-255), 'float' (0.0-1.0), or 'qcolor'. See :func:`map() <pyqtgraph.ColorMap.map>`. =============== ============================================================================= """ if isinstance(mode, basestring): mode = self.enumMap[mode.lower()] if alpha is None: alpha = self.usesAlpha() x = np.linspace(start, stop, nPts) table = self.map(x, mode) if not alpha and mode != self.QCOLOR: return table[:,:3] else: return table def usesAlpha(self): """Return True if any stops have an alpha < 255""" max = 1.0 if self.color.dtype.kind == 'f' else 255 return np.any(self.color[:,3] != max) def isMapTrivial(self): """ Return True if the gradient has exactly two stops in it: black at 0.0 and white at 1.0. """ if len(self.pos) != 2: return False if self.pos[0] != 0.0 or self.pos[1] != 1.0: return False if self.color.dtype.kind == 'f': return np.all(self.color == np.array([[0.,0.,0.,1.], [1.,1.,1.,1.]])) else: return np.all(self.color == np.array([[0,0,0,255], [255,255,255,255]])) def __repr__(self): pos = repr(self.pos).replace('\n', '') color = repr(self.color).replace('\n', '') return "ColorMap(%s, %s)" % (pos, color)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/graphicsWindows.py
.py
2,738
86
# -*- coding: utf-8 -*- """ DEPRECATED: The classes below are convenience classes that create a new window containting a single, specific widget. These classes are now unnecessary because it is possible to place any widget into its own window by simply calling its show() method. """ from .Qt import QtCore, QtGui, mkQApp from .widgets.PlotWidget import * from .imageview import * from .widgets.GraphicsLayoutWidget import GraphicsLayoutWidget from .widgets.GraphicsView import GraphicsView class GraphicsWindow(GraphicsLayoutWidget): """ (deprecated; use :class:`~pyqtgraph.GraphicsLayoutWidget` instead) Convenience subclass of :class:`~pyqtgraph.GraphicsLayoutWidget`. This class is intended for use from the interactive python prompt. """ def __init__(self, title=None, size=(800,600), **kargs): mkQApp() GraphicsLayoutWidget.__init__(self, **kargs) self.resize(*size) if title is not None: self.setWindowTitle(title) self.show() class TabWindow(QtGui.QMainWindow): """ (deprecated) """ def __init__(self, title=None, size=(800,600)): mkQApp() QtGui.QMainWindow.__init__(self) self.resize(*size) self.cw = QtGui.QTabWidget() self.setCentralWidget(self.cw) if title is not None: self.setWindowTitle(title) self.show() def __getattr__(self, attr): return getattr(self.cw, attr) class PlotWindow(PlotWidget): """ (deprecated; use :class:`~pyqtgraph.PlotWidget` instead) """ def __init__(self, title=None, **kargs): mkQApp() self.win = QtGui.QMainWindow() PlotWidget.__init__(self, **kargs) self.win.setCentralWidget(self) for m in ['resize']: setattr(self, m, getattr(self.win, m)) if title is not None: self.win.setWindowTitle(title) self.win.show() class ImageWindow(ImageView): """ (deprecated; use :class:`~pyqtgraph.ImageView` instead) """ def __init__(self, *args, **kargs): mkQApp() self.win = QtGui.QMainWindow() self.win.resize(800,600) if 'title' in kargs: self.win.setWindowTitle(kargs['title']) del kargs['title'] ImageView.__init__(self, self.win) if len(args) > 0 or len(kargs) > 0: self.setImage(*args, **kargs) self.win.setCentralWidget(self) for m in ['resize']: setattr(self, m, getattr(self.win, m)) #for m in ['setImage', 'autoRange', 'addItem', 'removeItem', 'blackLevel', 'whiteLevel', 'imageItem']: #setattr(self, m, getattr(self.cw, m)) self.win.show()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/WidgetGroup.py
.py
10,004
286
# -*- coding: utf-8 -*- """ WidgetGroup.py - WidgetGroup class for easily managing lots of Qt widgets Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. This class addresses the problem of having to save and restore the state of a large group of widgets. """ from .Qt import QtCore, QtGui, QT_LIB import weakref, inspect from .python2_3 import asUnicode __all__ = ['WidgetGroup'] def splitterState(w): s = str(w.saveState().toPercentEncoding()) return s def restoreSplitter(w, s): if type(s) is list: w.setSizes(s) elif type(s) is str: w.restoreState(QtCore.QByteArray.fromPercentEncoding(s)) else: print("Can't configure QSplitter using object of type", type(s)) if w.count() > 0: ## make sure at least one item is not collapsed for i in w.sizes(): if i > 0: return w.setSizes([50] * w.count()) def comboState(w): ind = w.currentIndex() data = w.itemData(ind) #if not data.isValid(): if data is not None: try: if not data.isValid(): data = None else: data = data.toInt()[0] except AttributeError: pass if data is None: return asUnicode(w.itemText(ind)) else: return data def setComboState(w, v): if type(v) is int: #ind = w.findData(QtCore.QVariant(v)) ind = w.findData(v) if ind > -1: w.setCurrentIndex(ind) return w.setCurrentIndex(w.findText(str(v))) class WidgetGroup(QtCore.QObject): """This class takes a list of widgets and keeps an internal record of their state that is always up to date. Allows reading and writing from groups of widgets simultaneously. """ ## List of widget types that can be handled by WidgetGroup. ## The value for each type is a tuple (change signal function, get function, set function, [auto-add children]) ## The change signal function that takes an object and returns a signal that is emitted any time the state of the widget changes, not just ## when it is changed by user interaction. (for example, 'clicked' is not a valid signal here) ## If the change signal is None, the value of the widget is not cached. ## Custom widgets not in this list can be made to work with WidgetGroup by giving them a 'widgetGroupInterface' method ## which returns the tuple. classes = { QtGui.QSpinBox: (lambda w: w.valueChanged, QtGui.QSpinBox.value, QtGui.QSpinBox.setValue), QtGui.QDoubleSpinBox: (lambda w: w.valueChanged, QtGui.QDoubleSpinBox.value, QtGui.QDoubleSpinBox.setValue), QtGui.QSplitter: (None, splitterState, restoreSplitter, True), QtGui.QCheckBox: (lambda w: w.stateChanged, QtGui.QCheckBox.isChecked, QtGui.QCheckBox.setChecked), QtGui.QComboBox: (lambda w: w.currentIndexChanged, comboState, setComboState), QtGui.QGroupBox: (lambda w: w.toggled, QtGui.QGroupBox.isChecked, QtGui.QGroupBox.setChecked, True), QtGui.QLineEdit: (lambda w: w.editingFinished, lambda w: str(w.text()), QtGui.QLineEdit.setText), QtGui.QRadioButton: (lambda w: w.toggled, QtGui.QRadioButton.isChecked, QtGui.QRadioButton.setChecked), QtGui.QSlider: (lambda w: w.valueChanged, QtGui.QSlider.value, QtGui.QSlider.setValue), } sigChanged = QtCore.Signal(str, object) def __init__(self, widgetList=None): """Initialize WidgetGroup, adding specified widgets into this group. widgetList can be: - a list of widget specifications (widget, [name], [scale]) - a dict of name: widget pairs - any QObject, and all compatible child widgets will be added recursively. The 'scale' parameter for each widget allows QSpinBox to display a different value than the value recorded in the group state (for example, the program may set a spin box value to 100e-6 and have it displayed as 100 to the user) """ QtCore.QObject.__init__(self) self.widgetList = weakref.WeakKeyDictionary() # Make sure widgets don't stick around just because they are listed here self.scales = weakref.WeakKeyDictionary() self.cache = {} ## name:value pairs self.uncachedWidgets = weakref.WeakKeyDictionary() if isinstance(widgetList, QtCore.QObject): self.autoAdd(widgetList) elif isinstance(widgetList, list): for w in widgetList: self.addWidget(*w) elif isinstance(widgetList, dict): for name, w in widgetList.items(): self.addWidget(w, name) elif widgetList is None: return else: raise Exception("Wrong argument type %s" % type(widgetList)) def addWidget(self, w, name=None, scale=None): if not self.acceptsType(w): raise Exception("Widget type %s not supported by WidgetGroup" % type(w)) if name is None: name = str(w.objectName()) if name == '': raise Exception("Cannot add widget '%s' without a name." % str(w)) self.widgetList[w] = name self.scales[w] = scale self.readWidget(w) if type(w) in WidgetGroup.classes: signal = WidgetGroup.classes[type(w)][0] else: signal = w.widgetGroupInterface()[0] if signal is not None: if inspect.isfunction(signal) or inspect.ismethod(signal): signal = signal(w) signal.connect(self.mkChangeCallback(w)) else: self.uncachedWidgets[w] = None def findWidget(self, name): for w in self.widgetList: if self.widgetList[w] == name: return w return None def interface(self, obj): t = type(obj) if t in WidgetGroup.classes: return WidgetGroup.classes[t] else: return obj.widgetGroupInterface() def checkForChildren(self, obj): """Return true if we should automatically search the children of this object for more.""" iface = self.interface(obj) return (len(iface) > 3 and iface[3]) def autoAdd(self, obj): ## Find all children of this object and add them if possible. accepted = self.acceptsType(obj) if accepted: #print "%s auto add %s" % (self.objectName(), obj.objectName()) self.addWidget(obj) if not accepted or self.checkForChildren(obj): for c in obj.children(): self.autoAdd(c) def acceptsType(self, obj): for c in WidgetGroup.classes: if isinstance(obj, c): return True if hasattr(obj, 'widgetGroupInterface'): return True return False def setScale(self, widget, scale): val = self.readWidget(widget) self.scales[widget] = scale self.setWidget(widget, val) def mkChangeCallback(self, w): return lambda *args: self.widgetChanged(w, *args) def widgetChanged(self, w, *args): n = self.widgetList[w] v1 = self.cache[n] v2 = self.readWidget(w) if v1 != v2: if QT_LIB != 'PyQt5': # Old signal kept for backward compatibility. self.emit(QtCore.SIGNAL('changed'), self.widgetList[w], v2) self.sigChanged.emit(self.widgetList[w], v2) def state(self): for w in self.uncachedWidgets: self.readWidget(w) return self.cache.copy() def setState(self, s): for w in self.widgetList: n = self.widgetList[w] if n not in s: continue self.setWidget(w, s[n]) def readWidget(self, w): if type(w) in WidgetGroup.classes: getFunc = WidgetGroup.classes[type(w)][1] else: getFunc = w.widgetGroupInterface()[1] if getFunc is None: return None ## if the getter function provided in the interface is a bound method, ## then just call the method directly. Otherwise, pass in the widget as the first arg ## to the function. if inspect.ismethod(getFunc) and getFunc.__self__ is not None: val = getFunc() else: val = getFunc(w) if self.scales[w] is not None: val /= self.scales[w] #if isinstance(val, QtCore.QString): #val = str(val) n = self.widgetList[w] self.cache[n] = val return val def setWidget(self, w, v): v1 = v if self.scales[w] is not None: v *= self.scales[w] if type(w) in WidgetGroup.classes: setFunc = WidgetGroup.classes[type(w)][2] else: setFunc = w.widgetGroupInterface()[2] ## if the setter function provided in the interface is a bound method, ## then just call the method directly. Otherwise, pass in the widget as the first arg ## to the function. if inspect.ismethod(setFunc) and setFunc.__self__ is not None: setFunc(v) else: setFunc(w, v) #name = self.widgetList[w] #if name in self.cache and (self.cache[name] != v1): #print "%s: Cached value %s != set value %s" % (name, str(self.cache[name]), str(v1))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/PlotData.py
.py
1,572
56
class PlotData(object): """ Class used for managing plot data - allows data sharing between multiple graphics items (curve, scatter, graph..) - each item may define the columns it needs - column groupings ('pos' or x, y, z) - efficiently appendable - log, fft transformations - color mode conversion (float/byte/qcolor) - pen/brush conversion - per-field cached masking - allows multiple masking fields (different graphics need to mask on different criteria) - removal of nan/inf values - option for single value shared by entire column - cached downsampling - cached min / max / hasnan / isuniform """ def __init__(self): self.fields = {} self.maxVals = {} ## cache for max/min self.minVals = {} def addFields(self, **fields): for f in fields: if f not in self.fields: self.fields[f] = None def hasField(self, f): return f in self.fields def __getitem__(self, field): return self.fields[field] def __setitem__(self, field, val): self.fields[field] = val def max(self, field): mx = self.maxVals.get(field, None) if mx is None: mx = np.max(self[field]) self.maxVals[field] = mx return mx def min(self, field): mn = self.minVals.get(field, None) if mn is None: mn = np.min(self[field]) self.minVals[field] = mn return mn
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/functions.py
.py
96,082
2,510
# -*- coding: utf-8 -*- """ functions.py - Miscellaneous functions with no other home Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. """ from __future__ import division import warnings import numpy as np import decimal, re import ctypes import sys, struct from .pgcollections import OrderedDict from .python2_3 import asUnicode, basestring from .Qt import QtGui, QtCore, QT_LIB from . import getConfigOption, setConfigOptions from . import debug, reload from .reload import getPreviousVersion from .metaarray import MetaArray Colors = { 'b': QtGui.QColor(0,0,255,255), 'g': QtGui.QColor(0,255,0,255), 'r': QtGui.QColor(255,0,0,255), 'c': QtGui.QColor(0,255,255,255), 'm': QtGui.QColor(255,0,255,255), 'y': QtGui.QColor(255,255,0,255), 'k': QtGui.QColor(0,0,0,255), 'w': QtGui.QColor(255,255,255,255), 'd': QtGui.QColor(150,150,150,255), 'l': QtGui.QColor(200,200,200,255), 's': QtGui.QColor(100,100,150,255), } SI_PREFIXES = asUnicode('yzafpnµm kMGTPEZY') SI_PREFIXES_ASCII = 'yzafpnum kMGTPEZY' SI_PREFIX_EXPONENTS = dict([(SI_PREFIXES[i], (i-8)*3) for i in range(len(SI_PREFIXES))]) SI_PREFIX_EXPONENTS['u'] = -6 FLOAT_REGEX = re.compile(r'(?P<number>[+-]?((\d+(\.\d*)?)|(\d*\.\d+))([eE][+-]?\d+)?)\s*((?P<siPrefix>[u' + SI_PREFIXES + r']?)(?P<suffix>\w.*))?$') INT_REGEX = re.compile(r'(?P<number>[+-]?\d+)\s*(?P<siPrefix>[u' + SI_PREFIXES + r']?)(?P<suffix>.*)$') def siScale(x, minVal=1e-25, allowUnicode=True): """ Return the recommended scale factor and SI prefix string for x. Example:: siScale(0.0001) # returns (1e6, 'μ') # This indicates that the number 0.0001 is best represented as 0.0001 * 1e6 = 100 μUnits """ if isinstance(x, decimal.Decimal): x = float(x) try: if np.isnan(x) or np.isinf(x): return(1, '') except: print(x, type(x)) raise if abs(x) < minVal: m = 0 x = 0 else: m = int(np.clip(np.floor(np.log(abs(x))/np.log(1000)), -9.0, 9.0)) if m == 0: pref = '' elif m < -8 or m > 8: pref = 'e%d' % (m*3) else: if allowUnicode: pref = SI_PREFIXES[m+8] else: pref = SI_PREFIXES_ASCII[m+8] p = .001**m return (p, pref) def siFormat(x, precision=3, suffix='', space=True, error=None, minVal=1e-25, allowUnicode=True): """ Return the number x formatted in engineering notation with SI prefix. Example:: siFormat(0.0001, suffix='V') # returns "100 μV" """ if space is True: space = ' ' if space is False: space = '' (p, pref) = siScale(x, minVal, allowUnicode) if not (len(pref) > 0 and pref[0] == 'e'): pref = space + pref if error is None: fmt = "%." + str(precision) + "g%s%s" return fmt % (x*p, pref, suffix) else: if allowUnicode: plusminus = space + asUnicode("±") + space else: plusminus = " +/- " fmt = "%." + str(precision) + "g%s%s%s%s" return fmt % (x*p, pref, suffix, plusminus, siFormat(error, precision=precision, suffix=suffix, space=space, minVal=minVal)) def siParse(s, regex=FLOAT_REGEX, suffix=None): """Convert a value written in SI notation to a tuple (number, si_prefix, suffix). Example:: siParse('100 μV") # returns ('100', 'μ', 'V') """ s = asUnicode(s) s = s.strip() if suffix is not None and len(suffix) > 0: if s[-len(suffix):] != suffix: raise ValueError("String '%s' does not have the expected suffix '%s'" % (s, suffix)) s = s[:-len(suffix)] + 'X' # add a fake suffix so the regex still picks up the si prefix m = regex.match(s) if m is None: raise ValueError('Cannot parse number "%s"' % s) try: sip = m.group('siPrefix') except IndexError: sip = '' if suffix is None: try: suf = m.group('suffix') except IndexError: suf = '' else: suf = suffix return m.group('number'), '' if sip is None else sip, '' if suf is None else suf def siEval(s, typ=float, regex=FLOAT_REGEX, suffix=None): """ Convert a value written in SI notation to its equivalent prefixless value. Example:: siEval("100 μV") # returns 0.0001 """ val, siprefix, suffix = siParse(s, regex, suffix=suffix) v = typ(val) return siApply(v, siprefix) def siApply(val, siprefix): """ """ n = SI_PREFIX_EXPONENTS[siprefix] if siprefix != '' else 0 if n > 0: return val * 10**n elif n < 0: # this case makes it possible to use Decimal objects here return val / 10**-n else: return val class Color(QtGui.QColor): def __init__(self, *args): QtGui.QColor.__init__(self, mkColor(*args)) def glColor(self): """Return (r,g,b,a) normalized for use in opengl""" return (self.red()/255., self.green()/255., self.blue()/255., self.alpha()/255.) def __getitem__(self, ind): return (self.red, self.green, self.blue, self.alpha)[ind]() def mkColor(*args): """ Convenience function for constructing QColor from a variety of argument types. Accepted arguments are: ================ ================================================ 'c' one of: r, g, b, c, m, y, k, w R, G, B, [A] integers 0-255 (R, G, B, [A]) tuple of integers 0-255 float greyscale, 0.0-1.0 int see :func:`intColor() <pyqtgraph.intColor>` (int, hues) see :func:`intColor() <pyqtgraph.intColor>` "RGB" hexadecimal strings; may begin with '#' "RGBA" "RRGGBB" "RRGGBBAA" QColor QColor instance; makes a copy. ================ ================================================ """ err = 'Not sure how to make a color from "%s"' % str(args) if len(args) == 1: if isinstance(args[0], basestring): c = args[0] if c[0] == '#': c = c[1:] if len(c) == 1: try: return Colors[c] except KeyError: raise ValueError('No color named "%s"' % c) if len(c) == 3: r = int(c[0]*2, 16) g = int(c[1]*2, 16) b = int(c[2]*2, 16) a = 255 elif len(c) == 4: r = int(c[0]*2, 16) g = int(c[1]*2, 16) b = int(c[2]*2, 16) a = int(c[3]*2, 16) elif len(c) == 6: r = int(c[0:2], 16) g = int(c[2:4], 16) b = int(c[4:6], 16) a = 255 elif len(c) == 8: r = int(c[0:2], 16) g = int(c[2:4], 16) b = int(c[4:6], 16) a = int(c[6:8], 16) elif isinstance(args[0], QtGui.QColor): return QtGui.QColor(args[0]) elif isinstance(args[0], float): r = g = b = int(args[0] * 255) a = 255 elif hasattr(args[0], '__len__'): if len(args[0]) == 3: (r, g, b) = args[0] a = 255 elif len(args[0]) == 4: (r, g, b, a) = args[0] elif len(args[0]) == 2: return intColor(*args[0]) else: raise TypeError(err) elif type(args[0]) == int: return intColor(args[0]) else: raise TypeError(err) elif len(args) == 3: (r, g, b) = args a = 255 elif len(args) == 4: (r, g, b, a) = args else: raise TypeError(err) args = [r,g,b,a] args = [0 if np.isnan(a) or np.isinf(a) else a for a in args] args = list(map(int, args)) return QtGui.QColor(*args) def mkBrush(*args, **kwds): """ | Convenience function for constructing Brush. | This function always constructs a solid brush and accepts the same arguments as :func:`mkColor() <pyqtgraph.mkColor>` | Calling mkBrush(None) returns an invisible brush. """ if 'color' in kwds: color = kwds['color'] elif len(args) == 1: arg = args[0] if arg is None: return QtGui.QBrush(QtCore.Qt.NoBrush) elif isinstance(arg, QtGui.QBrush): return QtGui.QBrush(arg) else: color = arg elif len(args) > 1: color = args return QtGui.QBrush(mkColor(color)) def mkPen(*args, **kargs): """ Convenience function for constructing QPen. Examples:: mkPen(color) mkPen(color, width=2) mkPen(cosmetic=False, width=4.5, color='r') mkPen({'color': "FF0", width: 2}) mkPen(None) # (no pen) In these examples, *color* may be replaced with any arguments accepted by :func:`mkColor() <pyqtgraph.mkColor>` """ color = kargs.get('color', None) width = kargs.get('width', 1) style = kargs.get('style', None) dash = kargs.get('dash', None) cosmetic = kargs.get('cosmetic', True) hsv = kargs.get('hsv', None) if len(args) == 1: arg = args[0] if isinstance(arg, dict): return mkPen(**arg) if isinstance(arg, QtGui.QPen): return QtGui.QPen(arg) ## return a copy of this pen elif arg is None: style = QtCore.Qt.NoPen else: color = arg if len(args) > 1: color = args if color is None: color = mkColor('l') if hsv is not None: color = hsvColor(*hsv) else: color = mkColor(color) pen = QtGui.QPen(QtGui.QBrush(color), width) pen.setCosmetic(cosmetic) if style is not None: pen.setStyle(style) if dash is not None: pen.setDashPattern(dash) return pen def hsvColor(hue, sat=1.0, val=1.0, alpha=1.0): """Generate a QColor from HSVa values. (all arguments are float 0.0-1.0)""" c = QtGui.QColor() c.setHsvF(hue, sat, val, alpha) return c def colorTuple(c): """Return a tuple (R,G,B,A) from a QColor""" return (c.red(), c.green(), c.blue(), c.alpha()) def colorStr(c): """Generate a hex string code from a QColor""" return ('%02x'*4) % colorTuple(c) def intColor(index, hues=9, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255): """ Creates a QColor from a single index. Useful for stepping through a predefined list of colors. The argument *index* determines which color from the set will be returned. All other arguments determine what the set of predefined colors will be Colors are chosen by cycling across hues while varying the value (brightness). By default, this selects from a list of 9 hues.""" hues = int(hues) values = int(values) ind = int(index) % (hues * values) indh = ind % hues indv = ind // hues if values > 1: v = minValue + indv * ((maxValue-minValue) / (values-1)) else: v = maxValue h = minHue + (indh * (maxHue-minHue)) / hues c = QtGui.QColor() c.setHsv(h, sat, v) c.setAlpha(alpha) return c def glColor(*args, **kargs): """ Convert a color to OpenGL color format (r,g,b,a) floats 0.0-1.0 Accepts same arguments as :func:`mkColor <pyqtgraph.mkColor>`. """ c = mkColor(*args, **kargs) return (c.red()/255., c.green()/255., c.blue()/255., c.alpha()/255.) def makeArrowPath(headLen=20, tipAngle=20, tailLen=20, tailWidth=3, baseAngle=0): """ Construct a path outlining an arrow with the given dimensions. The arrow points in the -x direction with tip positioned at 0,0. If *tipAngle* is supplied (in degrees), it overrides *headWidth*. If *tailLen* is None, no tail will be drawn. """ headWidth = headLen * np.tan(tipAngle * 0.5 * np.pi/180.) path = QtGui.QPainterPath() path.moveTo(0,0) path.lineTo(headLen, -headWidth) if tailLen is None: innerY = headLen - headWidth * np.tan(baseAngle*np.pi/180.) path.lineTo(innerY, 0) else: tailWidth *= 0.5 innerY = headLen - (headWidth-tailWidth) * np.tan(baseAngle*np.pi/180.) path.lineTo(innerY, -tailWidth) path.lineTo(headLen + tailLen, -tailWidth) path.lineTo(headLen + tailLen, tailWidth) path.lineTo(innerY, tailWidth) path.lineTo(headLen, headWidth) path.lineTo(0,0) return path def eq(a, b): """The great missing equivalence function: Guaranteed evaluation to a single bool value. This function has some important differences from the == operator: 1. Returns True if a IS b, even if a==b still evaluates to False, such as with nan values. 2. Tests for equivalence using ==, but silently ignores some common exceptions that can occur (AtrtibuteError, ValueError). 3. When comparing arrays, returns False if the array shapes are not the same. 4. When comparing arrays of the same shape, returns True only if all elements are equal (whereas the == operator would return a boolean array). 5. Collections (dict, list, etc.) must have the same type to be considered equal. One consequence is that comparing a dict to an OrderedDict will always return False. """ if a is b: return True # Avoid comparing large arrays against scalars; this is expensive and we know it should return False. aIsArr = isinstance(a, (np.ndarray, MetaArray)) bIsArr = isinstance(b, (np.ndarray, MetaArray)) if (aIsArr or bIsArr) and type(a) != type(b): return False # If both inputs are arrays, we can speeed up comparison if shapes / dtypes don't match # NOTE: arrays of dissimilar type should be considered unequal even if they are numerically # equal because they may behave differently when computed on. if aIsArr and bIsArr and (a.shape != b.shape or a.dtype != b.dtype): return False # Recursively handle common containers if isinstance(a, dict) and isinstance(b, dict): if type(a) != type(b) or len(a) != len(b): return False if set(a.keys()) != set(b.keys()): return False for k, v in a.items(): if not eq(v, b[k]): return False if isinstance(a, OrderedDict) or sys.version_info >= (3, 7): for a_item, b_item in zip(a.items(), b.items()): if not eq(a_item, b_item): return False return True if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)): if type(a) != type(b) or len(a) != len(b): return False for v1,v2 in zip(a, b): if not eq(v1, v2): return False return True # Test for equivalence. # If the test raises a recognized exception, then return Falase try: try: # Sometimes running catch_warnings(module=np) generates AttributeError ??? catcher = warnings.catch_warnings(module=np) # ignore numpy futurewarning (numpy v. 1.10) catcher.__enter__() except Exception: catcher = None e = a==b except (ValueError, AttributeError): return False except: print('failed to evaluate equivalence for:') print(" a:", str(type(a)), str(a)) print(" b:", str(type(b)), str(b)) raise finally: if catcher is not None: catcher.__exit__(None, None, None) t = type(e) if t is bool: return e elif t is np.bool_: return bool(e) elif isinstance(e, np.ndarray) or (hasattr(e, 'implements') and e.implements('MetaArray')): try: ## disaster: if a is an empty array and b is not, then e.all() is True if a.shape != b.shape: return False except: return False if (hasattr(e, 'implements') and e.implements('MetaArray')): return e.asarray().all() else: return e.all() else: raise Exception("== operator returned type %s" % str(type(e))) def affineSliceCoords(shape, origin, vectors, axes): """Return the array of coordinates used to sample data arrays in affineSlice(). """ # sanity check if len(shape) != len(vectors): raise Exception("shape and vectors must have same length.") if len(origin) != len(axes): raise Exception("origin and axes must have same length.") for v in vectors: if len(v) != len(axes): raise Exception("each vector must be same length as axes.") shape = list(map(np.ceil, shape)) ## make sure vectors are arrays if not isinstance(vectors, np.ndarray): vectors = np.array(vectors) if not isinstance(origin, np.ndarray): origin = np.array(origin) origin.shape = (len(axes),) + (1,)*len(shape) ## Build array of sample locations. grid = np.mgrid[tuple([slice(0,x) for x in shape])] ## mesh grid of indexes x = (grid[np.newaxis,...] * vectors.transpose()[(Ellipsis,) + (np.newaxis,)*len(shape)]).sum(axis=1) ## magic x += origin return x def affineSlice(data, shape, origin, vectors, axes, order=1, returnCoords=False, **kargs): """ Take a slice of any orientation through an array. This is useful for extracting sections of multi-dimensional arrays such as MRI images for viewing as 1D or 2D data. The slicing axes are aribtrary; they do not need to be orthogonal to the original data or even to each other. It is possible to use this function to extract arbitrary linear, rectangular, or parallelepiped shapes from within larger datasets. The original data is interpolated onto a new array of coordinates using either interpolateArray if order<2 or scipy.ndimage.map_coordinates otherwise. For a graphical interface to this function, see :func:`ROI.getArrayRegion <pyqtgraph.ROI.getArrayRegion>` ============== ==================================================================================================== **Arguments:** *data* (ndarray) the original dataset *shape* the shape of the slice to take (Note the return value may have more dimensions than len(shape)) *origin* the location in the original dataset that will become the origin of the sliced data. *vectors* list of unit vectors which point in the direction of the slice axes. Each vector must have the same length as *axes*. If the vectors are not unit length, the result will be scaled relative to the original data. If the vectors are not orthogonal, the result will be sheared relative to the original data. *axes* The axes in the original dataset which correspond to the slice *vectors* *order* The order of spline interpolation. Default is 1 (linear). See scipy.ndimage.map_coordinates for more information. *returnCoords* If True, return a tuple (result, coords) where coords is the array of coordinates used to select values from the original dataset. *All extra keyword arguments are passed to scipy.ndimage.map_coordinates.* -------------------------------------------------------------------------------------------------------------------- ============== ==================================================================================================== Note the following must be true: | len(shape) == len(vectors) | len(origin) == len(axes) == len(vectors[i]) Example: start with a 4D fMRI data set, take a diagonal-planar slice out of the last 3 axes * data = array with dims (time, x, y, z) = (100, 40, 40, 40) * The plane to pull out is perpendicular to the vector (x,y,z) = (1,1,1) * The origin of the slice will be at (x,y,z) = (40, 0, 0) * We will slice a 20x20 plane from each timepoint, giving a final shape (100, 20, 20) The call for this example would look like:: affineSlice(data, shape=(20,20), origin=(40,0,0), vectors=((-1, 1, 0), (-1, 0, 1)), axes=(1,2,3)) """ x = affineSliceCoords(shape, origin, vectors, axes) ## transpose data so slice axes come first trAx = list(range(data.ndim)) for ax in axes: trAx.remove(ax) tr1 = tuple(axes) + tuple(trAx) data = data.transpose(tr1) #print "tr1:", tr1 ## dims are now [(slice axes), (other axes)] if order > 1: try: import scipy.ndimage except ImportError: raise ImportError("Interpolating with order > 1 requires the scipy.ndimage module, but it could not be imported.") # iterate manually over unused axes since map_coordinates won't do it for us extraShape = data.shape[len(axes):] output = np.empty(tuple(shape) + extraShape, dtype=data.dtype) for inds in np.ndindex(*extraShape): ind = (Ellipsis,) + inds output[ind] = scipy.ndimage.map_coordinates(data[ind], x, order=order, **kargs) else: # map_coordinates expects the indexes as the first axis, whereas # interpolateArray expects indexes at the last axis. tr = tuple(range(1, x.ndim)) + (0,) output = interpolateArray(data, x.transpose(tr), order=order) tr = list(range(output.ndim)) trb = [] for i in range(min(axes)): ind = tr1.index(i) + (len(shape)-len(axes)) tr.remove(ind) trb.append(ind) tr2 = tuple(trb+tr) ## Untranspose array before returning output = output.transpose(tr2) if returnCoords: return (output, x) else: return output def interpolateArray(data, x, default=0.0, order=1): """ N-dimensional interpolation similar to scipy.ndimage.map_coordinates. This function returns linearly-interpolated values sampled from a regular grid of data. It differs from `ndimage.map_coordinates` by allowing broadcasting within the input array. ============== =========================================================================================== **Arguments:** *data* Array of any shape containing the values to be interpolated. *x* Array with (shape[-1] <= data.ndim) containing the locations within *data* to interpolate. (note: the axes for this argument are transposed relative to the same argument for `ndimage.map_coordinates`). *default* Value to return for locations in *x* that are outside the bounds of *data*. *order* Order of interpolation: 0=nearest, 1=linear. ============== =========================================================================================== Returns array of shape (x.shape[:-1] + data.shape[x.shape[-1]:]) For example, assume we have the following 2D image data:: >>> data = np.array([[1, 2, 4 ], [10, 20, 40 ], [100, 200, 400]]) To compute a single interpolated point from this data:: >>> x = np.array([(0.5, 0.5)]) >>> interpolateArray(data, x) array([ 8.25]) To compute a 1D list of interpolated locations:: >>> x = np.array([(0.5, 0.5), (1.0, 1.0), (1.0, 2.0), (1.5, 0.0)]) >>> interpolateArray(data, x) array([ 8.25, 20. , 40. , 55. ]) To compute a 2D array of interpolated locations:: >>> x = np.array([[(0.5, 0.5), (1.0, 2.0)], [(1.0, 1.0), (1.5, 0.0)]]) >>> interpolateArray(data, x) array([[ 8.25, 40. ], [ 20. , 55. ]]) ..and so on. The *x* argument may have any shape as long as ```x.shape[-1] <= data.ndim```. In the case that ```x.shape[-1] < data.ndim```, then the remaining axes are simply broadcasted as usual. For example, we can interpolate one location from an entire row of the data:: >>> x = np.array([[0.5]]) >>> interpolateArray(data, x) array([[ 5.5, 11. , 22. ]]) This is useful for interpolating from arrays of colors, vertexes, etc. """ if order not in (0, 1): raise ValueError("interpolateArray requires order=0 or 1 (got %s)" % order) prof = debug.Profiler() nd = data.ndim md = x.shape[-1] if md > nd: raise TypeError("x.shape[-1] must be less than or equal to data.ndim") totalMask = np.ones(x.shape[:-1], dtype=bool) # keep track of out-of-bound indexes if order == 0: xinds = np.round(x).astype(int) # NOTE: for 0.5 this rounds to the nearest *even* number for ax in range(md): mask = (xinds[...,ax] >= 0) & (xinds[...,ax] <= data.shape[ax]-1) xinds[...,ax][~mask] = 0 # keep track of points that need to be set to default totalMask &= mask result = data[tuple([xinds[...,i] for i in range(xinds.shape[-1])])] elif order == 1: # First we generate arrays of indexes that are needed to # extract the data surrounding each point fields = np.mgrid[(slice(0,order+1),) * md] xmin = np.floor(x).astype(int) xmax = xmin + 1 indexes = np.concatenate([xmin[np.newaxis, ...], xmax[np.newaxis, ...]]) fieldInds = [] for ax in range(md): mask = (xmin[...,ax] >= 0) & (x[...,ax] <= data.shape[ax]-1) # keep track of points that need to be set to default totalMask &= mask # ..and keep track of indexes that are out of bounds # (note that when x[...,ax] == data.shape[ax], then xmax[...,ax] will be out # of bounds, but the interpolation will work anyway) mask &= (xmax[...,ax] < data.shape[ax]) axisIndex = indexes[...,ax][fields[ax]] axisIndex[axisIndex < 0] = 0 axisIndex[axisIndex >= data.shape[ax]] = 0 fieldInds.append(axisIndex) prof() # Get data values surrounding each requested point fieldData = data[tuple(fieldInds)] prof() ## Interpolate s = np.empty((md,) + fieldData.shape, dtype=float) dx = x - xmin # reshape fields for arithmetic against dx for ax in range(md): f1 = fields[ax].reshape(fields[ax].shape + (1,)*(dx.ndim-1)) sax = f1 * dx[...,ax] + (1-f1) * (1-dx[...,ax]) sax = sax.reshape(sax.shape + (1,) * (s.ndim-1-sax.ndim)) s[ax] = sax s = np.product(s, axis=0) result = fieldData * s for i in range(md): result = result.sum(axis=0) prof() if totalMask.ndim > 0: result[~totalMask] = default else: if totalMask is False: result[:] = default prof() return result def subArray(data, offset, shape, stride): """ Unpack a sub-array from *data* using the specified offset, shape, and stride. Note that *stride* is specified in array elements, not bytes. For example, we have a 2x3 array packed in a 1D array as follows:: data = [_, _, 00, 01, 02, _, 10, 11, 12, _] Then we can unpack the sub-array with this call:: subArray(data, offset=2, shape=(2, 3), stride=(4, 1)) ..which returns:: [[00, 01, 02], [10, 11, 12]] This function operates only on the first axis of *data*. So changing the input in the example above to have shape (10, 7) would cause the output to have shape (2, 3, 7). """ data = np.ascontiguousarray(data)[offset:] shape = tuple(shape) extraShape = data.shape[1:] strides = list(data.strides[::-1]) itemsize = strides[-1] for s in stride[1::-1]: strides.append(itemsize * s) strides = tuple(strides[::-1]) return np.ndarray(buffer=data, shape=shape+extraShape, strides=strides, dtype=data.dtype) def transformToArray(tr): """ Given a QTransform, return a 3x3 numpy array. Given a QMatrix4x4, return a 4x4 numpy array. Example: map an array of x,y coordinates through a transform:: ## coordinates to map are (1,5), (2,6), (3,7), and (4,8) coords = np.array([[1,2,3,4], [5,6,7,8], [1,1,1,1]]) # the extra '1' coordinate is needed for translation to work ## Make an example transform tr = QtGui.QTransform() tr.translate(3,4) tr.scale(2, 0.1) ## convert to array m = pg.transformToArray()[:2] # ignore the perspective portion of the transformation ## map coordinates through transform mapped = np.dot(m, coords) """ #return np.array([[tr.m11(), tr.m12(), tr.m13()],[tr.m21(), tr.m22(), tr.m23()],[tr.m31(), tr.m32(), tr.m33()]]) ## The order of elements given by the method names m11..m33 is misleading-- ## It is most common for x,y translation to occupy the positions 1,3 and 2,3 in ## a transformation matrix. However, with QTransform these values appear at m31 and m32. ## So the correct interpretation is transposed: if isinstance(tr, QtGui.QTransform): return np.array([[tr.m11(), tr.m21(), tr.m31()], [tr.m12(), tr.m22(), tr.m32()], [tr.m13(), tr.m23(), tr.m33()]]) elif isinstance(tr, QtGui.QMatrix4x4): return np.array(tr.copyDataTo()).reshape(4,4) else: raise Exception("Transform argument must be either QTransform or QMatrix4x4.") def transformCoordinates(tr, coords, transpose=False): """ Map a set of 2D or 3D coordinates through a QTransform or QMatrix4x4. The shape of coords must be (2,...) or (3,...) The mapping will _ignore_ any perspective transformations. For coordinate arrays with ndim=2, this is basically equivalent to matrix multiplication. Most arrays, however, prefer to put the coordinate axis at the end (eg. shape=(...,3)). To allow this, use transpose=True. """ if transpose: ## move last axis to beginning. This transposition will be reversed before returning the mapped coordinates. coords = coords.transpose((coords.ndim-1,) + tuple(range(0,coords.ndim-1))) nd = coords.shape[0] if isinstance(tr, np.ndarray): m = tr else: m = transformToArray(tr) m = m[:m.shape[0]-1] # remove perspective ## If coords are 3D and tr is 2D, assume no change for Z axis if m.shape == (2,3) and nd == 3: m2 = np.zeros((3,4)) m2[:2, :2] = m[:2,:2] m2[:2, 3] = m[:2,2] m2[2,2] = 1 m = m2 ## if coords are 2D and tr is 3D, ignore Z axis if m.shape == (3,4) and nd == 2: m2 = np.empty((2,3)) m2[:,:2] = m[:2,:2] m2[:,2] = m[:2,3] m = m2 ## reshape tr and coords to prepare for multiplication m = m.reshape(m.shape + (1,)*(coords.ndim-1)) coords = coords[np.newaxis, ...] # separate scale/rotate and translation translate = m[:,-1] m = m[:, :-1] ## map coordinates and return mapped = (m*coords).sum(axis=1) ## apply scale/rotate mapped += translate if transpose: ## move first axis to end. mapped = mapped.transpose(tuple(range(1,mapped.ndim)) + (0,)) return mapped def solve3DTransform(points1, points2): """ Find a 3D transformation matrix that maps points1 onto points2. Points must be specified as either lists of 4 Vectors or (4, 3) arrays. """ import numpy.linalg pts = [] for inp in (points1, points2): if isinstance(inp, np.ndarray): A = np.empty((4,4), dtype=float) A[:,:3] = inp[:,:3] A[:,3] = 1.0 else: A = np.array([[inp[i].x(), inp[i].y(), inp[i].z(), 1] for i in range(4)]) pts.append(A) ## solve 3 sets of linear equations to determine transformation matrix elements matrix = np.zeros((4,4)) for i in range(3): ## solve Ax = B; x is one row of the desired transformation matrix matrix[i] = numpy.linalg.solve(pts[0], pts[1][:,i]) return matrix def solveBilinearTransform(points1, points2): """ Find a bilinear transformation matrix (2x4) that maps points1 onto points2. Points must be specified as a list of 4 Vector, Point, QPointF, etc. To use this matrix to map a point [x,y]:: mapped = np.dot(matrix, [x*y, x, y, 1]) """ import numpy.linalg ## A is 4 rows (points) x 4 columns (xy, x, y, 1) ## B is 4 rows (points) x 2 columns (x, y) A = np.array([[points1[i].x()*points1[i].y(), points1[i].x(), points1[i].y(), 1] for i in range(4)]) B = np.array([[points2[i].x(), points2[i].y()] for i in range(4)]) ## solve 2 sets of linear equations to determine transformation matrix elements matrix = np.zeros((2,4)) for i in range(2): matrix[i] = numpy.linalg.solve(A, B[:,i]) ## solve Ax = B; x is one row of the desired transformation matrix return matrix def rescaleData(data, scale, offset, dtype=None, clip=None): """Return data rescaled and optionally cast to a new dtype. The scaling operation is:: data => (data-offset) * scale """ if dtype is None: dtype = data.dtype else: dtype = np.dtype(dtype) try: if not getConfigOption('useWeave'): raise Exception('Weave is disabled; falling back to slower version.') try: import scipy.weave except ImportError: raise Exception('scipy.weave is not importable; falling back to slower version.') ## require native dtype when using weave if not data.dtype.isnative: data = data.astype(data.dtype.newbyteorder('=')) if not dtype.isnative: weaveDtype = dtype.newbyteorder('=') else: weaveDtype = dtype newData = np.empty((data.size,), dtype=weaveDtype) flat = np.ascontiguousarray(data).reshape(data.size) size = data.size code = """ double sc = (double)scale; double off = (double)offset; for( int i=0; i<size; i++ ) { newData[i] = ((double)flat[i] - off) * sc; } """ scipy.weave.inline(code, ['flat', 'newData', 'size', 'offset', 'scale'], compiler='gcc') if dtype != weaveDtype: newData = newData.astype(dtype) data = newData.reshape(data.shape) except: if getConfigOption('useWeave'): if getConfigOption('weaveDebug'): debug.printExc("Error; disabling weave.") setConfigOptions(useWeave=False) #p = np.poly1d([scale, -offset*scale]) #d2 = p(data) d2 = data - float(offset) d2 *= scale # Clip before converting dtype to avoid overflow if dtype.kind in 'ui': lim = np.iinfo(dtype) if clip is None: # don't let rescale cause integer overflow d2 = np.clip(d2, lim.min, lim.max) else: d2 = np.clip(d2, max(clip[0], lim.min), min(clip[1], lim.max)) else: if clip is not None: d2 = np.clip(d2, *clip) data = d2.astype(dtype) return data def applyLookupTable(data, lut): """ Uses values in *data* as indexes to select values from *lut*. The returned data has shape data.shape + lut.shape[1:] Note: color gradient lookup tables can be generated using GradientWidget. """ if data.dtype.kind not in ('i', 'u'): data = data.astype(int) return np.take(lut, data, axis=0, mode='clip') def makeRGBA(*args, **kwds): """Equivalent to makeARGB(..., useRGBA=True)""" kwds['useRGBA'] = True return makeARGB(*args, **kwds) def makeARGB(data, lut=None, levels=None, scale=None, useRGBA=False): """ Convert an array of values into an ARGB array suitable for building QImages, OpenGL textures, etc. Returns the ARGB array (unsigned byte) and a boolean indicating whether there is alpha channel data. This is a two stage process: 1) Rescale the data based on the values in the *levels* argument (min, max). 2) Determine the final output by passing the rescaled values through a lookup table. Both stages are optional. ============== ================================================================================== **Arguments:** data numpy array of int/float types. If levels List [min, max]; optionally rescale data before converting through the lookup table. The data is rescaled such that min->0 and max->*scale*:: rescaled = (clip(data, min, max) - min) * (*scale* / (max - min)) It is also possible to use a 2D (N,2) array of values for levels. In this case, it is assumed that each pair of min,max values in the levels array should be applied to a different subset of the input data (for example, the input data may already have RGB values and the levels are used to independently scale each channel). The use of this feature requires that levels.shape[0] == data.shape[-1]. scale The maximum value to which data will be rescaled before being passed through the lookup table (or returned if there is no lookup table). By default this will be set to the length of the lookup table, or 255 if no lookup table is provided. lut Optional lookup table (array with dtype=ubyte). Values in data will be converted to color by indexing directly from lut. The output data shape will be input.shape + lut.shape[1:]. Lookup tables can be built using ColorMap or GradientWidget. useRGBA If True, the data is returned in RGBA order (useful for building OpenGL textures). The default is False, which returns in ARGB order for use with QImage (Note that 'ARGB' is a term used by the Qt documentation; the *actual* order is BGRA). ============== ================================================================================== """ profile = debug.Profiler() if data.ndim not in (2, 3): raise TypeError("data must be 2D or 3D") if data.ndim == 3 and data.shape[2] > 4: raise TypeError("data.shape[2] must be <= 4") if lut is not None and not isinstance(lut, np.ndarray): lut = np.array(lut) if levels is None: # automatically decide levels based on data dtype if data.dtype.kind == 'u': levels = np.array([0, 2**(data.itemsize*8)-1]) elif data.dtype.kind == 'i': s = 2**(data.itemsize*8 - 1) levels = np.array([-s, s-1]) elif data.dtype.kind == 'b': levels = np.array([0,1]) else: raise Exception('levels argument is required for float input types') if not isinstance(levels, np.ndarray): levels = np.array(levels) levels = levels.astype(np.float) if levels.ndim == 1: if levels.shape[0] != 2: raise Exception('levels argument must have length 2') elif levels.ndim == 2: if lut is not None and lut.ndim > 1: raise Exception('Cannot make ARGB data when both levels and lut have ndim > 2') if levels.shape != (data.shape[-1], 2): raise Exception('levels must have shape (data.shape[-1], 2)') else: raise Exception("levels argument must be 1D or 2D (got shape=%s)." % repr(levels.shape)) profile() # Decide on maximum scaled value if scale is None: if lut is not None: scale = lut.shape[0] else: scale = 255. # Decide on the dtype we want after scaling if lut is None: dtype = np.ubyte else: dtype = np.min_scalar_type(lut.shape[0]-1) # awkward, but fastest numpy native nan evaluation # nanMask = None if data.dtype.kind == 'f' and np.isnan(data.min()): nanMask = np.isnan(data) if data.ndim > 2: nanMask = np.any(nanMask, axis=-1) # Apply levels if given if levels is not None: if isinstance(levels, np.ndarray) and levels.ndim == 2: # we are going to rescale each channel independently if levels.shape[0] != data.shape[-1]: raise Exception("When rescaling multi-channel data, there must be the same number of levels as channels (data.shape[-1] == levels.shape[0])") newData = np.empty(data.shape, dtype=int) for i in range(data.shape[-1]): minVal, maxVal = levels[i] if minVal == maxVal: maxVal = np.nextafter(maxVal, 2*maxVal) rng = maxVal-minVal rng = 1 if rng == 0 else rng newData[...,i] = rescaleData(data[...,i], scale / rng, minVal, dtype=dtype) data = newData else: # Apply level scaling unless it would have no effect on the data minVal, maxVal = levels if minVal != 0 or maxVal != scale: if minVal == maxVal: maxVal = np.nextafter(maxVal, 2*maxVal) rng = maxVal-minVal rng = 1 if rng == 0 else rng data = rescaleData(data, scale/rng, minVal, dtype=dtype) profile() # apply LUT if given if lut is not None: data = applyLookupTable(data, lut) else: if data.dtype is not np.ubyte: data = np.clip(data, 0, 255).astype(np.ubyte) profile() # this will be the final image array imgData = np.empty(data.shape[:2]+(4,), dtype=np.ubyte) profile() # decide channel order if useRGBA: order = [0,1,2,3] # array comes out RGBA else: order = [2,1,0,3] # for some reason, the colors line up as BGR in the final image. # copy data into image array if data.ndim == 2: # This is tempting: # imgData[..., :3] = data[..., np.newaxis] # ..but it turns out this is faster: for i in range(3): imgData[..., i] = data elif data.shape[2] == 1: for i in range(3): imgData[..., i] = data[..., 0] else: for i in range(0, data.shape[2]): imgData[..., i] = data[..., order[i]] profile() # add opaque alpha channel if needed if data.ndim == 2 or data.shape[2] == 3: alpha = False imgData[..., 3] = 255 else: alpha = True # apply nan mask through alpha channel if nanMask is not None: alpha = True imgData[nanMask, 3] = 0 profile() return imgData, alpha def makeQImage(imgData, alpha=None, copy=True, transpose=True): """ Turn an ARGB array into QImage. By default, the data is copied; changes to the array will not be reflected in the image. The image will be given a 'data' attribute pointing to the array which shares its data to prevent python freeing that memory while the image is in use. ============== =================================================================== **Arguments:** imgData Array of data to convert. Must have shape (width, height, 3 or 4) and dtype=ubyte. The order of values in the 3rd axis must be (b, g, r, a). alpha If True, the QImage returned will have format ARGB32. If False, the format will be RGB32. By default, _alpha_ is True if array.shape[2] == 4. copy If True, the data is copied before converting to QImage. If False, the new QImage points directly to the data in the array. Note that the array must be contiguous for this to work (see numpy.ascontiguousarray). transpose If True (the default), the array x/y axes are transposed before creating the image. Note that Qt expects the axes to be in (height, width) order whereas pyqtgraph usually prefers the opposite. ============== =================================================================== """ ## create QImage from buffer profile = debug.Profiler() ## If we didn't explicitly specify alpha, check the array shape. if alpha is None: alpha = (imgData.shape[2] == 4) copied = False if imgData.shape[2] == 3: ## need to make alpha channel (even if alpha==False; QImage requires 32 bpp) if copy is True: d2 = np.empty(imgData.shape[:2] + (4,), dtype=imgData.dtype) d2[:,:,:3] = imgData d2[:,:,3] = 255 imgData = d2 copied = True else: raise Exception('Array has only 3 channels; cannot make QImage without copying.') if alpha: imgFormat = QtGui.QImage.Format_ARGB32 else: imgFormat = QtGui.QImage.Format_RGB32 if transpose: imgData = imgData.transpose((1, 0, 2)) ## QImage expects the row/column order to be opposite profile() if not imgData.flags['C_CONTIGUOUS']: if copy is False: extra = ' (try setting transpose=False)' if transpose else '' raise Exception('Array is not contiguous; cannot make QImage without copying.'+extra) imgData = np.ascontiguousarray(imgData) copied = True if copy is True and copied is False: imgData = imgData.copy() if QT_LIB in ['PySide', 'PySide2']: ch = ctypes.c_char.from_buffer(imgData, 0) # Bug in PySide + Python 3 causes refcount for image data to be improperly # incremented, which leads to leaked memory. As a workaround, we manually # reset the reference count after creating the QImage. # See: https://bugreports.qt.io/browse/PYSIDE-140 # Get initial reference count (PyObject struct has ob_refcnt as first element) rcount = ctypes.c_long.from_address(id(ch)).value img = QtGui.QImage(ch, imgData.shape[1], imgData.shape[0], imgFormat) if sys.version[0] == '3': # Reset refcount only on python 3. Technically this would have no effect # on python 2, but this is a nasty hack, and checking for version here # helps to mitigate possible unforseen consequences. ctypes.c_long.from_address(id(ch)).value = rcount else: #addr = ctypes.addressof(ctypes.c_char.from_buffer(imgData, 0)) ## PyQt API for QImage changed between 4.9.3 and 4.9.6 (I don't know exactly which version it was) ## So we first attempt the 4.9.6 API, then fall back to 4.9.3 #addr = ctypes.c_char.from_buffer(imgData, 0) #try: #img = QtGui.QImage(addr, imgData.shape[1], imgData.shape[0], imgFormat) #except TypeError: #addr = ctypes.addressof(addr) #img = QtGui.QImage(addr, imgData.shape[1], imgData.shape[0], imgFormat) try: img = QtGui.QImage(imgData.ctypes.data, imgData.shape[1], imgData.shape[0], imgFormat) except: if copy: # does not leak memory, is not mutable img = QtGui.QImage(buffer(imgData), imgData.shape[1], imgData.shape[0], imgFormat) else: # mutable, but leaks memory img = QtGui.QImage(memoryview(imgData), imgData.shape[1], imgData.shape[0], imgFormat) img.data = imgData return img #try: #buf = imgData.data #except AttributeError: ## happens when image data is non-contiguous #buf = imgData.data #profiler() #qimage = QtGui.QImage(buf, imgData.shape[1], imgData.shape[0], imgFormat) #profiler() #qimage.data = imgData #return qimage def imageToArray(img, copy=False, transpose=True): """ Convert a QImage into numpy array. The image must have format RGB32, ARGB32, or ARGB32_Premultiplied. By default, the image is not copied; changes made to the array will appear in the QImage as well (beware: if the QImage is collected before the array, there may be trouble). The array will have shape (width, height, (b,g,r,a)). """ fmt = img.format() ptr = img.bits() if QT_LIB in ['PySide', 'PySide2']: arr = np.frombuffer(ptr, dtype=np.ubyte) else: ptr.setsize(img.byteCount()) arr = np.asarray(ptr) if img.byteCount() != arr.size * arr.itemsize: # Required for Python 2.6, PyQt 4.10 # If this works on all platforms, then there is no need to use np.asarray.. arr = np.frombuffer(ptr, np.ubyte, img.byteCount()) arr = arr.reshape(img.height(), img.width(), 4) if fmt == img.Format_RGB32: arr[...,3] = 255 if copy: arr = arr.copy() if transpose: return arr.transpose((1,0,2)) else: return arr def colorToAlpha(data, color): """ Given an RGBA image in *data*, convert *color* to be transparent. *data* must be an array (w, h, 3 or 4) of ubyte values and *color* must be an array (3) of ubyte values. This is particularly useful for use with images that have a black or white background. Algorithm is taken from Gimp's color-to-alpha function in plug-ins/common/colortoalpha.c Credit: /* * Color To Alpha plug-in v1.0 by Seth Burgess, sjburges@gimp.org 1999/05/14 * with algorithm by clahey */ """ data = data.astype(float) if data.shape[-1] == 3: ## add alpha channel if needed d2 = np.empty(data.shape[:2]+(4,), dtype=data.dtype) d2[...,:3] = data d2[...,3] = 255 data = d2 color = color.astype(float) alpha = np.zeros(data.shape[:2]+(3,), dtype=float) output = data.copy() for i in [0,1,2]: d = data[...,i] c = color[i] mask = d > c alpha[...,i][mask] = (d[mask] - c) / (255. - c) imask = d < c alpha[...,i][imask] = (c - d[imask]) / c output[...,3] = alpha.max(axis=2) * 255. mask = output[...,3] >= 1.0 ## avoid zero division while processing alpha channel correction = 255. / output[...,3][mask] ## increase value to compensate for decreased alpha for i in [0,1,2]: output[...,i][mask] = ((output[...,i][mask]-color[i]) * correction) + color[i] output[...,3][mask] *= data[...,3][mask] / 255. ## combine computed and previous alpha values #raise Exception() return np.clip(output, 0, 255).astype(np.ubyte) def gaussianFilter(data, sigma): """ Drop-in replacement for scipy.ndimage.gaussian_filter. (note: results are only approximately equal to the output of gaussian_filter) """ if np.isscalar(sigma): sigma = (sigma,) * data.ndim baseline = data.mean() filtered = data - baseline for ax in range(data.ndim): s = sigma[ax] if s == 0: continue # generate 1D gaussian kernel ksize = int(s * 6) x = np.arange(-ksize, ksize) kernel = np.exp(-x**2 / (2*s**2)) kshape = [1,] * data.ndim kshape[ax] = len(kernel) kernel = kernel.reshape(kshape) # convolve as product of FFTs shape = data.shape[ax] + ksize scale = 1.0 / (abs(s) * (2*np.pi)**0.5) filtered = scale * np.fft.irfft(np.fft.rfft(filtered, shape, axis=ax) * np.fft.rfft(kernel, shape, axis=ax), axis=ax) # clip off extra data sl = [slice(None)] * data.ndim sl[ax] = slice(filtered.shape[ax]-data.shape[ax],None,None) filtered = filtered[tuple(sl)] return filtered + baseline def downsample(data, n, axis=0, xvals='subsample'): """Downsample by averaging points together across axis. If multiple axes are specified, runs once per axis. If a metaArray is given, then the axis values can be either subsampled or downsampled to match. """ ma = None if (hasattr(data, 'implements') and data.implements('MetaArray')): ma = data data = data.view(np.ndarray) if hasattr(axis, '__len__'): if not hasattr(n, '__len__'): n = [n]*len(axis) for i in range(len(axis)): data = downsample(data, n[i], axis[i]) return data if n <= 1: return data nPts = int(data.shape[axis] / n) s = list(data.shape) s[axis] = nPts s.insert(axis+1, n) sl = [slice(None)] * data.ndim sl[axis] = slice(0, nPts*n) d1 = data[tuple(sl)] #print d1.shape, s d1.shape = tuple(s) d2 = d1.mean(axis+1) if ma is None: return d2 else: info = ma.infoCopy() if 'values' in info[axis]: if xvals == 'subsample': info[axis]['values'] = info[axis]['values'][::n][:nPts] elif xvals == 'downsample': info[axis]['values'] = downsample(info[axis]['values'], n) return MetaArray(d2, info=info) def arrayToQPath(x, y, connect='all'): """Convert an array of x,y coordinats to QPainterPath as efficiently as possible. The *connect* argument may be 'all', indicating that each point should be connected to the next; 'pairs', indicating that each pair of points should be connected, or an array of int32 values (0 or 1) indicating connections. """ ## Create all vertices in path. The method used below creates a binary format so that all ## vertices can be read in at once. This binary format may change in future versions of Qt, ## so the original (slower) method is left here for emergencies: #path.moveTo(x[0], y[0]) #if connect == 'all': #for i in range(1, y.shape[0]): #path.lineTo(x[i], y[i]) #elif connect == 'pairs': #for i in range(1, y.shape[0]): #if i%2 == 0: #path.lineTo(x[i], y[i]) #else: #path.moveTo(x[i], y[i]) #elif isinstance(connect, np.ndarray): #for i in range(1, y.shape[0]): #if connect[i] == 1: #path.lineTo(x[i], y[i]) #else: #path.moveTo(x[i], y[i]) #else: #raise Exception('connect argument must be "all", "pairs", or array') ## Speed this up using >> operator ## Format is: ## numVerts(i4) 0(i4) ## x(f8) y(f8) 0(i4) <-- 0 means this vertex does not connect ## x(f8) y(f8) 1(i4) <-- 1 means this vertex connects to the previous vertex ## ... ## 0(i4) ## ## All values are big endian--pack using struct.pack('>d') or struct.pack('>i') path = QtGui.QPainterPath() #profiler = debug.Profiler() n = x.shape[0] # create empty array, pad with extra space on either end arr = np.empty(n+2, dtype=[('x', '>f8'), ('y', '>f8'), ('c', '>i4')]) # write first two integers #profiler('allocate empty') byteview = arr.view(dtype=np.ubyte) byteview[:12] = 0 byteview.data[12:20] = struct.pack('>ii', n, 0) #profiler('pack header') # Fill array with vertex values arr[1:-1]['x'] = x arr[1:-1]['y'] = y # decide which points are connected by lines if eq(connect, 'all'): arr[1:-1]['c'] = 1 elif eq(connect, 'pairs'): arr[1:-1]['c'][::2] = 1 arr[1:-1]['c'][1::2] = 0 elif eq(connect, 'finite'): arr[1:-1]['c'] = np.isfinite(x) & np.isfinite(y) elif isinstance(connect, np.ndarray): arr[1:-1]['c'] = connect else: raise Exception('connect argument must be "all", "pairs", "finite", or array') #profiler('fill array') # write last 0 lastInd = 20*(n+1) byteview.data[lastInd:lastInd+4] = struct.pack('>i', 0) #profiler('footer') # create datastream object and stream into path ## Avoiding this method because QByteArray(str) leaks memory in PySide #buf = QtCore.QByteArray(arr.data[12:lastInd+4]) # I think one unnecessary copy happens here path.strn = byteview.data[12:lastInd+4] # make sure data doesn't run away try: buf = QtCore.QByteArray.fromRawData(path.strn) except TypeError: buf = QtCore.QByteArray(bytes(path.strn)) #profiler('create buffer') ds = QtCore.QDataStream(buf) ds >> path #profiler('load') return path #def isosurface(data, level): #""" #Generate isosurface from volumetric data using marching tetrahedra algorithm. #See Paul Bourke, "Polygonising a Scalar Field Using Tetrahedrons" (http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/) #*data* 3D numpy array of scalar values #*level* The level at which to generate an isosurface #""" #facets = [] ### mark everything below the isosurface level #mask = data < level #### make eight sub-fields #fields = np.empty((2,2,2), dtype=object) #slices = [slice(0,-1), slice(1,None)] #for i in [0,1]: #for j in [0,1]: #for k in [0,1]: #fields[i,j,k] = mask[slices[i], slices[j], slices[k]] ### split each cell into 6 tetrahedra ### these all have the same 'orienation'; points 1,2,3 circle ### clockwise around point 0 #tetrahedra = [ #[(0,1,0), (1,1,1), (0,1,1), (1,0,1)], #[(0,1,0), (0,1,1), (0,0,1), (1,0,1)], #[(0,1,0), (0,0,1), (0,0,0), (1,0,1)], #[(0,1,0), (0,0,0), (1,0,0), (1,0,1)], #[(0,1,0), (1,0,0), (1,1,0), (1,0,1)], #[(0,1,0), (1,1,0), (1,1,1), (1,0,1)] #] ### each tetrahedron will be assigned an index ### which determines how to generate its facets. ### this structure is: ### facets[index][facet1, facet2, ...] ### where each facet is triangular and its points are each ### interpolated between two points on the tetrahedron ### facet = [(p1a, p1b), (p2a, p2b), (p3a, p3b)] ### facet points always circle clockwise if you are looking ### at them from below the isosurface. #indexFacets = [ #[], ## all above #[[(0,1), (0,2), (0,3)]], # 0 below #[[(1,0), (1,3), (1,2)]], # 1 below #[[(0,2), (1,3), (1,2)], [(0,2), (0,3), (1,3)]], # 0,1 below #[[(2,0), (2,1), (2,3)]], # 2 below #[[(0,3), (1,2), (2,3)], [(0,3), (0,1), (1,2)]], # 0,2 below #[[(1,0), (2,3), (2,0)], [(1,0), (1,3), (2,3)]], # 1,2 below #[[(3,0), (3,1), (3,2)]], # 3 above #[[(3,0), (3,2), (3,1)]], # 3 below #[[(1,0), (2,0), (2,3)], [(1,0), (2,3), (1,3)]], # 0,3 below #[[(0,3), (2,3), (1,2)], [(0,3), (1,2), (0,1)]], # 1,3 below #[[(2,0), (2,3), (2,1)]], # 0,1,3 below #[[(0,2), (1,2), (1,3)], [(0,2), (1,3), (0,3)]], # 2,3 below #[[(1,0), (1,2), (1,3)]], # 0,2,3 below #[[(0,1), (0,3), (0,2)]], # 1,2,3 below #[] ## all below #] #for tet in tetrahedra: ### get the 4 fields for this tetrahedron #tetFields = [fields[c] for c in tet] ### generate an index for each grid cell #index = tetFields[0] + tetFields[1]*2 + tetFields[2]*4 + tetFields[3]*8 ### add facets #for i in xrange(index.shape[0]): # data x-axis #for j in xrange(index.shape[1]): # data y-axis #for k in xrange(index.shape[2]): # data z-axis #for f in indexFacets[index[i,j,k]]: # faces to generate for this tet #pts = [] #for l in [0,1,2]: # points in this face #p1 = tet[f[l][0]] # tet corner 1 #p2 = tet[f[l][1]] # tet corner 2 #pts.append([(p1[x]+p2[x])*0.5+[i,j,k][x]+0.5 for x in [0,1,2]]) ## interpolate between tet corners #facets.append(pts) #return facets def isocurve(data, level, connected=False, extendToEdge=False, path=False): """ Generate isocurve from 2D data using marching squares algorithm. ============== ========================================================= **Arguments:** data 2D numpy array of scalar values level The level at which to generate an isosurface connected If False, return a single long list of point pairs If True, return multiple long lists of connected point locations. (This is slower but better for drawing continuous lines) extendToEdge If True, extend the curves to reach the exact edges of the data. path if True, return a QPainterPath rather than a list of vertex coordinates. This forces connected=True. ============== ========================================================= This function is SLOW; plenty of room for optimization here. """ if path is True: connected = True if extendToEdge: d2 = np.empty((data.shape[0]+2, data.shape[1]+2), dtype=data.dtype) d2[1:-1, 1:-1] = data d2[0, 1:-1] = data[0] d2[-1, 1:-1] = data[-1] d2[1:-1, 0] = data[:, 0] d2[1:-1, -1] = data[:, -1] d2[0,0] = d2[0,1] d2[0,-1] = d2[1,-1] d2[-1,0] = d2[-1,1] d2[-1,-1] = d2[-1,-2] data = d2 sideTable = [ [], [0,1], [1,2], [0,2], [0,3], [1,3], [0,1,2,3], [2,3], [2,3], [0,1,2,3], [1,3], [0,3], [0,2], [1,2], [0,1], [] ] edgeKey=[ [(0,1), (0,0)], [(0,0), (1,0)], [(1,0), (1,1)], [(1,1), (0,1)] ] lines = [] ## mark everything below the isosurface level mask = data < level ### make four sub-fields and compute indexes for grid cells index = np.zeros([x-1 for x in data.shape], dtype=np.ubyte) fields = np.empty((2,2), dtype=object) slices = [slice(0,-1), slice(1,None)] for i in [0,1]: for j in [0,1]: fields[i,j] = mask[slices[i], slices[j]] #vertIndex = i - 2*j*i + 3*j + 4*k ## this is just to match Bourk's vertex numbering scheme vertIndex = i+2*j #print i,j,k," : ", fields[i,j,k], 2**vertIndex np.add(index, fields[i,j] * 2**vertIndex, out=index, casting='unsafe') #print index #print index ## add lines for i in range(index.shape[0]): # data x-axis for j in range(index.shape[1]): # data y-axis sides = sideTable[index[i,j]] for l in range(0, len(sides), 2): ## faces for this grid cell edges = sides[l:l+2] pts = [] for m in [0,1]: # points in this face p1 = edgeKey[edges[m]][0] # p1, p2 are points at either side of an edge p2 = edgeKey[edges[m]][1] v1 = data[i+p1[0], j+p1[1]] # v1 and v2 are the values at p1 and p2 v2 = data[i+p2[0], j+p2[1]] f = (level-v1) / (v2-v1) fi = 1.0 - f p = ( ## interpolate between corners p1[0]*fi + p2[0]*f + i + 0.5, p1[1]*fi + p2[1]*f + j + 0.5 ) if extendToEdge: ## check bounds p = ( min(data.shape[0]-2, max(0, p[0]-1)), min(data.shape[1]-2, max(0, p[1]-1)), ) if connected: gridKey = i + (1 if edges[m]==2 else 0), j + (1 if edges[m]==3 else 0), edges[m]%2 pts.append((p, gridKey)) ## give the actual position and a key identifying the grid location (for connecting segments) else: pts.append(p) lines.append(pts) if not connected: return lines ## turn disjoint list of segments into continuous lines #lines = [[2,5], [5,4], [3,4], [1,3], [6,7], [7,8], [8,6], [11,12], [12,15], [11,13], [13,14]] #lines = [[(float(a), a), (float(b), b)] for a,b in lines] points = {} ## maps each point to its connections for a,b in lines: if a[1] not in points: points[a[1]] = [] points[a[1]].append([a,b]) if b[1] not in points: points[b[1]] = [] points[b[1]].append([b,a]) ## rearrange into chains for k in list(points.keys()): try: chains = points[k] except KeyError: ## already used this point elsewhere continue #print "===========", k for chain in chains: #print " chain:", chain x = None while True: if x == chain[-1][1]: break ## nothing left to do on this chain x = chain[-1][1] if x == k: break ## chain has looped; we're done and can ignore the opposite chain y = chain[-2][1] connects = points[x] for conn in connects[:]: if conn[1][1] != y: #print " ext:", conn chain.extend(conn[1:]) #print " del:", x del points[x] if chain[0][1] == chain[-1][1]: # looped chain; no need to continue the other direction chains.pop() break ## extract point locations lines = [] for chain in points.values(): if len(chain) == 2: chain = chain[1][1:][::-1] + chain[0] # join together ends of chain else: chain = chain[0] lines.append([p[0] for p in chain]) if not path: return lines ## a list of pairs of points path = QtGui.QPainterPath() for line in lines: path.moveTo(*line[0]) for p in line[1:]: path.lineTo(*p) return path def traceImage(image, values, smooth=0.5): """ Convert an image to a set of QPainterPath curves. One curve will be generated for each item in *values*; each curve outlines the area of the image that is closer to its value than to any others. If image is RGB or RGBA, then the shape of values should be (nvals, 3/4) The parameter *smooth* is expressed in pixels. """ try: import scipy.ndimage as ndi except ImportError: raise Exception("traceImage() requires the package scipy.ndimage, but it is not importable.") if values.ndim == 2: values = values.T values = values[np.newaxis, np.newaxis, ...].astype(float) image = image[..., np.newaxis].astype(float) diff = np.abs(image-values) if values.ndim == 4: diff = diff.sum(axis=2) labels = np.argmin(diff, axis=2) paths = [] for i in range(diff.shape[-1]): d = (labels==i).astype(float) d = gaussianFilter(d, (smooth, smooth)) lines = isocurve(d, 0.5, connected=True, extendToEdge=True) path = QtGui.QPainterPath() for line in lines: path.moveTo(*line[0]) for p in line[1:]: path.lineTo(*p) paths.append(path) return paths IsosurfaceDataCache = None def isosurface(data, level): """ Generate isosurface from volumetric data using marching cubes algorithm. See Paul Bourke, "Polygonising a Scalar Field" (http://paulbourke.net/geometry/polygonise/) *data* 3D numpy array of scalar values. Must be contiguous. *level* The level at which to generate an isosurface Returns an array of vertex coordinates (Nv, 3) and an array of per-face vertex indexes (Nf, 3) """ ## For improvement, see: ## ## Efficient implementation of Marching Cubes' cases with topological guarantees. ## Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan Tavares. ## Journal of Graphics Tools 8(2): pp. 1-15 (december 2003) ## Precompute lookup tables on the first run global IsosurfaceDataCache if IsosurfaceDataCache is None: ## map from grid cell index to edge index. ## grid cell index tells us which corners are below the isosurface, ## edge index tells us which edges are cut by the isosurface. ## (Data stolen from Bourk; see above.) edgeTable = np.array([ 0x0 , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc , 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0 ], dtype=np.uint16) ## Table of triangles to use for filling each grid cell. ## Each set of three integers tells us which three edges to ## draw a triangle between. ## (Data stolen from Bourk; see above.) triTable = [ [], [0, 8, 3], [0, 1, 9], [1, 8, 3, 9, 8, 1], [1, 2, 10], [0, 8, 3, 1, 2, 10], [9, 2, 10, 0, 2, 9], [2, 8, 3, 2, 10, 8, 10, 9, 8], [3, 11, 2], [0, 11, 2, 8, 11, 0], [1, 9, 0, 2, 3, 11], [1, 11, 2, 1, 9, 11, 9, 8, 11], [3, 10, 1, 11, 10, 3], [0, 10, 1, 0, 8, 10, 8, 11, 10], [3, 9, 0, 3, 11, 9, 11, 10, 9], [9, 8, 10, 10, 8, 11], [4, 7, 8], [4, 3, 0, 7, 3, 4], [0, 1, 9, 8, 4, 7], [4, 1, 9, 4, 7, 1, 7, 3, 1], [1, 2, 10, 8, 4, 7], [3, 4, 7, 3, 0, 4, 1, 2, 10], [9, 2, 10, 9, 0, 2, 8, 4, 7], [2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4], [8, 4, 7, 3, 11, 2], [11, 4, 7, 11, 2, 4, 2, 0, 4], [9, 0, 1, 8, 4, 7, 2, 3, 11], [4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1], [3, 10, 1, 3, 11, 10, 7, 8, 4], [1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4], [4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3], [4, 7, 11, 4, 11, 9, 9, 11, 10], [9, 5, 4], [9, 5, 4, 0, 8, 3], [0, 5, 4, 1, 5, 0], [8, 5, 4, 8, 3, 5, 3, 1, 5], [1, 2, 10, 9, 5, 4], [3, 0, 8, 1, 2, 10, 4, 9, 5], [5, 2, 10, 5, 4, 2, 4, 0, 2], [2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8], [9, 5, 4, 2, 3, 11], [0, 11, 2, 0, 8, 11, 4, 9, 5], [0, 5, 4, 0, 1, 5, 2, 3, 11], [2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5], [10, 3, 11, 10, 1, 3, 9, 5, 4], [4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10], [5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3], [5, 4, 8, 5, 8, 10, 10, 8, 11], [9, 7, 8, 5, 7, 9], [9, 3, 0, 9, 5, 3, 5, 7, 3], [0, 7, 8, 0, 1, 7, 1, 5, 7], [1, 5, 3, 3, 5, 7], [9, 7, 8, 9, 5, 7, 10, 1, 2], [10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3], [8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2], [2, 10, 5, 2, 5, 3, 3, 5, 7], [7, 9, 5, 7, 8, 9, 3, 11, 2], [9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11], [2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7], [11, 2, 1, 11, 1, 7, 7, 1, 5], [9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11], [5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0], [11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0], [11, 10, 5, 7, 11, 5], [10, 6, 5], [0, 8, 3, 5, 10, 6], [9, 0, 1, 5, 10, 6], [1, 8, 3, 1, 9, 8, 5, 10, 6], [1, 6, 5, 2, 6, 1], [1, 6, 5, 1, 2, 6, 3, 0, 8], [9, 6, 5, 9, 0, 6, 0, 2, 6], [5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8], [2, 3, 11, 10, 6, 5], [11, 0, 8, 11, 2, 0, 10, 6, 5], [0, 1, 9, 2, 3, 11, 5, 10, 6], [5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11], [6, 3, 11, 6, 5, 3, 5, 1, 3], [0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6], [3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9], [6, 5, 9, 6, 9, 11, 11, 9, 8], [5, 10, 6, 4, 7, 8], [4, 3, 0, 4, 7, 3, 6, 5, 10], [1, 9, 0, 5, 10, 6, 8, 4, 7], [10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4], [6, 1, 2, 6, 5, 1, 4, 7, 8], [1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7], [8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6], [7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9], [3, 11, 2, 7, 8, 4, 10, 6, 5], [5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11], [0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6], [9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6], [8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6], [5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11], [0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7], [6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9], [10, 4, 9, 6, 4, 10], [4, 10, 6, 4, 9, 10, 0, 8, 3], [10, 0, 1, 10, 6, 0, 6, 4, 0], [8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10], [1, 4, 9, 1, 2, 4, 2, 6, 4], [3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4], [0, 2, 4, 4, 2, 6], [8, 3, 2, 8, 2, 4, 4, 2, 6], [10, 4, 9, 10, 6, 4, 11, 2, 3], [0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6], [3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10], [6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1], [9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3], [8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1], [3, 11, 6, 3, 6, 0, 0, 6, 4], [6, 4, 8, 11, 6, 8], [7, 10, 6, 7, 8, 10, 8, 9, 10], [0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10], [10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0], [10, 6, 7, 10, 7, 1, 1, 7, 3], [1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7], [2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9], [7, 8, 0, 7, 0, 6, 6, 0, 2], [7, 3, 2, 6, 7, 2], [2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7], [2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7], [1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11], [11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1], [8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6], [0, 9, 1, 11, 6, 7], [7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0], [7, 11, 6], [7, 6, 11], [3, 0, 8, 11, 7, 6], [0, 1, 9, 11, 7, 6], [8, 1, 9, 8, 3, 1, 11, 7, 6], [10, 1, 2, 6, 11, 7], [1, 2, 10, 3, 0, 8, 6, 11, 7], [2, 9, 0, 2, 10, 9, 6, 11, 7], [6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8], [7, 2, 3, 6, 2, 7], [7, 0, 8, 7, 6, 0, 6, 2, 0], [2, 7, 6, 2, 3, 7, 0, 1, 9], [1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6], [10, 7, 6, 10, 1, 7, 1, 3, 7], [10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8], [0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7], [7, 6, 10, 7, 10, 8, 8, 10, 9], [6, 8, 4, 11, 8, 6], [3, 6, 11, 3, 0, 6, 0, 4, 6], [8, 6, 11, 8, 4, 6, 9, 0, 1], [9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6], [6, 8, 4, 6, 11, 8, 2, 10, 1], [1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6], [4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9], [10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3], [8, 2, 3, 8, 4, 2, 4, 6, 2], [0, 4, 2, 4, 6, 2], [1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8], [1, 9, 4, 1, 4, 2, 2, 4, 6], [8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1], [10, 1, 0, 10, 0, 6, 6, 0, 4], [4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3], [10, 9, 4, 6, 10, 4], [4, 9, 5, 7, 6, 11], [0, 8, 3, 4, 9, 5, 11, 7, 6], [5, 0, 1, 5, 4, 0, 7, 6, 11], [11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5], [9, 5, 4, 10, 1, 2, 7, 6, 11], [6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5], [7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2], [3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6], [7, 2, 3, 7, 6, 2, 5, 4, 9], [9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7], [3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0], [6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8], [9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7], [1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4], [4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10], [7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10], [6, 9, 5, 6, 11, 9, 11, 8, 9], [3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5], [0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11], [6, 11, 3, 6, 3, 5, 5, 3, 1], [1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6], [0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10], [11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5], [6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3], [5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2], [9, 5, 6, 9, 6, 0, 0, 6, 2], [1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8], [1, 5, 6, 2, 1, 6], [1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6], [10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0], [0, 3, 8, 5, 6, 10], [10, 5, 6], [11, 5, 10, 7, 5, 11], [11, 5, 10, 11, 7, 5, 8, 3, 0], [5, 11, 7, 5, 10, 11, 1, 9, 0], [10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1], [11, 1, 2, 11, 7, 1, 7, 5, 1], [0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11], [9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7], [7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2], [2, 5, 10, 2, 3, 5, 3, 7, 5], [8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5], [9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2], [9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2], [1, 3, 5, 3, 7, 5], [0, 8, 7, 0, 7, 1, 1, 7, 5], [9, 0, 3, 9, 3, 5, 5, 3, 7], [9, 8, 7, 5, 9, 7], [5, 8, 4, 5, 10, 8, 10, 11, 8], [5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0], [0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5], [10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4], [2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8], [0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11], [0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5], [9, 4, 5, 2, 11, 3], [2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4], [5, 10, 2, 5, 2, 4, 4, 2, 0], [3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9], [5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2], [8, 4, 5, 8, 5, 3, 3, 5, 1], [0, 4, 5, 1, 0, 5], [8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5], [9, 4, 5], [4, 11, 7, 4, 9, 11, 9, 10, 11], [0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11], [1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11], [3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4], [4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2], [9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3], [11, 7, 4, 11, 4, 2, 2, 4, 0], [11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4], [2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9], [9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7], [3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10], [1, 10, 2, 8, 7, 4], [4, 9, 1, 4, 1, 7, 7, 1, 3], [4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1], [4, 0, 3, 7, 4, 3], [4, 8, 7], [9, 10, 8, 10, 11, 8], [3, 0, 9, 3, 9, 11, 11, 9, 10], [0, 1, 10, 0, 10, 8, 8, 10, 11], [3, 1, 10, 11, 3, 10], [1, 2, 11, 1, 11, 9, 9, 11, 8], [3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9], [0, 2, 11, 8, 0, 11], [3, 2, 11], [2, 3, 8, 2, 8, 10, 10, 8, 9], [9, 10, 2, 0, 9, 2], [2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8], [1, 10, 2], [1, 3, 8, 9, 1, 8], [0, 9, 1], [0, 3, 8], [] ] edgeShifts = np.array([ ## maps edge ID (0-11) to (x,y,z) cell offset and edge ID (0-2) [0, 0, 0, 0], [1, 0, 0, 1], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 1, 1], [0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 2], [1, 0, 0, 2], [1, 1, 0, 2], [0, 1, 0, 2], #[9, 9, 9, 9] ## fake ], dtype=np.uint16) # don't use ubyte here! This value gets added to cell index later; will need the extra precision. nTableFaces = np.array([len(f)/3 for f in triTable], dtype=np.ubyte) faceShiftTables = [None] for i in range(1,6): ## compute lookup table of index: vertexes mapping faceTableI = np.zeros((len(triTable), i*3), dtype=np.ubyte) faceTableInds = np.argwhere(nTableFaces == i) faceTableI[faceTableInds[:,0]] = np.array([triTable[j[0]] for j in faceTableInds]) faceTableI = faceTableI.reshape((len(triTable), i, 3)) faceShiftTables.append(edgeShifts[faceTableI]) ## Let's try something different: #faceTable = np.empty((256, 5, 3, 4), dtype=np.ubyte) # (grid cell index, faces, vertexes, edge lookup) #for i,f in enumerate(triTable): #f = np.array(f + [12] * (15-len(f))).reshape(5,3) #faceTable[i] = edgeShifts[f] IsosurfaceDataCache = (faceShiftTables, edgeShifts, edgeTable, nTableFaces) else: faceShiftTables, edgeShifts, edgeTable, nTableFaces = IsosurfaceDataCache # We use strides below, which means we need contiguous array input. # Ideally we can fix this just by removing the dependency on strides. if not data.flags['C_CONTIGUOUS']: raise TypeError("isosurface input data must be c-contiguous.") ## mark everything below the isosurface level mask = data < level ### make eight sub-fields and compute indexes for grid cells index = np.zeros([x-1 for x in data.shape], dtype=np.ubyte) fields = np.empty((2,2,2), dtype=object) slices = [slice(0,-1), slice(1,None)] for i in [0,1]: for j in [0,1]: for k in [0,1]: fields[i,j,k] = mask[slices[i], slices[j], slices[k]] vertIndex = i - 2*j*i + 3*j + 4*k ## this is just to match Bourk's vertex numbering scheme np.add(index, fields[i,j,k] * 2**vertIndex, out=index, casting='unsafe') ### Generate table of edges that have been cut cutEdges = np.zeros([x+1 for x in index.shape]+[3], dtype=np.uint32) edges = edgeTable[index] for i, shift in enumerate(edgeShifts[:12]): slices = [slice(shift[j],cutEdges.shape[j]+(shift[j]-1)) for j in range(3)] cutEdges[slices[0], slices[1], slices[2], shift[3]] += edges & 2**i ## for each cut edge, interpolate to see where exactly the edge is cut and generate vertex positions m = cutEdges > 0 vertexInds = np.argwhere(m) ## argwhere is slow! vertexes = vertexInds[:,:3].astype(np.float32) dataFlat = data.reshape(data.shape[0]*data.shape[1]*data.shape[2]) ## re-use the cutEdges array as a lookup table for vertex IDs cutEdges[vertexInds[:,0], vertexInds[:,1], vertexInds[:,2], vertexInds[:,3]] = np.arange(vertexInds.shape[0]) for i in [0,1,2]: vim = vertexInds[:,3] == i vi = vertexInds[vim, :3] viFlat = (vi * (np.array(data.strides[:3]) // data.itemsize)[np.newaxis,:]).sum(axis=1) v1 = dataFlat[viFlat] v2 = dataFlat[viFlat + data.strides[i]//data.itemsize] vertexes[vim,i] += (level-v1) / (v2-v1) ### compute the set of vertex indexes for each face. ## This works, but runs a bit slower. #cells = np.argwhere((index != 0) & (index != 255)) ## all cells with at least one face #cellInds = index[cells[:,0], cells[:,1], cells[:,2]] #verts = faceTable[cellInds] #mask = verts[...,0,0] != 9 #verts[...,:3] += cells[:,np.newaxis,np.newaxis,:] ## we now have indexes into cutEdges #verts = verts[mask] #faces = cutEdges[verts[...,0], verts[...,1], verts[...,2], verts[...,3]] ## and these are the vertex indexes we want. ## To allow this to be vectorized efficiently, we count the number of faces in each ## grid cell and handle each group of cells with the same number together. ## determine how many faces to assign to each grid cell nFaces = nTableFaces[index] totFaces = nFaces.sum() faces = np.empty((totFaces, 3), dtype=np.uint32) ptr = 0 #import debug #p = debug.Profiler() ## this helps speed up an indexing operation later on cs = np.array(cutEdges.strides)//cutEdges.itemsize cutEdges = cutEdges.flatten() ## this, strangely, does not seem to help. #ins = np.array(index.strides)/index.itemsize #index = index.flatten() for i in range(1,6): ### expensive: #profiler() cells = np.argwhere(nFaces == i) ## all cells which require i faces (argwhere is expensive) #profiler() if cells.shape[0] == 0: continue cellInds = index[cells[:,0], cells[:,1], cells[:,2]] ## index values of cells to process for this round #profiler() ### expensive: verts = faceShiftTables[i][cellInds] #profiler() np.add(verts[...,:3], cells[:,np.newaxis,np.newaxis,:], out=verts[...,:3], casting='unsafe') ## we now have indexes into cutEdges verts = verts.reshape((verts.shape[0]*i,)+verts.shape[2:]) #profiler() ### expensive: verts = (verts * cs[np.newaxis, np.newaxis, :]).sum(axis=2) vertInds = cutEdges[verts] #profiler() nv = vertInds.shape[0] #profiler() faces[ptr:ptr+nv] = vertInds #.reshape((nv, 3)) #profiler() ptr += nv return vertexes, faces def invertQTransform(tr): """Return a QTransform that is the inverse of *tr*. Rasises an exception if tr is not invertible. Note that this function is preferred over QTransform.inverted() due to bugs in that method. (specifically, Qt has floating-point precision issues when determining whether a matrix is invertible) """ try: import numpy.linalg arr = np.array([[tr.m11(), tr.m12(), tr.m13()], [tr.m21(), tr.m22(), tr.m23()], [tr.m31(), tr.m32(), tr.m33()]]) inv = numpy.linalg.inv(arr) return QtGui.QTransform(inv[0,0], inv[0,1], inv[0,2], inv[1,0], inv[1,1], inv[1,2], inv[2,0], inv[2,1]) except ImportError: inv = tr.inverted() if inv[1] is False: raise Exception("Transform is not invertible.") return inv[0] def pseudoScatter(data, spacing=None, shuffle=True, bidir=False): """ Used for examining the distribution of values in a set. Produces scattering as in beeswarm or column scatter plots. Given a list of x-values, construct a set of y-values such that an x,y scatter-plot will not have overlapping points (it will look similar to a histogram). """ inds = np.arange(len(data)) if shuffle: np.random.shuffle(inds) data = data[inds] if spacing is None: spacing = 2.*np.std(data)/len(data)**0.5 s2 = spacing**2 yvals = np.empty(len(data)) if len(data) == 0: return yvals yvals[0] = 0 for i in range(1,len(data)): x = data[i] # current x value to be placed x0 = data[:i] # all x values already placed y0 = yvals[:i] # all y values already placed y = 0 dx = (x0-x)**2 # x-distance to each previous point xmask = dx < s2 # exclude anything too far away if xmask.sum() > 0: if bidir: dirs = [-1, 1] else: dirs = [1] yopts = [] for direction in dirs: y = 0 dx2 = dx[xmask] dy = (s2 - dx2)**0.5 limits = np.empty((2,len(dy))) # ranges of y-values to exclude limits[0] = y0[xmask] - dy limits[1] = y0[xmask] + dy while True: # ignore anything below this y-value if direction > 0: mask = limits[1] >= y else: mask = limits[0] <= y limits2 = limits[:,mask] # are we inside an excluded region? mask = (limits2[0] < y) & (limits2[1] > y) if mask.sum() == 0: break if direction > 0: y = limits2[:,mask].max() else: y = limits2[:,mask].min() yopts.append(y) if bidir: y = yopts[0] if -yopts[0] < yopts[1] else yopts[1] else: y = yopts[0] yvals[i] = y return yvals[np.argsort(inds)] ## un-shuffle values before returning def toposort(deps, nodes=None, seen=None, stack=None, depth=0): """Topological sort. Arguments are: deps dictionary describing dependencies where a:[b,c] means "a depends on b and c" nodes optional, specifies list of starting nodes (these should be the nodes which are not depended on by any other nodes). Other candidate starting nodes will be ignored. Example:: # Sort the following graph: # # B ──┬─────> C <── D # │ │ # E <─┴─> A <─┘ # deps = {'a': ['b', 'c'], 'c': ['b', 'd'], 'e': ['b']} toposort(deps) => ['b', 'd', 'c', 'a', 'e'] """ # fill in empty dep lists deps = deps.copy() for k,v in list(deps.items()): for k in v: if k not in deps: deps[k] = [] if nodes is None: ## run through deps to find nodes that are not depended upon rem = set() for dep in deps.values(): rem |= set(dep) nodes = set(deps.keys()) - rem if seen is None: seen = set() stack = [] sorted = [] for n in nodes: if n in stack: raise Exception("Cyclic dependency detected", stack + [n]) if n in seen: continue seen.add(n) sorted.extend( toposort(deps, deps[n], seen, stack+[n], depth=depth+1)) sorted.append(n) return sorted def disconnect(signal, slot): """Disconnect a Qt signal from a slot. This method augments Qt's Signal.disconnect(): * Return bool indicating whether disconnection was successful, rather than raising an exception * Attempt to disconnect prior versions of the slot when using pg.reload """ while True: try: signal.disconnect(slot) return True except (TypeError, RuntimeError): slot = reload.getPreviousVersion(slot) if slot is None: return False class SignalBlock(object): """Class used to temporarily block a Qt signal connection:: with SignalBlock(signal, slot): # do something that emits a signal; it will # not be delivered to slot """ def __init__(self, signal, slot): self.signal = signal self.slot = slot def __enter__(self): self.reconnect = disconnect(self.signal, self.slot) return self def __exit__(self, *args): if self.reconnect: self.signal.connect(self.slot)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/SRTTransform3D.py
.py
10,879
316
# -*- coding: utf-8 -*- from .Qt import QtCore, QtGui from .Vector import Vector from .Transform3D import Transform3D from .Vector import Vector import numpy as np class SRTTransform3D(Transform3D): """4x4 Transform matrix that can always be represented as a combination of 3 matrices: scale * rotate * translate This transform has no shear; angles are always preserved. """ def __init__(self, init=None): Transform3D.__init__(self) self.reset() if init is None: return if init.__class__ is QtGui.QTransform: init = SRTTransform(init) if isinstance(init, dict): self.restoreState(init) elif isinstance(init, SRTTransform3D): self._state = { 'pos': Vector(init._state['pos']), 'scale': Vector(init._state['scale']), 'angle': init._state['angle'], 'axis': Vector(init._state['axis']), } self.update() elif isinstance(init, SRTTransform): self._state = { 'pos': Vector(init._state['pos']), 'scale': Vector(init._state['scale']), 'angle': init._state['angle'], 'axis': Vector(0, 0, 1), } self._state['scale'][2] = 1.0 self.update() elif isinstance(init, QtGui.QMatrix4x4): self.setFromMatrix(init) else: raise Exception("Cannot build SRTTransform3D from argument type:", type(init)) def getScale(self): return Vector(self._state['scale']) def getRotation(self): """Return (angle, axis) of rotation""" return self._state['angle'], Vector(self._state['axis']) def getTranslation(self): return Vector(self._state['pos']) def reset(self): self._state = { 'pos': Vector(0,0,0), 'scale': Vector(1,1,1), 'angle': 0.0, ## in degrees 'axis': (0, 0, 1) } self.update() def translate(self, *args): """Adjust the translation of this transform""" t = Vector(*args) self.setTranslate(self._state['pos']+t) def setTranslate(self, *args): """Set the translation of this transform""" self._state['pos'] = Vector(*args) self.update() def scale(self, *args): """adjust the scale of this transform""" ## try to prevent accidentally setting 0 scale on z axis if len(args) == 1 and hasattr(args[0], '__len__'): args = args[0] if len(args) == 2: args = args + (1,) s = Vector(*args) self.setScale(self._state['scale'] * s) def setScale(self, *args): """Set the scale of this transform""" if len(args) == 1 and hasattr(args[0], '__len__'): args = args[0] if len(args) == 2: args = args + (1,) self._state['scale'] = Vector(*args) self.update() def rotate(self, angle, axis=(0,0,1)): """Adjust the rotation of this transform""" origAxis = self._state['axis'] if axis[0] == origAxis[0] and axis[1] == origAxis[1] and axis[2] == origAxis[2]: self.setRotate(self._state['angle'] + angle) else: m = QtGui.QMatrix4x4() m.translate(*self._state['pos']) m.rotate(self._state['angle'], *self._state['axis']) m.rotate(angle, *axis) m.scale(*self._state['scale']) self.setFromMatrix(m) def setRotate(self, angle, axis=(0,0,1)): """Set the transformation rotation to angle (in degrees)""" self._state['angle'] = angle self._state['axis'] = Vector(axis) self.update() def setFromMatrix(self, m): """ Set this transform based on the elements of *m* The input matrix must be affine AND have no shear, otherwise the conversion will most likely fail. """ import numpy.linalg for i in range(4): self.setRow(i, m.row(i)) m = self.matrix().reshape(4,4) ## translation is 4th column self._state['pos'] = m[:3,3] ## scale is vector-length of first three columns scale = (m[:3,:3]**2).sum(axis=0)**0.5 ## see whether there is an inversion z = np.cross(m[0, :3], m[1, :3]) if np.dot(z, m[2, :3]) < 0: scale[1] *= -1 ## doesn't really matter which axis we invert self._state['scale'] = scale ## rotation axis is the eigenvector with eigenvalue=1 r = m[:3, :3] / scale[np.newaxis, :] try: evals, evecs = numpy.linalg.eig(r) except: print("Rotation matrix: %s" % str(r)) print("Scale: %s" % str(scale)) print("Original matrix: %s" % str(m)) raise eigIndex = np.argwhere(np.abs(evals-1) < 1e-6) if len(eigIndex) < 1: print("eigenvalues: %s" % str(evals)) print("eigenvectors: %s" % str(evecs)) print("index: %s, %s" % (str(eigIndex), str(evals-1))) raise Exception("Could not determine rotation axis.") axis = evecs[:,eigIndex[0,0]].real axis /= ((axis**2).sum())**0.5 self._state['axis'] = axis ## trace(r) == 2 cos(angle) + 1, so: cos = (r.trace()-1)*0.5 ## this only gets us abs(angle) ## The off-diagonal values can be used to correct the angle ambiguity, ## but we need to figure out which element to use: axisInd = np.argmax(np.abs(axis)) rInd,sign = [((1,2), -1), ((0,2), 1), ((0,1), -1)][axisInd] ## Then we have r-r.T = sin(angle) * 2 * sign * axis[axisInd]; ## solve for sin(angle) sin = (r-r.T)[rInd] / (2. * sign * axis[axisInd]) ## finally, we get the complete angle from arctan(sin/cos) self._state['angle'] = np.arctan2(sin, cos) * 180 / np.pi if self._state['angle'] == 0: self._state['axis'] = (0,0,1) def as2D(self): """Return a QTransform representing the x,y portion of this transform (if possible)""" return SRTTransform(self) #def __div__(self, t): #"""A / B == B^-1 * A""" #dt = t.inverted()[0] * self #return SRTTransform(dt) #def __mul__(self, t): #return SRTTransform(QtGui.QTransform.__mul__(self, t)) def saveState(self): p = self._state['pos'] s = self._state['scale'] ax = self._state['axis'] #if s[0] == 0: #raise Exception('Invalid scale: %s' % str(s)) return { 'pos': (p[0], p[1], p[2]), 'scale': (s[0], s[1], s[2]), 'angle': self._state['angle'], 'axis': (ax[0], ax[1], ax[2]) } def restoreState(self, state): self._state['pos'] = Vector(state.get('pos', (0.,0.,0.))) scale = state.get('scale', (1.,1.,1.)) scale = tuple(scale) + (1.,) * (3-len(scale)) self._state['scale'] = Vector(scale) self._state['angle'] = state.get('angle', 0.) self._state['axis'] = state.get('axis', (0, 0, 1)) self.update() def update(self): Transform3D.setToIdentity(self) ## modifications to the transform are multiplied on the right, so we need to reverse order here. Transform3D.translate(self, *self._state['pos']) Transform3D.rotate(self, self._state['angle'], *self._state['axis']) Transform3D.scale(self, *self._state['scale']) def __repr__(self): return str(self.saveState()) def matrix(self, nd=3): if nd == 3: return np.array(self.copyDataTo()).reshape(4,4) elif nd == 2: m = np.array(self.copyDataTo()).reshape(4,4) m[2] = m[3] m[:,2] = m[:,3] return m[:3,:3] else: raise Exception("Argument 'nd' must be 2 or 3") if __name__ == '__main__': import widgets import GraphicsView from functions import * app = QtGui.QApplication([]) win = QtGui.QMainWindow() win.show() cw = GraphicsView.GraphicsView() #cw.enableMouse() win.setCentralWidget(cw) s = QtGui.QGraphicsScene() cw.setScene(s) win.resize(600,600) cw.enableMouse() cw.setRange(QtCore.QRectF(-100., -100., 200., 200.)) class Item(QtGui.QGraphicsItem): def __init__(self): QtGui.QGraphicsItem.__init__(self) self.b = QtGui.QGraphicsRectItem(20, 20, 20, 20, self) self.b.setPen(QtGui.QPen(mkPen('y'))) self.t1 = QtGui.QGraphicsTextItem(self) self.t1.setHtml('<span style="color: #F00">R</span>') self.t1.translate(20, 20) self.l1 = QtGui.QGraphicsLineItem(10, 0, -10, 0, self) self.l2 = QtGui.QGraphicsLineItem(0, 10, 0, -10, self) self.l1.setPen(QtGui.QPen(mkPen('y'))) self.l2.setPen(QtGui.QPen(mkPen('y'))) def boundingRect(self): return QtCore.QRectF() def paint(self, *args): pass #s.addItem(b) #s.addItem(t1) item = Item() s.addItem(item) l1 = QtGui.QGraphicsLineItem(10, 0, -10, 0) l2 = QtGui.QGraphicsLineItem(0, 10, 0, -10) l1.setPen(QtGui.QPen(mkPen('r'))) l2.setPen(QtGui.QPen(mkPen('r'))) s.addItem(l1) s.addItem(l2) tr1 = SRTTransform() tr2 = SRTTransform() tr3 = QtGui.QTransform() tr3.translate(20, 0) tr3.rotate(45) print("QTransform -> Transform: %s" % str(SRTTransform(tr3))) print("tr1: %s" % str(tr1)) tr2.translate(20, 0) tr2.rotate(45) print("tr2: %s" % str(tr2)) dt = tr2/tr1 print("tr2 / tr1 = %s" % str(dt)) print("tr2 * tr1 = %s" % str(tr2*tr1)) tr4 = SRTTransform() tr4.scale(-1, 1) tr4.rotate(30) print("tr1 * tr4 = %s" % str(tr1*tr4)) w1 = widgets.TestROI((19,19), (22, 22), invertible=True) #w2 = widgets.TestROI((0,0), (150, 150)) w1.setZValue(10) s.addItem(w1) #s.addItem(w2) w1Base = w1.getState() #w2Base = w2.getState() def update(): tr1 = w1.getGlobalTransform(w1Base) #tr2 = w2.getGlobalTransform(w2Base) item.setTransform(tr1) #def update2(): #tr1 = w1.getGlobalTransform(w1Base) #tr2 = w2.getGlobalTransform(w2Base) #t1.setTransform(tr1) #w1.setState(w1Base) #w1.applyGlobalTransform(tr2) w1.sigRegionChanged.connect(update) #w2.sigRegionChanged.connect(update2) from .SRTTransform import SRTTransform
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/configfile.py
.py
6,853
217
# -*- coding: utf-8 -*- """ configfile.py - Human-readable text configuration file library Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. Used for reading and writing dictionary objects to a python-like configuration file format. Data structures may be nested and contain any data type as long as it can be converted to/from a string using repr and eval. """ import re, os, sys, datetime import numpy from .pgcollections import OrderedDict from . import units from .python2_3 import asUnicode, basestring from .Qt import QtCore from .Point import Point from .colormap import ColorMap GLOBAL_PATH = None # so not thread safe. class ParseError(Exception): def __init__(self, message, lineNum, line, fileName=None): self.lineNum = lineNum self.line = line #self.message = message self.fileName = fileName Exception.__init__(self, message) def __str__(self): if self.fileName is None: msg = "Error parsing string at line %d:\n" % self.lineNum else: msg = "Error parsing config file '%s' at line %d:\n" % (self.fileName, self.lineNum) msg += "%s\n%s" % (self.line, Exception.__str__(self)) return msg def writeConfigFile(data, fname): s = genString(data) with open(fname, 'w') as fd: fd.write(s) def readConfigFile(fname): #cwd = os.getcwd() global GLOBAL_PATH if GLOBAL_PATH is not None: fname2 = os.path.join(GLOBAL_PATH, fname) if os.path.exists(fname2): fname = fname2 GLOBAL_PATH = os.path.dirname(os.path.abspath(fname)) try: #os.chdir(newDir) ## bad. with open(fname) as fd: s = asUnicode(fd.read()) s = s.replace("\r\n", "\n") s = s.replace("\r", "\n") data = parseString(s)[1] except ParseError: sys.exc_info()[1].fileName = fname raise except: print("Error while reading config file %s:"% fname) raise #finally: #os.chdir(cwd) return data def appendConfigFile(data, fname): s = genString(data) with open(fname, 'a') as fd: fd.write(s) def genString(data, indent=''): s = '' for k in data: sk = str(k) if len(sk) == 0: print(data) raise Exception('blank dict keys not allowed (see data above)') if sk[0] == ' ' or ':' in sk: print(data) raise Exception('dict keys must not contain ":" or start with spaces [offending key is "%s"]' % sk) if isinstance(data[k], dict): s += indent + sk + ':\n' s += genString(data[k], indent + ' ') else: s += indent + sk + ': ' + repr(data[k]).replace("\n", "\\\n") + '\n' return s def parseString(lines, start=0): data = OrderedDict() if isinstance(lines, basestring): lines = lines.replace("\\\n", "") lines = lines.split('\n') lines = [l for l in lines if re.search(r'\S', l) and not re.match(r'\s*#', l)] ## remove empty lines indent = measureIndent(lines[start]) ln = start - 1 try: while True: ln += 1 #print ln if ln >= len(lines): break l = lines[ln] ## Skip blank lines or lines starting with # if re.match(r'\s*#', l) or not re.search(r'\S', l): continue ## Measure line indentation, make sure it is correct for this level lineInd = measureIndent(l) if lineInd < indent: ln -= 1 break if lineInd > indent: #print lineInd, indent raise ParseError('Indentation is incorrect. Expected %d, got %d' % (indent, lineInd), ln+1, l) if ':' not in l: raise ParseError('Missing colon', ln+1, l) (k, p, v) = l.partition(':') k = k.strip() v = v.strip() ## set up local variables to use for eval local = units.allUnits.copy() local['OrderedDict'] = OrderedDict local['readConfigFile'] = readConfigFile local['Point'] = Point local['QtCore'] = QtCore local['ColorMap'] = ColorMap local['datetime'] = datetime # Needed for reconstructing numpy arrays local['array'] = numpy.array for dtype in ['int8', 'uint8', 'int16', 'uint16', 'float16', 'int32', 'uint32', 'float32', 'int64', 'uint64', 'float64']: local[dtype] = getattr(numpy, dtype) if len(k) < 1: raise ParseError('Missing name preceding colon', ln+1, l) if k[0] == '(' and k[-1] == ')': ## If the key looks like a tuple, try evaluating it. try: k1 = eval(k, local) if type(k1) is tuple: k = k1 except: pass if re.search(r'\S', v) and v[0] != '#': ## eval the value try: val = eval(v, local) except: ex = sys.exc_info()[1] raise ParseError("Error evaluating expression '%s': [%s: %s]" % (v, ex.__class__.__name__, str(ex)), (ln+1), l) else: if ln+1 >= len(lines) or measureIndent(lines[ln+1]) <= indent: #print "blank dict" val = {} else: #print "Going deeper..", ln+1 (ln, val) = parseString(lines, start=ln+1) data[k] = val #print k, repr(val) except ParseError: raise except: ex = sys.exc_info()[1] raise ParseError("%s: %s" % (ex.__class__.__name__, str(ex)), ln+1, l) #print "Returning shallower..", ln+1 return (ln, data) def measureIndent(s): n = 0 while n < len(s) and s[n] == ' ': n += 1 return n if __name__ == '__main__': import tempfile cf = """ key: 'value' key2: ##comment ##comment key21: 'value' ## comment ##comment key22: [1,2,3] key23: 234 #comment """ fn = tempfile.mktemp() with open(fn, 'w') as tf: tf.write(cf) print("=== Test:===") num = 1 for line in cf.split('\n'): print("%02d %s" % (num, line)) num += 1 print(cf) print("============") data = readConfigFile(fn) print(data) os.remove(fn)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/Vector.py
.py
2,932
87
# -*- coding: utf-8 -*- """ Vector.py - Extension of QVector3D which adds a few missing methods. Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. """ from .Qt import QtGui, QtCore, QT_LIB import numpy as np class Vector(QtGui.QVector3D): """Extension of QVector3D which adds a few helpful methods.""" def __init__(self, *args): if len(args) == 1: if isinstance(args[0], QtCore.QSizeF): QtGui.QVector3D.__init__(self, float(args[0].width()), float(args[0].height()), 0) return elif isinstance(args[0], QtCore.QPoint) or isinstance(args[0], QtCore.QPointF): QtGui.QVector3D.__init__(self, float(args[0].x()), float(args[0].y()), 0) elif hasattr(args[0], '__getitem__'): vals = list(args[0]) if len(vals) == 2: vals.append(0) if len(vals) != 3: raise Exception('Cannot init Vector with sequence of length %d' % len(args[0])) QtGui.QVector3D.__init__(self, *vals) return elif len(args) == 2: QtGui.QVector3D.__init__(self, args[0], args[1], 0) return QtGui.QVector3D.__init__(self, *args) def __len__(self): return 3 def __add__(self, b): # workaround for pyside bug. see https://bugs.launchpad.net/pyqtgraph/+bug/1223173 if QT_LIB == 'PySide' and isinstance(b, QtGui.QVector3D): b = Vector(b) return QtGui.QVector3D.__add__(self, b) #def __reduce__(self): #return (Point, (self.x(), self.y())) def __getitem__(self, i): if i == 0: return self.x() elif i == 1: return self.y() elif i == 2: return self.z() else: raise IndexError("Point has no index %s" % str(i)) def __setitem__(self, i, x): if i == 0: return self.setX(x) elif i == 1: return self.setY(x) elif i == 2: return self.setZ(x) else: raise IndexError("Point has no index %s" % str(i)) def __iter__(self): yield(self.x()) yield(self.y()) yield(self.z()) def angle(self, a): """Returns the angle in degrees between this vector and the vector a.""" n1 = self.length() n2 = a.length() if n1 == 0. or n2 == 0.: return None ## Probably this should be done with arctan2 instead.. ang = np.arccos(np.clip(QtGui.QVector3D.dotProduct(self, a) / (n1 * n2), -1.0, 1.0)) ### in radians # c = self.crossProduct(a) # if c > 0: # ang *= -1. return ang * 180. / np.pi def __abs__(self): return Vector(abs(self.x()), abs(self.y()), abs(self.z()))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/reload.py
.py
19,304
572
# -*- coding: utf-8 -*- """ Magic Reload Library Luke Campagnola 2010 Python reload function that actually works (the way you expect it to) - No re-importing necessary - Modules can be reloaded in any order - Replaces functions and methods with their updated code - Changes instances to use updated classes - Automatically decides which modules to update by comparing file modification times Does NOT: - re-initialize exting instances, even if __init__ changes - update references to any module-level objects ie, this does not reload correctly: from module import someObject print someObject ..but you can use this instead: (this works even for the builtin reload) import module print module.someObject """ from __future__ import print_function import inspect, os, sys, gc, traceback, types from .debug import printExc try: from importlib import reload as orig_reload except ImportError: orig_reload = reload py3 = sys.version_info >= (3,) def reloadAll(prefix=None, debug=False): """Automatically reload everything whose __file__ begins with prefix. - Skips reload if the file has not been updated (if .pyc is newer than .py) - if prefix is None, checks all loaded modules """ failed = [] changed = [] for modName, mod in list(sys.modules.items()): ## don't use iteritems; size may change during reload if not inspect.ismodule(mod): continue if modName == '__main__': continue ## Ignore if the file name does not start with prefix if not hasattr(mod, '__file__') or mod.__file__ is None or os.path.splitext(mod.__file__)[1] not in ['.py', '.pyc']: continue if prefix is not None and mod.__file__[:len(prefix)] != prefix: continue ## ignore if the .pyc is newer than the .py (or if there is no pyc or py) py = os.path.splitext(mod.__file__)[0] + '.py' pyc = py + 'c' if py not in changed and os.path.isfile(pyc) and os.path.isfile(py) and os.stat(pyc).st_mtime >= os.stat(py).st_mtime: #if debug: #print "Ignoring module %s; unchanged" % str(mod) continue changed.append(py) ## keep track of which modules have changed to insure that duplicate-import modules get reloaded. try: reload(mod, debug=debug) except: printExc("Error while reloading module %s, skipping\n" % mod) failed.append(mod.__name__) if len(failed) > 0: raise Exception("Some modules failed to reload: %s" % ', '.join(failed)) def reload(module, debug=False, lists=False, dicts=False): """Replacement for the builtin reload function: - Reloads the module as usual - Updates all old functions and class methods to use the new code - Updates all instances of each modified class to use the new class - Can update lists and dicts, but this is disabled by default - Requires that class and function names have not changed """ if debug: print("Reloading %s" % str(module)) ## make a copy of the old module dictionary, reload, then grab the new module dictionary for comparison oldDict = module.__dict__.copy() orig_reload(module) newDict = module.__dict__ ## Allow modules access to the old dictionary after they reload if hasattr(module, '__reload__'): module.__reload__(oldDict) ## compare old and new elements from each dict; update where appropriate for k in oldDict: old = oldDict[k] new = newDict.get(k, None) if old is new or new is None: continue if inspect.isclass(old): if debug: print(" Updating class %s.%s (0x%x -> 0x%x)" % (module.__name__, k, id(old), id(new))) updateClass(old, new, debug) # don't put this inside updateClass because it is reentrant. new.__previous_reload_version__ = old elif inspect.isfunction(old): depth = updateFunction(old, new, debug) if debug: extra = "" if depth > 0: extra = " (and %d previous versions)" % depth print(" Updating function %s.%s%s" % (module.__name__, k, extra)) elif lists and isinstance(old, list): l = old.len() old.extend(new) for i in range(l): old.pop(0) elif dicts and isinstance(old, dict): old.update(new) for k in old: if k not in new: del old[k] ## For functions: ## 1) update the code and defaults to new versions. ## 2) keep a reference to the previous version so ALL versions get updated for every reload def updateFunction(old, new, debug, depth=0, visited=None): #if debug and depth > 0: #print " -> also updating previous version", old, " -> ", new old.__code__ = new.__code__ old.__defaults__ = new.__defaults__ if hasattr(old, '__kwdefaults'): old.__kwdefaults__ = new.__kwdefaults__ old.__doc__ = new.__doc__ if visited is None: visited = [] if old in visited: return visited.append(old) ## finally, update any previous versions still hanging around.. if hasattr(old, '__previous_reload_version__'): maxDepth = updateFunction(old.__previous_reload_version__, new, debug, depth=depth+1, visited=visited) else: maxDepth = depth ## We need to keep a pointer to the previous version so we remember to update BOTH ## when the next reload comes around. if depth == 0: new.__previous_reload_version__ = old return maxDepth ## For classes: ## 1) find all instances of the old class and set instance.__class__ to the new class ## 2) update all old class methods to use code from the new class methods def updateClass(old, new, debug): ## Track town all instances and subclasses of old refs = gc.get_referrers(old) for ref in refs: try: if isinstance(ref, old) and ref.__class__ is old: ref.__class__ = new if debug: print(" Changed class for %s" % safeStr(ref)) elif inspect.isclass(ref) and issubclass(ref, old) and old in ref.__bases__: ind = ref.__bases__.index(old) ## Does not work: #ref.__bases__ = ref.__bases__[:ind] + (new,) + ref.__bases__[ind+1:] ## reason: Even though we change the code on methods, they remain bound ## to their old classes (changing im_class is not allowed). Instead, ## we have to update the __bases__ such that this class will be allowed ## as an argument to older methods. ## This seems to work. Is there any reason not to? ## Note that every time we reload, the class hierarchy becomes more complex. ## (and I presume this may slow things down?) newBases = ref.__bases__[:ind] + (new,old) + ref.__bases__[ind+1:] try: ref.__bases__ = newBases except TypeError: print(" Error setting bases for class %s" % ref) print(" old bases: %s" % repr(ref.__bases__)) print(" new bases: %s" % repr(newBases)) raise if debug: print(" Changed superclass for %s" % safeStr(ref)) #else: #if debug: #print " Ignoring reference", type(ref) except Exception: print("Error updating reference (%s) for class change (%s -> %s)" % (safeStr(ref), safeStr(old), safeStr(new))) raise ## update all class methods to use new code. ## Generally this is not needed since instances already know about the new class, ## but it fixes a few specific cases (pyqt signals, for one) for attr in dir(old): oa = getattr(old, attr) if (py3 and inspect.isfunction(oa)) or inspect.ismethod(oa): # note python2 has unbound methods, whereas python3 just uses plain functions try: na = getattr(new, attr) except AttributeError: if debug: print(" Skipping method update for %s; new class does not have this attribute" % attr) continue ofunc = getattr(oa, '__func__', oa) # in py2 we have to get the __func__ from unbound method, nfunc = getattr(na, '__func__', na) # in py3 the attribute IS the function if ofunc is not nfunc: depth = updateFunction(ofunc, nfunc, debug) if not hasattr(nfunc, '__previous_reload_method__'): nfunc.__previous_reload_method__ = oa # important for managing signal connection #oa.__class__ = new ## bind old method to new class ## not allowed if debug: extra = "" if depth > 0: extra = " (and %d previous versions)" % depth print(" Updating method %s%s" % (attr, extra)) ## And copy in new functions that didn't exist previously for attr in dir(new): if attr == '__previous_reload_version__': continue if not hasattr(old, attr): if debug: print(" Adding missing attribute %s" % attr) setattr(old, attr, getattr(new, attr)) ## finally, update any previous versions still hanging around.. if hasattr(old, '__previous_reload_version__'): updateClass(old.__previous_reload_version__, new, debug) ## It is possible to build classes for which str(obj) just causes an exception. ## Avoid thusly: def safeStr(obj): try: s = str(obj) except Exception: try: s = repr(obj) except Exception: s = "<instance of %s at 0x%x>" % (safeStr(type(obj)), id(obj)) return s def getPreviousVersion(obj): """Return the previous version of *obj*, or None if this object has not been reloaded. """ if isinstance(obj, type) or inspect.isfunction(obj): return getattr(obj, '__previous_reload_version__', None) elif inspect.ismethod(obj): if obj.__self__ is None: # unbound method return getattr(obj.__func__, '__previous_reload_method__', None) else: oldmethod = getattr(obj.__func__, '__previous_reload_method__', None) if oldmethod is None: return None self = obj.__self__ oldfunc = getattr(oldmethod, '__func__', oldmethod) if hasattr(oldmethod, 'im_class'): # python 2 cls = oldmethod.im_class return types.MethodType(oldfunc, self, cls) else: # python 3 return types.MethodType(oldfunc, self) ## Tests: # write modules to disk, import, then re-write and run again if __name__ == '__main__': doQtTest = True try: from PyQt4 import QtCore if not hasattr(QtCore, 'Signal'): QtCore.Signal = QtCore.pyqtSignal #app = QtGui.QApplication([]) class Btn(QtCore.QObject): sig = QtCore.Signal() def emit(self): self.sig.emit() btn = Btn() except: raise print("Error; skipping Qt tests") doQtTest = False import os if not os.path.isdir('test1'): os.mkdir('test1') with open('test1/__init__.py', 'w'): pass modFile1 = "test1/test1.py" modCode1 = """ import sys class A(object): def __init__(self, msg): object.__init__(self) self.msg = msg def fn(self, pfx = ""): print(pfx+"A class: %%s %%s" %% (str(self.__class__), str(id(self.__class__)))) print(pfx+" %%s: %d" %% self.msg) class B(A): def fn(self, pfx=""): print(pfx+"B class:", self.__class__, id(self.__class__)) print(pfx+" %%s: %d" %% self.msg) print(pfx+" calling superclass.. (%%s)" %% id(A) ) A.fn(self, " ") """ modFile2 = "test2.py" modCode2 = """ from test1.test1 import A from test1.test1 import B a1 = A("ax1") b1 = B("bx1") class C(A): def __init__(self, msg): #print "| C init:" #print "| C.__bases__ = ", map(id, C.__bases__) #print "| A:", id(A) #print "| A.__init__ = ", id(A.__init__.im_func), id(A.__init__.im_func.__code__), id(A.__init__.im_class) A.__init__(self, msg + "(init from C)") def fn(): print("fn: %s") """ with open(modFile1, 'w') as f: f.write(modCode1 % (1, 1)) with open(modFile2, 'w') as f: f.write(modCode2 % ("message 1", )) import test1.test1 as test1 import test2 print("Test 1 originals:") A1 = test1.A B1 = test1.B a1 = test1.A("a1") b1 = test1.B("b1") a1.fn() b1.fn() #print "function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.im_func), id(a1.fn.im_class), id(b1.fn.im_func), id(b1.fn.im_class)) from test2 import fn, C if doQtTest: print("Button test before:") btn.sig.connect(fn) btn.sig.connect(a1.fn) btn.emit() #btn.sig.emit() print("") #print "a1.fn referrers:", sys.getrefcount(a1.fn.im_func), gc.get_referrers(a1.fn.im_func) print("Test2 before reload:") fn() oldfn = fn test2.a1.fn() test2.b1.fn() c1 = test2.C('c1') c1.fn() os.remove(modFile1+'c') with open(modFile1, 'w') as f: f.write(modCode1 %(2, 2)) print("\n----RELOAD test1-----\n") reloadAll(os.path.abspath(__file__)[:10], debug=True) print("Subclass test:") c2 = test2.C('c2') c2.fn() os.remove(modFile2+'c') with open(modFile2, 'w') as f: f.write(modCode2 % ("message 2", )) print("\n----RELOAD test2-----\n") reloadAll(os.path.abspath(__file__)[:10], debug=True) if doQtTest: print("Button test after:") btn.emit() #btn.sig.emit() #print "a1.fn referrers:", sys.getrefcount(a1.fn.im_func), gc.get_referrers(a1.fn.im_func) print("Test2 after reload:") fn() test2.a1.fn() test2.b1.fn() print("\n==> Test 1 Old instances:") a1.fn() b1.fn() c1.fn() #print "function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.im_func), id(a1.fn.im_class), id(b1.fn.im_func), id(b1.fn.im_class)) print("\n==> Test 1 New instances:") a2 = test1.A("a2") b2 = test1.B("b2") a2.fn() b2.fn() c2 = test2.C('c2') c2.fn() #print "function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.im_func), id(a1.fn.im_class), id(b1.fn.im_func), id(b1.fn.im_class)) os.remove(modFile1+'c') os.remove(modFile2+'c') with open(modFile1, 'w') as f: f.write(modCode1 % (3, 3)) with open(modFile2, 'w') as f: f.write(modCode2 % ("message 3", )) print("\n----RELOAD-----\n") reloadAll(os.path.abspath(__file__)[:10], debug=True) if doQtTest: print("Button test after:") btn.emit() #btn.sig.emit() #print "a1.fn referrers:", sys.getrefcount(a1.fn.im_func), gc.get_referrers(a1.fn.im_func) print("Test2 after reload:") fn() test2.a1.fn() test2.b1.fn() print("\n==> Test 1 Old instances:") a1.fn() b1.fn() print("function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.__func__), id(a1.fn.__self__.__class__), id(b1.fn.__func__), id(b1.fn.__self__.__class__))) print("\n==> Test 1 New instances:") a2 = test1.A("a2") b2 = test1.B("b2") a2.fn() b2.fn() print("function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.__func__), id(a1.fn.__self__.__class__), id(b1.fn.__func__), id(b1.fn.__self__.__class__))) os.remove(modFile1) os.remove(modFile2) os.remove(modFile1+'c') os.remove(modFile2+'c') os.system('rm -r test1') # # Failure graveyard ahead: # """Reload Importer: Hooks into import system to 1) keep a record of module dependencies as they are imported 2) make sure modules are always reloaded in correct order 3) update old classes and functions to use reloaded code""" #import imp, sys ## python's import hook mechanism doesn't work since we need to be ## informed every time there is an import statement, not just for new imports #class ReloadImporter: #def __init__(self): #self.depth = 0 #def find_module(self, name, path): #print " "*self.depth + "find: ", name, path ##if name == 'PyQt4' and path is None: ##print "PyQt4 -> PySide" ##self.modData = imp.find_module('PySide') ##return self ##return None ## return none to allow the import to proceed normally; return self to intercept with load_module #self.modData = imp.find_module(name, path) #self.depth += 1 ##sys.path_importer_cache = {} #return self #def load_module(self, name): #mod = imp.load_module(name, *self.modData) #self.depth -= 1 #print " "*self.depth + "load: ", name #return mod #def pathHook(path): #print "path hook:", path #raise ImportError #sys.path_hooks.append(pathHook) #sys.meta_path.append(ReloadImporter()) ### replace __import__ with a wrapper that tracks module dependencies #modDeps = {} #reloadModule = None #origImport = __builtins__.__import__ #def _import(name, globals=None, locals=None, fromlist=None, level=-1, stack=[]): ### Note that stack behaves as a static variable. ##print " "*len(importStack) + "import %s" % args[0] #stack.append(set()) #mod = origImport(name, globals, locals, fromlist, level) #deps = stack.pop() #if len(stack) > 0: #stack[-1].add(mod) #elif reloadModule is not None: ## If this is the top level import AND we're inside a module reload #modDeps[reloadModule].add(mod) #if mod in modDeps: #modDeps[mod] |= deps #else: #modDeps[mod] = deps #return mod #__builtins__.__import__ = _import ### replace #origReload = __builtins__.reload #def _reload(mod): #reloadModule = mod #ret = origReload(mod) #reloadModule = None #return ret #__builtins__.reload = _reload #def reload(mod, visited=None): #if visited is None: #visited = set() #if mod in visited: #return #visited.add(mod) #for dep in modDeps.get(mod, []): #reload(dep, visited) #__builtins__.reload(mod)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/ThreadsafeTimer.py
.py
1,551
41
from .Qt import QtCore, QtGui class ThreadsafeTimer(QtCore.QObject): """ Thread-safe replacement for QTimer. """ timeout = QtCore.Signal() sigTimerStopRequested = QtCore.Signal() sigTimerStartRequested = QtCore.Signal(object) def __init__(self): QtCore.QObject.__init__(self) self.timer = QtCore.QTimer() self.timer.timeout.connect(self.timerFinished) self.timer.moveToThread(QtCore.QCoreApplication.instance().thread()) self.moveToThread(QtCore.QCoreApplication.instance().thread()) self.sigTimerStopRequested.connect(self.stop, QtCore.Qt.QueuedConnection) self.sigTimerStartRequested.connect(self.start, QtCore.Qt.QueuedConnection) def start(self, timeout): isGuiThread = QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread() if isGuiThread: #print "start timer", self, "from gui thread" self.timer.start(timeout) else: #print "start timer", self, "from remote thread" self.sigTimerStartRequested.emit(timeout) def stop(self): isGuiThread = QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread() if isGuiThread: #print "stop timer", self, "from gui thread" self.timer.stop() else: #print "stop timer", self, "from remote thread" self.sigTimerStopRequested.emit() def timerFinished(self): self.timeout.emit()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/frozenSupport.py
.py
1,830
52
## Definitions helpful in frozen environments (eg py2exe) import os, sys, zipfile def listdir(path): """Replacement for os.listdir that works in frozen environments.""" if not hasattr(sys, 'frozen'): return os.listdir(path) (zipPath, archivePath) = splitZip(path) if archivePath is None: return os.listdir(path) with zipfile.ZipFile(zipPath, "r") as zipobj: contents = zipobj.namelist() results = set() for name in contents: # components in zip archive paths are always separated by forward slash if name.startswith(archivePath) and len(name) > len(archivePath): name = name[len(archivePath):].split('/')[0] results.add(name) return list(results) def isdir(path): """Replacement for os.path.isdir that works in frozen environments.""" if not hasattr(sys, 'frozen'): return os.path.isdir(path) (zipPath, archivePath) = splitZip(path) if archivePath is None: return os.path.isdir(path) with zipfile.ZipFile(zipPath, "r") as zipobj: contents = zipobj.namelist() archivePath = archivePath.rstrip('/') + '/' ## make sure there's exactly one '/' at the end for c in contents: if c.startswith(archivePath): return True return False def splitZip(path): """Splits a path containing a zip file into (zipfile, subpath). If there is no zip file, returns (path, None)""" components = os.path.normpath(path).split(os.sep) for index, component in enumerate(components): if component.endswith('.zip'): zipPath = os.sep.join(components[0:index+1]) archivePath = ''.join([x+'/' for x in components[index+1:]]) return (zipPath, archivePath) else: return (path, None)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/SignalProxy.py
.py
3,854
119
# -*- coding: utf-8 -*- from .Qt import QtCore from .ptime import time from . import ThreadsafeTimer import weakref __all__ = ['SignalProxy'] class SignalProxy(QtCore.QObject): """Object which collects rapid-fire signals and condenses them into a single signal or a rate-limited stream of signals. Used, for example, to prevent a SpinBox from generating multiple signals when the mouse wheel is rolled over it. Emits sigDelayed after input signals have stopped for a certain period of time. """ sigDelayed = QtCore.Signal(object) def __init__(self, signal, delay=0.3, rateLimit=0, slot=None): """Initialization arguments: signal - a bound Signal or pyqtSignal instance delay - Time (in seconds) to wait for signals to stop before emitting (default 0.3s) slot - Optional function to connect sigDelayed to. rateLimit - (signals/sec) if greater than 0, this allows signals to stream out at a steady rate while they are being received. """ QtCore.QObject.__init__(self) signal.connect(self.signalReceived) self.signal = signal self.delay = delay self.rateLimit = rateLimit self.args = None self.timer = ThreadsafeTimer.ThreadsafeTimer() self.timer.timeout.connect(self.flush) self.block = False self.slot = weakref.ref(slot) self.lastFlushTime = None if slot is not None: self.sigDelayed.connect(slot) def setDelay(self, delay): self.delay = delay def signalReceived(self, *args): """Received signal. Cancel previous timer and store args to be forwarded later.""" if self.block: return self.args = args if self.rateLimit == 0: self.timer.stop() self.timer.start((self.delay*1000)+1) else: now = time() if self.lastFlushTime is None: leakTime = 0 else: lastFlush = self.lastFlushTime leakTime = max(0, (lastFlush + (1.0 / self.rateLimit)) - now) self.timer.stop() self.timer.start((min(leakTime, self.delay)*1000)+1) def flush(self): """If there is a signal queued up, send it now.""" if self.args is None or self.block: return False args, self.args = self.args, None self.timer.stop() self.lastFlushTime = time() #self.emit(self.signal, *self.args) self.sigDelayed.emit(args) return True def disconnect(self): self.block = True try: self.signal.disconnect(self.signalReceived) except: pass try: self.sigDelayed.disconnect(self.slot) except: pass #def proxyConnect(source, signal, slot, delay=0.3): #"""Connect a signal to a slot with delay. Returns the SignalProxy #object that was created. Be sure to store this object so it is not #garbage-collected immediately.""" #sp = SignalProxy(source, signal, delay) #if source is None: #sp.connect(sp, QtCore.SIGNAL('signal'), slot) #else: #sp.connect(sp, signal, slot) #return sp if __name__ == '__main__': from .Qt import QtGui app = QtGui.QApplication([]) win = QtGui.QMainWindow() spin = QtGui.QSpinBox() win.setCentralWidget(spin) win.show() def fn(*args): print("Raw signal:", args) def fn2(*args): print("Delayed signal:", args) spin.valueChanged.connect(fn) #proxy = proxyConnect(spin, QtCore.SIGNAL('valueChanged(int)'), fn) proxy = SignalProxy(spin.valueChanged, delay=0.5, slot=fn2)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/console/template_pyqt5.py
.py
6,230
115
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyqtgraph/console/template.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(739, 497) self.gridLayout = QtWidgets.QGridLayout(Form) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setSpacing(0) self.gridLayout.setObjectName("gridLayout") self.splitter = QtWidgets.QSplitter(Form) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName("splitter") self.layoutWidget = QtWidgets.QWidget(self.splitter) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget) self.verticalLayout.setObjectName("verticalLayout") self.output = QtWidgets.QPlainTextEdit(self.layoutWidget) font = QtGui.QFont() font.setFamily("Monospace") self.output.setFont(font) self.output.setReadOnly(True) self.output.setObjectName("output") self.verticalLayout.addWidget(self.output) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.input = CmdInput(self.layoutWidget) self.input.setObjectName("input") self.horizontalLayout.addWidget(self.input) self.historyBtn = QtWidgets.QPushButton(self.layoutWidget) self.historyBtn.setCheckable(True) self.historyBtn.setObjectName("historyBtn") self.horizontalLayout.addWidget(self.historyBtn) self.exceptionBtn = QtWidgets.QPushButton(self.layoutWidget) self.exceptionBtn.setCheckable(True) self.exceptionBtn.setObjectName("exceptionBtn") self.horizontalLayout.addWidget(self.exceptionBtn) self.verticalLayout.addLayout(self.horizontalLayout) self.historyList = QtWidgets.QListWidget(self.splitter) font = QtGui.QFont() font.setFamily("Monospace") self.historyList.setFont(font) self.historyList.setObjectName("historyList") self.exceptionGroup = QtWidgets.QGroupBox(self.splitter) self.exceptionGroup.setObjectName("exceptionGroup") self.gridLayout_2 = QtWidgets.QGridLayout(self.exceptionGroup) self.gridLayout_2.setContentsMargins(-1, 0, -1, 0) self.gridLayout_2.setHorizontalSpacing(2) self.gridLayout_2.setVerticalSpacing(0) self.gridLayout_2.setObjectName("gridLayout_2") self.clearExceptionBtn = QtWidgets.QPushButton(self.exceptionGroup) self.clearExceptionBtn.setEnabled(False) self.clearExceptionBtn.setObjectName("clearExceptionBtn") self.gridLayout_2.addWidget(self.clearExceptionBtn, 0, 6, 1, 1) self.catchAllExceptionsBtn = QtWidgets.QPushButton(self.exceptionGroup) self.catchAllExceptionsBtn.setCheckable(True) self.catchAllExceptionsBtn.setObjectName("catchAllExceptionsBtn") self.gridLayout_2.addWidget(self.catchAllExceptionsBtn, 0, 1, 1, 1) self.catchNextExceptionBtn = QtWidgets.QPushButton(self.exceptionGroup) self.catchNextExceptionBtn.setCheckable(True) self.catchNextExceptionBtn.setObjectName("catchNextExceptionBtn") self.gridLayout_2.addWidget(self.catchNextExceptionBtn, 0, 0, 1, 1) self.onlyUncaughtCheck = QtWidgets.QCheckBox(self.exceptionGroup) self.onlyUncaughtCheck.setChecked(True) self.onlyUncaughtCheck.setObjectName("onlyUncaughtCheck") self.gridLayout_2.addWidget(self.onlyUncaughtCheck, 0, 4, 1, 1) self.exceptionStackList = QtWidgets.QListWidget(self.exceptionGroup) self.exceptionStackList.setAlternatingRowColors(True) self.exceptionStackList.setObjectName("exceptionStackList") self.gridLayout_2.addWidget(self.exceptionStackList, 2, 0, 1, 7) self.runSelectedFrameCheck = QtWidgets.QCheckBox(self.exceptionGroup) self.runSelectedFrameCheck.setChecked(True) self.runSelectedFrameCheck.setObjectName("runSelectedFrameCheck") self.gridLayout_2.addWidget(self.runSelectedFrameCheck, 3, 0, 1, 7) self.exceptionInfoLabel = QtWidgets.QLabel(self.exceptionGroup) self.exceptionInfoLabel.setWordWrap(True) self.exceptionInfoLabel.setObjectName("exceptionInfoLabel") self.gridLayout_2.addWidget(self.exceptionInfoLabel, 1, 0, 1, 7) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 5, 1, 1) self.label = QtWidgets.QLabel(self.exceptionGroup) self.label.setObjectName("label") self.gridLayout_2.addWidget(self.label, 0, 2, 1, 1) self.filterText = QtWidgets.QLineEdit(self.exceptionGroup) self.filterText.setObjectName("filterText") self.gridLayout_2.addWidget(self.filterText, 0, 3, 1, 1) self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Console")) self.historyBtn.setText(_translate("Form", "History..")) self.exceptionBtn.setText(_translate("Form", "Exceptions..")) self.exceptionGroup.setTitle(_translate("Form", "Exception Handling")) self.clearExceptionBtn.setText(_translate("Form", "Clear Stack")) self.catchAllExceptionsBtn.setText(_translate("Form", "Show All Exceptions")) self.catchNextExceptionBtn.setText(_translate("Form", "Show Next Exception")) self.onlyUncaughtCheck.setText(_translate("Form", "Only Uncaught Exceptions")) self.runSelectedFrameCheck.setText(_translate("Form", "Run commands in selected stack frame")) self.exceptionInfoLabel.setText(_translate("Form", "Stack Trace")) self.label.setText(_translate("Form", "Filter (regex):")) from .CmdInput import CmdInput
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/console/template_pyside2.py
.py
6,517
114
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'template.ui' # # Created: Sun Sep 18 19:19:10 2016 # by: pyside2-uic running on PySide2 2.0.0~alpha0 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(694, 497) self.gridLayout = QtWidgets.QGridLayout(Form) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setSpacing(0) self.gridLayout.setObjectName("gridLayout") self.splitter = QtWidgets.QSplitter(Form) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName("splitter") self.layoutWidget = QtWidgets.QWidget(self.splitter) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.output = QtWidgets.QPlainTextEdit(self.layoutWidget) font = QtGui.QFont() font.setFamily("Monospace") self.output.setFont(font) self.output.setReadOnly(True) self.output.setObjectName("output") self.verticalLayout.addWidget(self.output) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.input = CmdInput(self.layoutWidget) self.input.setObjectName("input") self.horizontalLayout.addWidget(self.input) self.historyBtn = QtWidgets.QPushButton(self.layoutWidget) self.historyBtn.setCheckable(True) self.historyBtn.setObjectName("historyBtn") self.horizontalLayout.addWidget(self.historyBtn) self.exceptionBtn = QtWidgets.QPushButton(self.layoutWidget) self.exceptionBtn.setCheckable(True) self.exceptionBtn.setObjectName("exceptionBtn") self.horizontalLayout.addWidget(self.exceptionBtn) self.verticalLayout.addLayout(self.horizontalLayout) self.historyList = QtWidgets.QListWidget(self.splitter) font = QtGui.QFont() font.setFamily("Monospace") self.historyList.setFont(font) self.historyList.setObjectName("historyList") self.exceptionGroup = QtWidgets.QGroupBox(self.splitter) self.exceptionGroup.setObjectName("exceptionGroup") self.gridLayout_2 = QtWidgets.QGridLayout(self.exceptionGroup) self.gridLayout_2.setSpacing(0) self.gridLayout_2.setContentsMargins(-1, 0, -1, 0) self.gridLayout_2.setObjectName("gridLayout_2") self.clearExceptionBtn = QtWidgets.QPushButton(self.exceptionGroup) self.clearExceptionBtn.setEnabled(False) self.clearExceptionBtn.setObjectName("clearExceptionBtn") self.gridLayout_2.addWidget(self.clearExceptionBtn, 0, 6, 1, 1) self.catchAllExceptionsBtn = QtWidgets.QPushButton(self.exceptionGroup) self.catchAllExceptionsBtn.setCheckable(True) self.catchAllExceptionsBtn.setObjectName("catchAllExceptionsBtn") self.gridLayout_2.addWidget(self.catchAllExceptionsBtn, 0, 1, 1, 1) self.catchNextExceptionBtn = QtWidgets.QPushButton(self.exceptionGroup) self.catchNextExceptionBtn.setCheckable(True) self.catchNextExceptionBtn.setObjectName("catchNextExceptionBtn") self.gridLayout_2.addWidget(self.catchNextExceptionBtn, 0, 0, 1, 1) self.onlyUncaughtCheck = QtWidgets.QCheckBox(self.exceptionGroup) self.onlyUncaughtCheck.setChecked(True) self.onlyUncaughtCheck.setObjectName("onlyUncaughtCheck") self.gridLayout_2.addWidget(self.onlyUncaughtCheck, 0, 4, 1, 1) self.exceptionStackList = QtWidgets.QListWidget(self.exceptionGroup) self.exceptionStackList.setAlternatingRowColors(True) self.exceptionStackList.setObjectName("exceptionStackList") self.gridLayout_2.addWidget(self.exceptionStackList, 2, 0, 1, 7) self.runSelectedFrameCheck = QtWidgets.QCheckBox(self.exceptionGroup) self.runSelectedFrameCheck.setChecked(True) self.runSelectedFrameCheck.setObjectName("runSelectedFrameCheck") self.gridLayout_2.addWidget(self.runSelectedFrameCheck, 3, 0, 1, 7) self.exceptionInfoLabel = QtWidgets.QLabel(self.exceptionGroup) self.exceptionInfoLabel.setObjectName("exceptionInfoLabel") self.gridLayout_2.addWidget(self.exceptionInfoLabel, 1, 0, 1, 7) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 5, 1, 1) self.label = QtWidgets.QLabel(self.exceptionGroup) self.label.setObjectName("label") self.gridLayout_2.addWidget(self.label, 0, 2, 1, 1) self.filterText = QtWidgets.QLineEdit(self.exceptionGroup) self.filterText.setObjectName("filterText") self.gridLayout_2.addWidget(self.filterText, 0, 3, 1, 1) self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(QtWidgets.QApplication.translate("Form", "Console", None, -1)) self.historyBtn.setText(QtWidgets.QApplication.translate("Form", "History..", None, -1)) self.exceptionBtn.setText(QtWidgets.QApplication.translate("Form", "Exceptions..", None, -1)) self.exceptionGroup.setTitle(QtWidgets.QApplication.translate("Form", "Exception Handling", None, -1)) self.clearExceptionBtn.setText(QtWidgets.QApplication.translate("Form", "Clear Exception", None, -1)) self.catchAllExceptionsBtn.setText(QtWidgets.QApplication.translate("Form", "Show All Exceptions", None, -1)) self.catchNextExceptionBtn.setText(QtWidgets.QApplication.translate("Form", "Show Next Exception", None, -1)) self.onlyUncaughtCheck.setText(QtWidgets.QApplication.translate("Form", "Only Uncaught Exceptions", None, -1)) self.runSelectedFrameCheck.setText(QtWidgets.QApplication.translate("Form", "Run commands in selected stack frame", None, -1)) self.exceptionInfoLabel.setText(QtWidgets.QApplication.translate("Form", "Exception Info", None, -1)) self.label.setText(QtWidgets.QApplication.translate("Form", "Filter (regex):", None, -1)) from .CmdInput import CmdInput
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/console/__init__.py
.py
34
1
from .Console import ConsoleWidget
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/console/Console.py
.py
19,438
484
# -*- coding: utf-8 -*- import sys, re, os, time, traceback, subprocess import pickle from ..Qt import QtCore, QtGui, QT_LIB from ..python2_3 import basestring from .. import exceptionHandling as exceptionHandling from .. import getConfigOption from ..functions import SignalBlock if QT_LIB == 'PySide': from . import template_pyside as template elif QT_LIB == 'PySide2': from . import template_pyside2 as template elif QT_LIB == 'PyQt5': from . import template_pyqt5 as template else: from . import template_pyqt as template class ConsoleWidget(QtGui.QWidget): """ Widget displaying console output and accepting command input. Implements: - eval python expressions / exec python statements - storable history of commands - exception handling allowing commands to be interpreted in the context of any level in the exception stack frame Why not just use python in an interactive shell (or ipython) ? There are a few reasons: - pyside does not yet allow Qt event processing and interactive shell at the same time - on some systems, typing in the console _blocks_ the qt event loop until the user presses enter. This can be baffling and frustrating to users since it would appear the program has frozen. - some terminals (eg windows cmd.exe) have notoriously unfriendly interfaces - ability to add extra features like exception stack introspection - ability to have multiple interactive prompts, including for spawned sub-processes """ _threadException = QtCore.Signal(object) def __init__(self, parent=None, namespace=None, historyFile=None, text=None, editor=None): """ ============== ============================================================================ **Arguments:** namespace dictionary containing the initial variables present in the default namespace historyFile optional file for storing command history text initial text to display in the console window editor optional string for invoking code editor (called when stack trace entries are double-clicked). May contain {fileName} and {lineNum} format keys. Example:: editorCommand --loadfile {fileName} --gotoline {lineNum} ============== ============================================================================= """ QtGui.QWidget.__init__(self, parent) if namespace is None: namespace = {} namespace['__console__'] = self self.localNamespace = namespace self.editor = editor self.multiline = None self.inCmd = False self.frames = [] # stack frames to access when an item in the stack list is selected self.ui = template.Ui_Form() self.ui.setupUi(self) self.output = self.ui.output self.input = self.ui.input self.input.setFocus() if text is not None: self.output.setPlainText(text) self.historyFile = historyFile history = self.loadHistory() if history is not None: self.input.history = [""] + history self.ui.historyList.addItems(history[::-1]) self.ui.historyList.hide() self.ui.exceptionGroup.hide() self.input.sigExecuteCmd.connect(self.runCmd) self.ui.historyBtn.toggled.connect(self.ui.historyList.setVisible) self.ui.historyList.itemClicked.connect(self.cmdSelected) self.ui.historyList.itemDoubleClicked.connect(self.cmdDblClicked) self.ui.exceptionBtn.toggled.connect(self.ui.exceptionGroup.setVisible) self.ui.catchAllExceptionsBtn.toggled.connect(self.catchAllExceptions) self.ui.catchNextExceptionBtn.toggled.connect(self.catchNextException) self.ui.clearExceptionBtn.clicked.connect(self.clearExceptionClicked) self.ui.exceptionStackList.itemClicked.connect(self.stackItemClicked) self.ui.exceptionStackList.itemDoubleClicked.connect(self.stackItemDblClicked) self.ui.onlyUncaughtCheck.toggled.connect(self.updateSysTrace) self.currentTraceback = None # send exceptions raised in non-gui threads back to the main thread by signal. self._threadException.connect(self._threadExceptionHandler) def loadHistory(self): """Return the list of previously-invoked command strings (or None).""" if self.historyFile is not None: with open(self.historyFile, 'rb') as pf: return pickle.load(pf) def saveHistory(self, history): """Store the list of previously-invoked command strings.""" if self.historyFile is not None: with open(self.historyFile, 'wb') as pf: pickle.dump(pf, history) def runCmd(self, cmd): self.stdout = sys.stdout self.stderr = sys.stderr encCmd = re.sub(r'>', '&gt;', re.sub(r'<', '&lt;', cmd)) encCmd = re.sub(r' ', '&nbsp;', encCmd) self.ui.historyList.addItem(cmd) self.saveHistory(self.input.history[1:100]) try: sys.stdout = self sys.stderr = self if self.multiline is not None: self.write("<br><b>%s</b>\n"%encCmd, html=True, scrollToBottom=True) self.execMulti(cmd) else: self.write("<br><div style='background-color: #CCF; color: black'><b>%s</b>\n"%encCmd, html=True, scrollToBottom=True) self.inCmd = True self.execSingle(cmd) if not self.inCmd: self.write("</div>\n", html=True, scrollToBottom=True) finally: sys.stdout = self.stdout sys.stderr = self.stderr sb = self.ui.historyList.verticalScrollBar() sb.setValue(sb.maximum()) def globals(self): frame = self.currentFrame() if frame is not None and self.ui.runSelectedFrameCheck.isChecked(): return self.currentFrame().f_globals else: return self.localNamespace def locals(self): frame = self.currentFrame() if frame is not None and self.ui.runSelectedFrameCheck.isChecked(): return self.currentFrame().f_locals else: return self.localNamespace def currentFrame(self): ## Return the currently selected exception stack frame (or None if there is no exception) index = self.ui.exceptionStackList.currentRow() if index >= 0 and index < len(self.frames): return self.frames[index] else: return None def execSingle(self, cmd): try: output = eval(cmd, self.globals(), self.locals()) self.write(repr(output) + '\n') except SyntaxError: try: exec(cmd, self.globals(), self.locals()) except SyntaxError as exc: if 'unexpected EOF' in exc.msg: self.multiline = cmd else: self.displayException() except: self.displayException() except: self.displayException() def execMulti(self, nextLine): #self.stdout.write(nextLine+"\n") if nextLine.strip() != '': self.multiline += "\n" + nextLine return else: cmd = self.multiline try: output = eval(cmd, self.globals(), self.locals()) self.write(str(output) + '\n') self.multiline = None except SyntaxError: try: exec(cmd, self.globals(), self.locals()) self.multiline = None except SyntaxError as exc: if 'unexpected EOF' in exc.msg: self.multiline = cmd else: self.displayException() self.multiline = None except: self.displayException() self.multiline = None except: self.displayException() self.multiline = None def write(self, strn, html=False, scrollToBottom='auto'): """Write a string into the console. If scrollToBottom is 'auto', then the console is automatically scrolled to fit the new text only if it was already at the bottom. """ isGuiThread = QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread() if not isGuiThread: self.stdout.write(strn) return sb = self.output.verticalScrollBar() scroll = sb.value() if scrollToBottom == 'auto': atBottom = scroll == sb.maximum() scrollToBottom = atBottom self.output.moveCursor(QtGui.QTextCursor.End) if html: self.output.textCursor().insertHtml(strn) else: if self.inCmd: self.inCmd = False self.output.textCursor().insertHtml("</div><br><div style='font-weight: normal; background-color: #FFF; color: black'>") self.output.insertPlainText(strn) if scrollToBottom: sb.setValue(sb.maximum()) else: sb.setValue(scroll) def displayException(self): """ Display the current exception and stack. """ tb = traceback.format_exc() lines = [] indent = 4 prefix = '' for l in tb.split('\n'): lines.append(" "*indent + prefix + l) self.write('\n'.join(lines)) self.exceptionHandler(*sys.exc_info()) def cmdSelected(self, item): index = -(self.ui.historyList.row(item)+1) self.input.setHistory(index) self.input.setFocus() def cmdDblClicked(self, item): index = -(self.ui.historyList.row(item)+1) self.input.setHistory(index) self.input.execCmd() def flush(self): pass def catchAllExceptions(self, catch=True): """ If True, the console will catch all unhandled exceptions and display the stack trace. Each exception caught clears the last. """ with SignalBlock(self.ui.catchAllExceptionsBtn.toggled, self.catchAllExceptions): self.ui.catchAllExceptionsBtn.setChecked(catch) if catch: with SignalBlock(self.ui.catchNextExceptionBtn.toggled, self.catchNextException): self.ui.catchNextExceptionBtn.setChecked(False) self.enableExceptionHandling() self.ui.exceptionBtn.setChecked(True) else: self.disableExceptionHandling() def catchNextException(self, catch=True): """ If True, the console will catch the next unhandled exception and display the stack trace. """ with SignalBlock(self.ui.catchNextExceptionBtn.toggled, self.catchNextException): self.ui.catchNextExceptionBtn.setChecked(catch) if catch: with SignalBlock(self.ui.catchAllExceptionsBtn.toggled, self.catchAllExceptions): self.ui.catchAllExceptionsBtn.setChecked(False) self.enableExceptionHandling() self.ui.exceptionBtn.setChecked(True) else: self.disableExceptionHandling() def enableExceptionHandling(self): exceptionHandling.register(self.exceptionHandler) self.updateSysTrace() def disableExceptionHandling(self): exceptionHandling.unregister(self.exceptionHandler) self.updateSysTrace() def clearExceptionClicked(self): self.currentTraceback = None self.frames = [] self.ui.exceptionInfoLabel.setText("[No current exception]") self.ui.exceptionStackList.clear() self.ui.clearExceptionBtn.setEnabled(False) def stackItemClicked(self, item): pass def stackItemDblClicked(self, item): editor = self.editor if editor is None: editor = getConfigOption('editorCommand') if editor is None: return tb = self.currentFrame() lineNum = tb.tb_lineno fileName = tb.tb_frame.f_code.co_filename subprocess.Popen(self.editor.format(fileName=fileName, lineNum=lineNum), shell=True) def updateSysTrace(self): ## Install or uninstall sys.settrace handler if not self.ui.catchNextExceptionBtn.isChecked() and not self.ui.catchAllExceptionsBtn.isChecked(): if sys.gettrace() == self.systrace: sys.settrace(None) return if self.ui.onlyUncaughtCheck.isChecked(): if sys.gettrace() == self.systrace: sys.settrace(None) else: if sys.gettrace() is not None and sys.gettrace() != self.systrace: self.ui.onlyUncaughtCheck.setChecked(False) raise Exception("sys.settrace is in use; cannot monitor for caught exceptions.") else: sys.settrace(self.systrace) def exceptionHandler(self, excType, exc, tb, systrace=False, frame=None): if frame is None: frame = sys._getframe() # exceptions raised in non-gui threads must be handled separately isGuiThread = QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread() if not isGuiThread: # sending a frame from one thread to another.. probably not safe, but better than just # dropping the exception? self._threadException.emit((excType, exc, tb, systrace, frame.f_back)) return if self.ui.catchNextExceptionBtn.isChecked(): self.ui.catchNextExceptionBtn.setChecked(False) elif not self.ui.catchAllExceptionsBtn.isChecked(): return self.currentTraceback = tb excMessage = ''.join(traceback.format_exception_only(excType, exc)) self.ui.exceptionInfoLabel.setText(excMessage) if systrace: # exceptions caught using systrace don't need the usual # call stack + traceback handling self.setStack(frame.f_back.f_back) else: self.setStack(frame=frame.f_back, tb=tb) def _threadExceptionHandler(self, args): self.exceptionHandler(*args) def setStack(self, frame=None, tb=None): """Display a call stack and exception traceback. This allows the user to probe the contents of any frame in the given stack. *frame* may either be a Frame instance or None, in which case the current frame is retrieved from ``sys._getframe()``. If *tb* is provided then the frames in the traceback will be appended to the end of the stack list. If *tb* is None, then sys.exc_info() will be checked instead. """ self.ui.clearExceptionBtn.setEnabled(True) if frame is None: frame = sys._getframe().f_back if tb is None: tb = sys.exc_info()[2] self.ui.exceptionStackList.clear() self.frames = [] # Build stack up to this point for index, line in enumerate(traceback.extract_stack(frame)): # extract_stack return value changed in python 3.5 if 'FrameSummary' in str(type(line)): line = (line.filename, line.lineno, line.name, line._line) self.ui.exceptionStackList.addItem('File "%s", line %s, in %s()\n %s' % line) while frame is not None: self.frames.insert(0, frame) frame = frame.f_back if tb is None: return self.ui.exceptionStackList.addItem('-- exception caught here: --') item = self.ui.exceptionStackList.item(self.ui.exceptionStackList.count()-1) item.setBackground(QtGui.QBrush(QtGui.QColor(200, 200, 200))) item.setForeground(QtGui.QBrush(QtGui.QColor(50, 50, 50))) self.frames.append(None) # And finish the rest of the stack up to the exception for index, line in enumerate(traceback.extract_tb(tb)): # extract_stack return value changed in python 3.5 if 'FrameSummary' in str(type(line)): line = (line.filename, line.lineno, line.name, line._line) self.ui.exceptionStackList.addItem('File "%s", line %s, in %s()\n %s' % line) while tb is not None: self.frames.append(tb.tb_frame) tb = tb.tb_next def systrace(self, frame, event, arg): if event == 'exception' and self.checkException(*arg): self.exceptionHandler(*arg, systrace=True) return self.systrace def checkException(self, excType, exc, tb): ## Return True if the exception is interesting; False if it should be ignored. filename = tb.tb_frame.f_code.co_filename function = tb.tb_frame.f_code.co_name filterStr = str(self.ui.filterText.text()) if filterStr != '': if isinstance(exc, Exception): msg = exc.message elif isinstance(exc, basestring): msg = exc else: msg = repr(exc) match = re.search(filterStr, "%s:%s:%s" % (filename, function, msg)) return match is not None ## Go through a list of common exception points we like to ignore: if excType is GeneratorExit or excType is StopIteration: return False if excType is KeyError: if filename.endswith('python2.7/weakref.py') and function in ('__contains__', 'get'): return False if filename.endswith('python2.7/copy.py') and function == '_keep_alive': return False if excType is AttributeError: if filename.endswith('python2.7/collections.py') and function == '__init__': return False if filename.endswith('numpy/core/fromnumeric.py') and function in ('all', '_wrapit', 'transpose', 'sum'): return False if filename.endswith('numpy/core/arrayprint.py') and function in ('_array2string'): return False if filename.endswith('MetaArray.py') and function == '__getattr__': for name in ('__array_interface__', '__array_struct__', '__array__'): ## numpy looks for these when converting objects to array if name in exc: return False if filename.endswith('flowchart/eq.py'): return False if filename.endswith('pyqtgraph/functions.py') and function == 'makeQImage': return False if excType is TypeError: if filename.endswith('numpy/lib/function_base.py') and function == 'iterable': return False if excType is ZeroDivisionError: if filename.endswith('python2.7/traceback.py'): return False return True
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/console/template_pyside.py
.py
6,793
116
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyqtgraph/console/template.ui' # # Created: Tue Sep 19 09:45:18 2017 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(739, 497) self.gridLayout = QtGui.QGridLayout(Form) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setSpacing(0) self.gridLayout.setObjectName("gridLayout") self.splitter = QtGui.QSplitter(Form) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName("splitter") self.layoutWidget = QtGui.QWidget(self.splitter) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout = QtGui.QVBoxLayout(self.layoutWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.output = QtGui.QPlainTextEdit(self.layoutWidget) font = QtGui.QFont() font.setFamily("Monospace") self.output.setFont(font) self.output.setReadOnly(True) self.output.setObjectName("output") self.verticalLayout.addWidget(self.output) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.input = CmdInput(self.layoutWidget) self.input.setObjectName("input") self.horizontalLayout.addWidget(self.input) self.historyBtn = QtGui.QPushButton(self.layoutWidget) self.historyBtn.setCheckable(True) self.historyBtn.setObjectName("historyBtn") self.horizontalLayout.addWidget(self.historyBtn) self.exceptionBtn = QtGui.QPushButton(self.layoutWidget) self.exceptionBtn.setCheckable(True) self.exceptionBtn.setObjectName("exceptionBtn") self.horizontalLayout.addWidget(self.exceptionBtn) self.verticalLayout.addLayout(self.horizontalLayout) self.historyList = QtGui.QListWidget(self.splitter) font = QtGui.QFont() font.setFamily("Monospace") self.historyList.setFont(font) self.historyList.setObjectName("historyList") self.exceptionGroup = QtGui.QGroupBox(self.splitter) self.exceptionGroup.setObjectName("exceptionGroup") self.gridLayout_2 = QtGui.QGridLayout(self.exceptionGroup) self.gridLayout_2.setContentsMargins(-1, 0, -1, 0) self.gridLayout_2.setHorizontalSpacing(2) self.gridLayout_2.setVerticalSpacing(0) self.gridLayout_2.setObjectName("gridLayout_2") self.clearExceptionBtn = QtGui.QPushButton(self.exceptionGroup) self.clearExceptionBtn.setEnabled(False) self.clearExceptionBtn.setObjectName("clearExceptionBtn") self.gridLayout_2.addWidget(self.clearExceptionBtn, 0, 6, 1, 1) self.catchAllExceptionsBtn = QtGui.QPushButton(self.exceptionGroup) self.catchAllExceptionsBtn.setCheckable(True) self.catchAllExceptionsBtn.setObjectName("catchAllExceptionsBtn") self.gridLayout_2.addWidget(self.catchAllExceptionsBtn, 0, 1, 1, 1) self.catchNextExceptionBtn = QtGui.QPushButton(self.exceptionGroup) self.catchNextExceptionBtn.setCheckable(True) self.catchNextExceptionBtn.setObjectName("catchNextExceptionBtn") self.gridLayout_2.addWidget(self.catchNextExceptionBtn, 0, 0, 1, 1) self.onlyUncaughtCheck = QtGui.QCheckBox(self.exceptionGroup) self.onlyUncaughtCheck.setChecked(True) self.onlyUncaughtCheck.setObjectName("onlyUncaughtCheck") self.gridLayout_2.addWidget(self.onlyUncaughtCheck, 0, 4, 1, 1) self.exceptionStackList = QtGui.QListWidget(self.exceptionGroup) self.exceptionStackList.setAlternatingRowColors(True) self.exceptionStackList.setObjectName("exceptionStackList") self.gridLayout_2.addWidget(self.exceptionStackList, 2, 0, 1, 7) self.runSelectedFrameCheck = QtGui.QCheckBox(self.exceptionGroup) self.runSelectedFrameCheck.setChecked(True) self.runSelectedFrameCheck.setObjectName("runSelectedFrameCheck") self.gridLayout_2.addWidget(self.runSelectedFrameCheck, 3, 0, 1, 7) self.exceptionInfoLabel = QtGui.QLabel(self.exceptionGroup) self.exceptionInfoLabel.setWordWrap(True) self.exceptionInfoLabel.setObjectName("exceptionInfoLabel") self.gridLayout_2.addWidget(self.exceptionInfoLabel, 1, 0, 1, 7) spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 5, 1, 1) self.label = QtGui.QLabel(self.exceptionGroup) self.label.setObjectName("label") self.gridLayout_2.addWidget(self.label, 0, 2, 1, 1) self.filterText = QtGui.QLineEdit(self.exceptionGroup) self.filterText.setObjectName("filterText") self.gridLayout_2.addWidget(self.filterText, 0, 3, 1, 1) self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(QtGui.QApplication.translate("Form", "Console", None, QtGui.QApplication.UnicodeUTF8)) self.historyBtn.setText(QtGui.QApplication.translate("Form", "History..", None, QtGui.QApplication.UnicodeUTF8)) self.exceptionBtn.setText(QtGui.QApplication.translate("Form", "Exceptions..", None, QtGui.QApplication.UnicodeUTF8)) self.exceptionGroup.setTitle(QtGui.QApplication.translate("Form", "Exception Handling", None, QtGui.QApplication.UnicodeUTF8)) self.clearExceptionBtn.setText(QtGui.QApplication.translate("Form", "Clear Stack", None, QtGui.QApplication.UnicodeUTF8)) self.catchAllExceptionsBtn.setText(QtGui.QApplication.translate("Form", "Show All Exceptions", None, QtGui.QApplication.UnicodeUTF8)) self.catchNextExceptionBtn.setText(QtGui.QApplication.translate("Form", "Show Next Exception", None, QtGui.QApplication.UnicodeUTF8)) self.onlyUncaughtCheck.setText(QtGui.QApplication.translate("Form", "Only Uncaught Exceptions", None, QtGui.QApplication.UnicodeUTF8)) self.runSelectedFrameCheck.setText(QtGui.QApplication.translate("Form", "Run commands in selected stack frame", None, QtGui.QApplication.UnicodeUTF8)) self.exceptionInfoLabel.setText(QtGui.QApplication.translate("Form", "Stack Trace", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("Form", "Filter (regex):", None, QtGui.QApplication.UnicodeUTF8)) from .CmdInput import CmdInput
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/console/CmdInput.py
.py
1,236
41
from ..Qt import QtCore, QtGui from ..python2_3 import asUnicode class CmdInput(QtGui.QLineEdit): sigExecuteCmd = QtCore.Signal(object) def __init__(self, parent): QtGui.QLineEdit.__init__(self, parent) self.history = [""] self.ptr = 0 def keyPressEvent(self, ev): if ev.key() == QtCore.Qt.Key_Up: if self.ptr < len(self.history) - 1: self.setHistory(self.ptr+1) ev.accept() return elif ev.key() == QtCore.Qt.Key_Down: if self.ptr > 0: self.setHistory(self.ptr-1) ev.accept() return elif ev.key() == QtCore.Qt.Key_Return: self.execCmd() else: QtGui.QLineEdit.keyPressEvent(self, ev) self.history[0] = asUnicode(self.text()) def execCmd(self): cmd = asUnicode(self.text()) if len(self.history) == 1 or cmd != self.history[1]: self.history.insert(1, cmd) self.history[0] = "" self.setHistory(0) self.sigExecuteCmd.emit(cmd) def setHistory(self, num): self.ptr = num self.setText(self.history[self.ptr])
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/console/template_pyqt.py
.py
6,808
128
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyqtgraph/console/template.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(739, 497) self.gridLayout = QtGui.QGridLayout(Form) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.splitter = QtGui.QSplitter(Form) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(_fromUtf8("splitter")) self.layoutWidget = QtGui.QWidget(self.splitter) self.layoutWidget.setObjectName(_fromUtf8("layoutWidget")) self.verticalLayout = QtGui.QVBoxLayout(self.layoutWidget) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.output = QtGui.QPlainTextEdit(self.layoutWidget) font = QtGui.QFont() font.setFamily(_fromUtf8("Monospace")) self.output.setFont(font) self.output.setReadOnly(True) self.output.setObjectName(_fromUtf8("output")) self.verticalLayout.addWidget(self.output) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.input = CmdInput(self.layoutWidget) self.input.setObjectName(_fromUtf8("input")) self.horizontalLayout.addWidget(self.input) self.historyBtn = QtGui.QPushButton(self.layoutWidget) self.historyBtn.setCheckable(True) self.historyBtn.setObjectName(_fromUtf8("historyBtn")) self.horizontalLayout.addWidget(self.historyBtn) self.exceptionBtn = QtGui.QPushButton(self.layoutWidget) self.exceptionBtn.setCheckable(True) self.exceptionBtn.setObjectName(_fromUtf8("exceptionBtn")) self.horizontalLayout.addWidget(self.exceptionBtn) self.verticalLayout.addLayout(self.horizontalLayout) self.historyList = QtGui.QListWidget(self.splitter) font = QtGui.QFont() font.setFamily(_fromUtf8("Monospace")) self.historyList.setFont(font) self.historyList.setObjectName(_fromUtf8("historyList")) self.exceptionGroup = QtGui.QGroupBox(self.splitter) self.exceptionGroup.setObjectName(_fromUtf8("exceptionGroup")) self.gridLayout_2 = QtGui.QGridLayout(self.exceptionGroup) self.gridLayout_2.setContentsMargins(-1, 0, -1, 0) self.gridLayout_2.setHorizontalSpacing(2) self.gridLayout_2.setVerticalSpacing(0) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.clearExceptionBtn = QtGui.QPushButton(self.exceptionGroup) self.clearExceptionBtn.setEnabled(False) self.clearExceptionBtn.setObjectName(_fromUtf8("clearExceptionBtn")) self.gridLayout_2.addWidget(self.clearExceptionBtn, 0, 6, 1, 1) self.catchAllExceptionsBtn = QtGui.QPushButton(self.exceptionGroup) self.catchAllExceptionsBtn.setCheckable(True) self.catchAllExceptionsBtn.setObjectName(_fromUtf8("catchAllExceptionsBtn")) self.gridLayout_2.addWidget(self.catchAllExceptionsBtn, 0, 1, 1, 1) self.catchNextExceptionBtn = QtGui.QPushButton(self.exceptionGroup) self.catchNextExceptionBtn.setCheckable(True) self.catchNextExceptionBtn.setObjectName(_fromUtf8("catchNextExceptionBtn")) self.gridLayout_2.addWidget(self.catchNextExceptionBtn, 0, 0, 1, 1) self.onlyUncaughtCheck = QtGui.QCheckBox(self.exceptionGroup) self.onlyUncaughtCheck.setChecked(True) self.onlyUncaughtCheck.setObjectName(_fromUtf8("onlyUncaughtCheck")) self.gridLayout_2.addWidget(self.onlyUncaughtCheck, 0, 4, 1, 1) self.exceptionStackList = QtGui.QListWidget(self.exceptionGroup) self.exceptionStackList.setAlternatingRowColors(True) self.exceptionStackList.setObjectName(_fromUtf8("exceptionStackList")) self.gridLayout_2.addWidget(self.exceptionStackList, 2, 0, 1, 7) self.runSelectedFrameCheck = QtGui.QCheckBox(self.exceptionGroup) self.runSelectedFrameCheck.setChecked(True) self.runSelectedFrameCheck.setObjectName(_fromUtf8("runSelectedFrameCheck")) self.gridLayout_2.addWidget(self.runSelectedFrameCheck, 3, 0, 1, 7) self.exceptionInfoLabel = QtGui.QLabel(self.exceptionGroup) self.exceptionInfoLabel.setWordWrap(True) self.exceptionInfoLabel.setObjectName(_fromUtf8("exceptionInfoLabel")) self.gridLayout_2.addWidget(self.exceptionInfoLabel, 1, 0, 1, 7) spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 5, 1, 1) self.label = QtGui.QLabel(self.exceptionGroup) self.label.setObjectName(_fromUtf8("label")) self.gridLayout_2.addWidget(self.label, 0, 2, 1, 1) self.filterText = QtGui.QLineEdit(self.exceptionGroup) self.filterText.setObjectName(_fromUtf8("filterText")) self.gridLayout_2.addWidget(self.filterText, 0, 3, 1, 1) self.gridLayout.addWidget(self.splitter, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Console", None)) self.historyBtn.setText(_translate("Form", "History..", None)) self.exceptionBtn.setText(_translate("Form", "Exceptions..", None)) self.exceptionGroup.setTitle(_translate("Form", "Exception Handling", None)) self.clearExceptionBtn.setText(_translate("Form", "Clear Stack", None)) self.catchAllExceptionsBtn.setText(_translate("Form", "Show All Exceptions", None)) self.catchNextExceptionBtn.setText(_translate("Form", "Show Next Exception", None)) self.onlyUncaughtCheck.setText(_translate("Form", "Only Uncaught Exceptions", None)) self.runSelectedFrameCheck.setText(_translate("Form", "Run commands in selected stack frame", None)) self.exceptionInfoLabel.setText(_translate("Form", "Stack Trace", None)) self.label.setText(_translate("Form", "Filter (regex):", None)) from .CmdInput import CmdInput
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/Exporter.py
.py
5,393
140
from ..widgets.FileDialog import FileDialog from ..Qt import QtGui, QtCore, QtSvg from ..python2_3 import asUnicode, basestring from ..GraphicsScene import GraphicsScene import os, re LastExportDirectory = None class Exporter(object): """ Abstract class used for exporting graphics to file / printer / whatever. """ allowCopy = False # subclasses set this to True if they can use the copy buffer Exporters = [] @classmethod def register(cls): """ Used to register Exporter classes to appear in the export dialog. """ Exporter.Exporters.append(cls) def __init__(self, item): """ Initialize with the item to be exported. Can be an individual graphics item or a scene. """ object.__init__(self) self.item = item def parameters(self): """Return the parameters used to configure this exporter.""" raise Exception("Abstract method must be overridden in subclass.") def export(self, fileName=None, toBytes=False, copy=False): """ If *fileName* is None, pop-up a file dialog. If *toBytes* is True, return a bytes object rather than writing to file. If *copy* is True, export to the copy buffer rather than writing to file. """ raise Exception("Abstract method must be overridden in subclass.") def fileSaveDialog(self, filter=None, opts=None): ## Show a file dialog, call self.export(fileName) when finished. if opts is None: opts = {} self.fileDialog = FileDialog() self.fileDialog.setFileMode(QtGui.QFileDialog.AnyFile) self.fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) if filter is not None: if isinstance(filter, basestring): self.fileDialog.setNameFilter(filter) elif isinstance(filter, list): self.fileDialog.setNameFilters(filter) global LastExportDirectory exportDir = LastExportDirectory if exportDir is not None: self.fileDialog.setDirectory(exportDir) self.fileDialog.show() self.fileDialog.opts = opts self.fileDialog.fileSelected.connect(self.fileSaveFinished) return def fileSaveFinished(self, fileName): fileName = asUnicode(fileName) global LastExportDirectory LastExportDirectory = os.path.split(fileName)[0] ## If file name does not match selected extension, append it now ext = os.path.splitext(fileName)[1].lower().lstrip('.') selectedExt = re.search(r'\*\.(\w+)\b', asUnicode(self.fileDialog.selectedNameFilter())) if selectedExt is not None: selectedExt = selectedExt.groups()[0].lower() if ext != selectedExt: fileName = fileName + '.' + selectedExt.lstrip('.') self.export(fileName=fileName, **self.fileDialog.opts) def getScene(self): if isinstance(self.item, GraphicsScene): return self.item else: return self.item.scene() def getSourceRect(self): if isinstance(self.item, GraphicsScene): w = self.item.getViewWidget() return w.viewportTransform().inverted()[0].mapRect(w.rect()) else: return self.item.sceneBoundingRect() def getTargetRect(self): if isinstance(self.item, GraphicsScene): return self.item.getViewWidget().rect() else: return self.item.mapRectToDevice(self.item.boundingRect()) def setExportMode(self, export, opts=None): """ Call setExportMode(export, opts) on all items that will be painted during the export. This informs the item that it is about to be painted for export, allowing it to alter its appearance temporarily *export* - bool; must be True before exporting and False afterward *opts* - dict; common parameters are 'antialias' and 'background' """ if opts is None: opts = {} for item in self.getPaintItems(): if hasattr(item, 'setExportMode'): item.setExportMode(export, opts) def getPaintItems(self, root=None): """Return a list of all items that should be painted in the correct order.""" if root is None: root = self.item preItems = [] postItems = [] if isinstance(root, QtGui.QGraphicsScene): childs = [i for i in root.items() if i.parentItem() is None] rootItem = [] else: childs = root.childItems() rootItem = [root] childs.sort(key=lambda a: a.zValue()) while len(childs) > 0: ch = childs.pop(0) tree = self.getPaintItems(ch) if int(ch.flags() & ch.ItemStacksBehindParent) > 0 or (ch.zValue() < 0 and int(ch.flags() & ch.ItemNegativeZStacksBehindParent) > 0): preItems.extend(tree) else: postItems.extend(tree) return preItems + rootItem + postItems def render(self, painter, targetRect, sourceRect, item=None): self.getScene().render(painter, QtCore.QRectF(targetRect), QtCore.QRectF(sourceRect))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/HDF5Exporter.py
.py
2,396
72
from ..Qt import QtGui, QtCore from .Exporter import Exporter from ..parametertree import Parameter from .. import PlotItem import numpy try: import h5py HAVE_HDF5 = True except ImportError: HAVE_HDF5 = False __all__ = ['HDF5Exporter'] class HDF5Exporter(Exporter): Name = "HDF5 Export: plot (x,y)" windows = [] allowCopy = False def __init__(self, item): Exporter.__init__(self, item) self.params = Parameter(name='params', type='group', children=[ {'name': 'Name', 'type': 'str', 'value': 'Export',}, {'name': 'columnMode', 'type': 'list', 'values': ['(x,y) per plot', '(x,y,y,y) for all plots']}, ]) def parameters(self): return self.params def export(self, fileName=None): if not HAVE_HDF5: raise RuntimeError("This exporter requires the h5py package, " "but it was not importable.") if not isinstance(self.item, PlotItem): raise Exception("Must have a PlotItem selected for HDF5 export.") if fileName is None: self.fileSaveDialog(filter=["*.h5", "*.hdf", "*.hd5"]) return dsname = self.params['Name'] fd = h5py.File(fileName, 'a') # forces append to file... 'w' doesn't seem to "delete/overwrite" data = [] appendAllX = self.params['columnMode'] == '(x,y) per plot' # Check if the arrays are ragged len_first = len(self.item.curves[0].getData()[0]) if self.item.curves[0] else None ragged = any(len(i.getData()[0]) != len_first for i in self.item.curves) if ragged: dgroup = fd.create_group(dsname) for i, c in enumerate(self.item.curves): d = c.getData() fdata = numpy.array([d[0], d[1]]).astype('double') cname = c.name() if c.name() is not None else str(i) dset = dgroup.create_dataset(cname, data=fdata) else: for i, c in enumerate(self.item.curves): d = c.getData() if appendAllX or i == 0: data.append(d[0]) data.append(d[1]) fdata = numpy.array(data).astype('double') dset = fd.create_dataset(dsname, data=fdata) fd.close() if HAVE_HDF5: HDF5Exporter.register()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/CSVExporter.py
.py
2,857
85
# -*- coding: utf-8 -*- from ..Qt import QtGui, QtCore from .Exporter import Exporter from ..parametertree import Parameter from .. import PlotItem __all__ = ['CSVExporter'] class CSVExporter(Exporter): Name = "CSV from plot data" windows = [] def __init__(self, item): Exporter.__init__(self, item) self.params = Parameter(name='params', type='group', children=[ {'name': 'separator', 'type': 'list', 'value': 'comma', 'values': ['comma', 'tab']}, {'name': 'precision', 'type': 'int', 'value': 10, 'limits': [0, None]}, {'name': 'columnMode', 'type': 'list', 'values': ['(x,y) per plot', '(x,y,y,y) for all plots']} ]) def parameters(self): return self.params def export(self, fileName=None): if not isinstance(self.item, PlotItem): raise Exception("Must have a PlotItem selected for CSV export.") if fileName is None: self.fileSaveDialog(filter=["*.csv", "*.tsv"]) return data = [] header = [] appendAllX = self.params['columnMode'] == '(x,y) per plot' for i, c in enumerate(self.item.curves): cd = c.getData() if cd[0] is None: continue data.append(cd) if hasattr(c, 'implements') and c.implements('plotData') and c.name() is not None: name = c.name().replace('"', '""') + '_' xName, yName = '"'+name+'x"', '"'+name+'y"' else: xName = 'x%04d' % i yName = 'y%04d' % i if appendAllX or i == 0: header.extend([xName, yName]) else: header.extend([yName]) if self.params['separator'] == 'comma': sep = ',' else: sep = '\t' with open(fileName, 'w') as fd: fd.write(sep.join(header) + '\n') i = 0 numFormat = '%%0.%dg' % self.params['precision'] numRows = max([len(d[0]) for d in data]) for i in range(numRows): for j, d in enumerate(data): # write x value if this is the first column, or if we want # x for all rows if appendAllX or j == 0: if d is not None and i < len(d[0]): fd.write(numFormat % d[0][i] + sep) else: fd.write(' %s' % sep) # write y value if d is not None and i < len(d[1]): fd.write(numFormat % d[1][i] + sep) else: fd.write(' %s' % sep) fd.write('\n') CSVExporter.register()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/SVGExporter.py
.py
17,482
444
from .Exporter import Exporter from ..python2_3 import asUnicode from ..parametertree import Parameter from ..Qt import QtGui, QtCore, QtSvg, QT_LIB from .. import debug from .. import functions as fn import re import xml.dom.minidom as xml import numpy as np __all__ = ['SVGExporter'] class SVGExporter(Exporter): Name = "Scalable Vector Graphics (SVG)" allowCopy=True def __init__(self, item): Exporter.__init__(self, item) #tr = self.getTargetRect() self.params = Parameter(name='params', type='group', children=[ #{'name': 'width', 'type': 'float', 'value': tr.width(), 'limits': (0, None)}, #{'name': 'height', 'type': 'float', 'value': tr.height(), 'limits': (0, None)}, #{'name': 'viewbox clipping', 'type': 'bool', 'value': True}, #{'name': 'normalize coordinates', 'type': 'bool', 'value': True}, {'name': 'scaling stroke', 'type': 'bool', 'value': False, 'tip': "If False, strokes are non-scaling, " "which means that they appear the same width on screen regardless of how they are scaled or how the view is zoomed."}, ]) #self.params.param('width').sigValueChanged.connect(self.widthChanged) #self.params.param('height').sigValueChanged.connect(self.heightChanged) def widthChanged(self): sr = self.getSourceRect() ar = sr.height() / sr.width() self.params.param('height').setValue(self.params['width'] * ar, blockSignal=self.heightChanged) def heightChanged(self): sr = self.getSourceRect() ar = sr.width() / sr.height() self.params.param('width').setValue(self.params['height'] * ar, blockSignal=self.widthChanged) def parameters(self): return self.params def export(self, fileName=None, toBytes=False, copy=False): if toBytes is False and copy is False and fileName is None: self.fileSaveDialog(filter="Scalable Vector Graphics (*.svg)") return ## Qt's SVG generator is not complete. (notably, it lacks clipping) ## Instead, we will use Qt to generate SVG for each item independently, ## then manually reconstruct the entire document. options = {ch.name():ch.value() for ch in self.params.children()} xml = generateSvg(self.item, options) if toBytes: return xml.encode('UTF-8') elif copy: md = QtCore.QMimeData() md.setData('image/svg+xml', QtCore.QByteArray(xml.encode('UTF-8'))) QtGui.QApplication.clipboard().setMimeData(md) else: with open(fileName, 'wb') as fh: fh.write(asUnicode(xml).encode('utf-8')) xmlHeader = """\ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.2" baseProfile="tiny"> <title>pyqtgraph SVG export</title> <desc>Generated with Qt and pyqtgraph</desc> <style> image { image-rendering: crisp-edges; image-rendering: -moz-crisp-edges; image-rendering: pixelated; } </style> """ def generateSvg(item, options={}): global xmlHeader try: node, defs = _generateItemSvg(item, options=options) finally: ## reset export mode for all items in the tree if isinstance(item, QtGui.QGraphicsScene): items = item.items() else: items = [item] for i in items: items.extend(i.childItems()) for i in items: if hasattr(i, 'setExportMode'): i.setExportMode(False) cleanXml(node) defsXml = "<defs>\n" for d in defs: defsXml += d.toprettyxml(indent=' ') defsXml += "</defs>\n" return xmlHeader + defsXml + node.toprettyxml(indent=' ') + "\n</svg>\n" def _generateItemSvg(item, nodes=None, root=None, options={}): ## This function is intended to work around some issues with Qt's SVG generator ## and SVG in general. ## 1) Qt SVG does not implement clipping paths. This is absurd. ## The solution is to let Qt generate SVG for each item independently, ## then glue them together manually with clipping. ## ## The format Qt generates for all items looks like this: ## ## <g> ## <g transform="matrix(...)"> ## one or more of: <path/> or <polyline/> or <text/> ## </g> ## <g transform="matrix(...)"> ## one or more of: <path/> or <polyline/> or <text/> ## </g> ## . . . ## </g> ## ## 2) There seems to be wide disagreement over whether path strokes ## should be scaled anisotropically. ## see: http://web.mit.edu/jonas/www/anisotropy/ ## Given that both inkscape and illustrator seem to prefer isotropic ## scaling, we will optimize for those cases. ## ## 3) Qt generates paths using non-scaling-stroke from SVG 1.2, but ## inkscape only supports 1.1. ## ## Both 2 and 3 can be addressed by drawing all items in world coordinates. profiler = debug.Profiler() if nodes is None: ## nodes maps all node IDs to their XML element. ## this allows us to ensure all elements receive unique names. nodes = {} if root is None: root = item ## Skip hidden items if hasattr(item, 'isVisible') and not item.isVisible(): return None ## If this item defines its own SVG generator, use that. if hasattr(item, 'generateSvg'): return item.generateSvg(nodes) ## Generate SVG text for just this item (exclude its children; we'll handle them later) tr = QtGui.QTransform() if isinstance(item, QtGui.QGraphicsScene): xmlStr = "<g>\n</g>\n" doc = xml.parseString(xmlStr) childs = [i for i in item.items() if i.parentItem() is None] elif item.__class__.paint == QtGui.QGraphicsItem.paint: xmlStr = "<g>\n</g>\n" doc = xml.parseString(xmlStr) childs = item.childItems() else: childs = item.childItems() tr = itemTransform(item, item.scene()) ## offset to corner of root item if isinstance(root, QtGui.QGraphicsScene): rootPos = QtCore.QPoint(0,0) else: rootPos = root.scenePos() tr2 = QtGui.QTransform() tr2.translate(-rootPos.x(), -rootPos.y()) tr = tr * tr2 arr = QtCore.QByteArray() buf = QtCore.QBuffer(arr) svg = QtSvg.QSvgGenerator() svg.setOutputDevice(buf) dpi = QtGui.QDesktopWidget().logicalDpiX() svg.setResolution(dpi) p = QtGui.QPainter() p.begin(svg) if hasattr(item, 'setExportMode'): item.setExportMode(True, {'painter': p}) try: p.setTransform(tr) opt = QtGui.QStyleOptionGraphicsItem() if item.flags() & QtGui.QGraphicsItem.ItemUsesExtendedStyleOption: opt.exposedRect = item.boundingRect() item.paint(p, opt, None) finally: p.end() ## Can't do this here--we need to wait until all children have painted as well. ## this is taken care of in generateSvg instead. #if hasattr(item, 'setExportMode'): #item.setExportMode(False) doc = xml.parseString(arr.data()) try: ## Get top-level group for this item g1 = doc.getElementsByTagName('g')[0] ## get list of sub-groups g2 = [n for n in g1.childNodes if isinstance(n, xml.Element) and n.tagName == 'g'] defs = doc.getElementsByTagName('defs') if len(defs) > 0: defs = [n for n in defs[0].childNodes if isinstance(n, xml.Element)] except: print(doc.toxml()) raise profiler('render') ## Get rid of group transformation matrices by applying ## transformation to inner coordinates correctCoordinates(g1, defs, item, options) profiler('correct') ## decide on a name for this item baseName = item.__class__.__name__ i = 1 while True: name = baseName + "_%d" % i if name not in nodes: break i += 1 nodes[name] = g1 g1.setAttribute('id', name) ## If this item clips its children, we need to take care of that. childGroup = g1 ## add children directly to this node unless we are clipping if not isinstance(item, QtGui.QGraphicsScene): ## See if this item clips its children if int(item.flags() & item.ItemClipsChildrenToShape) > 0: ## Generate svg for just the path path = QtGui.QGraphicsPathItem(item.mapToScene(item.shape())) item.scene().addItem(path) try: pathNode = _generateItemSvg(path, root=root, options=options)[0].getElementsByTagName('path')[0] # assume <defs> for this path is empty.. possibly problematic. finally: item.scene().removeItem(path) ## and for the clipPath element clip = name + '_clip' clipNode = g1.ownerDocument.createElement('clipPath') clipNode.setAttribute('id', clip) clipNode.appendChild(pathNode) g1.appendChild(clipNode) childGroup = g1.ownerDocument.createElement('g') childGroup.setAttribute('clip-path', 'url(#%s)' % clip) g1.appendChild(childGroup) profiler('clipping') ## Add all child items as sub-elements. childs.sort(key=lambda c: c.zValue()) for ch in childs: csvg = _generateItemSvg(ch, nodes, root, options=options) if csvg is None: continue cg, cdefs = csvg childGroup.appendChild(cg) ### this isn't quite right--some items draw below their parent (good enough for now) defs.extend(cdefs) profiler('children') return g1, defs def correctCoordinates(node, defs, item, options): # TODO: correct gradient coordinates inside defs ## Remove transformation matrices from <g> tags by applying matrix to coordinates inside. ## Each item is represented by a single top-level group with one or more groups inside. ## Each inner group contains one or more drawing primitives, possibly of different types. groups = node.getElementsByTagName('g') ## Since we leave text unchanged, groups which combine text and non-text primitives must be split apart. ## (if at some point we start correcting text transforms as well, then it should be safe to remove this) groups2 = [] for grp in groups: subGroups = [grp.cloneNode(deep=False)] textGroup = None for ch in grp.childNodes[:]: if isinstance(ch, xml.Element): if textGroup is None: textGroup = ch.tagName == 'text' if ch.tagName == 'text': if textGroup is False: subGroups.append(grp.cloneNode(deep=False)) textGroup = True else: if textGroup is True: subGroups.append(grp.cloneNode(deep=False)) textGroup = False subGroups[-1].appendChild(ch) groups2.extend(subGroups) for sg in subGroups: node.insertBefore(sg, grp) node.removeChild(grp) groups = groups2 for grp in groups: matrix = grp.getAttribute('transform') match = re.match(r'matrix\((.*)\)', matrix) if match is None: vals = [1,0,0,1,0,0] else: vals = [float(a) for a in match.groups()[0].split(',')] tr = np.array([[vals[0], vals[2], vals[4]], [vals[1], vals[3], vals[5]]]) removeTransform = False for ch in grp.childNodes: if not isinstance(ch, xml.Element): continue if ch.tagName == 'polyline': removeTransform = True coords = np.array([[float(a) for a in c.split(',')] for c in ch.getAttribute('points').strip().split(' ')]) coords = fn.transformCoordinates(tr, coords, transpose=True) ch.setAttribute('points', ' '.join([','.join([str(a) for a in c]) for c in coords])) elif ch.tagName == 'path': removeTransform = True newCoords = '' oldCoords = ch.getAttribute('d').strip() if oldCoords == '': continue for c in oldCoords.split(' '): x,y = c.split(',') if x[0].isalpha(): t = x[0] x = x[1:] else: t = '' nc = fn.transformCoordinates(tr, np.array([[float(x),float(y)]]), transpose=True) newCoords += t+str(nc[0,0])+','+str(nc[0,1])+' ' # If coords start with L instead of M, then the entire path will not be rendered. # (This can happen if the first point had nan values in it--Qt will skip it on export) if newCoords[0] != 'M': newCoords = 'M' + newCoords[1:] ch.setAttribute('d', newCoords) elif ch.tagName == 'text': removeTransform = False ## leave text alone for now. Might need this later to correctly render text with outline. #c = np.array([ #[float(ch.getAttribute('x')), float(ch.getAttribute('y'))], #[float(ch.getAttribute('font-size')), 0], #[0,0]]) #c = fn.transformCoordinates(tr, c, transpose=True) #ch.setAttribute('x', str(c[0,0])) #ch.setAttribute('y', str(c[0,1])) #fs = c[1]-c[2] #fs = (fs**2).sum()**0.5 #ch.setAttribute('font-size', str(fs)) ## Correct some font information families = ch.getAttribute('font-family').split(',') if len(families) == 1: font = QtGui.QFont(families[0].strip('" ')) if font.style() == font.SansSerif: families.append('sans-serif') elif font.style() == font.Serif: families.append('serif') elif font.style() == font.Courier: families.append('monospace') ch.setAttribute('font-family', ', '.join([f if ' ' not in f else '"%s"'%f for f in families])) ## correct line widths if needed if removeTransform and ch.getAttribute('vector-effect') != 'non-scaling-stroke' and grp.getAttribute('stroke-width') != '': w = float(grp.getAttribute('stroke-width')) s = fn.transformCoordinates(tr, np.array([[w,0], [0,0]]), transpose=True) w = ((s[0]-s[1])**2).sum()**0.5 ch.setAttribute('stroke-width', str(w)) # Remove non-scaling-stroke if requested if options.get('scaling stroke') is True and ch.getAttribute('vector-effect') == 'non-scaling-stroke': ch.removeAttribute('vector-effect') if removeTransform: grp.removeAttribute('transform') SVGExporter.register() def itemTransform(item, root): ## Return the transformation mapping item to root ## (actually to parent coordinate system of root) if item is root: tr = QtGui.QTransform() tr.translate(*item.pos()) tr = tr * item.transform() return tr if int(item.flags() & item.ItemIgnoresTransformations) > 0: pos = item.pos() parent = item.parentItem() if parent is not None: pos = itemTransform(parent, root).map(pos) tr = QtGui.QTransform() tr.translate(pos.x(), pos.y()) tr = item.transform() * tr else: ## find next parent that is either the root item or ## an item that ignores its transformation nextRoot = item while True: nextRoot = nextRoot.parentItem() if nextRoot is None: nextRoot = root break if nextRoot is root or int(nextRoot.flags() & nextRoot.ItemIgnoresTransformations) > 0: break if isinstance(nextRoot, QtGui.QGraphicsScene): tr = item.sceneTransform() else: tr = itemTransform(nextRoot, root) * item.itemTransform(nextRoot)[0] return tr def cleanXml(node): ## remove extraneous text; let the xml library do the formatting. hasElement = False nonElement = [] for ch in node.childNodes: if isinstance(ch, xml.Element): hasElement = True cleanXml(ch) else: nonElement.append(ch) if hasElement: for ch in nonElement: node.removeChild(ch) elif node.tagName == 'g': ## remove childless groups node.parentNode.removeChild(node)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/ImageExporter.py
.py
4,304
109
from .Exporter import Exporter from ..parametertree import Parameter from ..Qt import QtGui, QtCore, QtSvg, QT_LIB from .. import functions as fn import numpy as np __all__ = ['ImageExporter'] class ImageExporter(Exporter): Name = "Image File (PNG, TIF, JPG, ...)" allowCopy = True def __init__(self, item): Exporter.__init__(self, item) tr = self.getTargetRect() if isinstance(item, QtGui.QGraphicsItem): scene = item.scene() else: scene = item bgbrush = scene.views()[0].backgroundBrush() bg = bgbrush.color() if bgbrush.style() == QtCore.Qt.NoBrush: bg.setAlpha(0) self.params = Parameter(name='params', type='group', children=[ {'name': 'width', 'type': 'int', 'value': int(tr.width()), 'limits': (0, None)}, {'name': 'height', 'type': 'int', 'value': int(tr.height()), 'limits': (0, None)}, {'name': 'antialias', 'type': 'bool', 'value': True}, {'name': 'background', 'type': 'color', 'value': bg}, {'name': 'invertValue', 'type': 'bool', 'value': False} ]) self.params.param('width').sigValueChanged.connect(self.widthChanged) self.params.param('height').sigValueChanged.connect(self.heightChanged) def widthChanged(self): sr = self.getSourceRect() ar = float(sr.height()) / sr.width() self.params.param('height').setValue(int(self.params['width'] * ar), blockSignal=self.heightChanged) def heightChanged(self): sr = self.getSourceRect() ar = float(sr.width()) / sr.height() self.params.param('width').setValue(int(self.params['height'] * ar), blockSignal=self.widthChanged) def parameters(self): return self.params def export(self, fileName=None, toBytes=False, copy=False): if fileName is None and not toBytes and not copy: filter = ["*."+f.data().decode('utf-8') for f in QtGui.QImageWriter.supportedImageFormats()] preferred = ['*.png', '*.tif', '*.jpg'] for p in preferred[::-1]: if p in filter: filter.remove(p) filter.insert(0, p) self.fileSaveDialog(filter=filter) return w = int(self.params['width']) h = int(self.params['height']) if w == 0 or h == 0: raise Exception("Cannot export image with size=0 (requested " "export size is %dx%d)" % (w, h)) targetRect = QtCore.QRect(0, 0, w, h) sourceRect = self.getSourceRect() bg = np.empty((h, w, 4), dtype=np.ubyte) color = self.params['background'] bg[:,:,0] = color.blue() bg[:,:,1] = color.green() bg[:,:,2] = color.red() bg[:,:,3] = color.alpha() self.png = fn.makeQImage(bg, alpha=True, copy=False, transpose=False) self.bg = bg ## set resolution of image: origTargetRect = self.getTargetRect() resolutionScale = targetRect.width() / origTargetRect.width() #self.png.setDotsPerMeterX(self.png.dotsPerMeterX() * resolutionScale) #self.png.setDotsPerMeterY(self.png.dotsPerMeterY() * resolutionScale) painter = QtGui.QPainter(self.png) #dtr = painter.deviceTransform() try: self.setExportMode(True, {'antialias': self.params['antialias'], 'background': self.params['background'], 'painter': painter, 'resolutionScale': resolutionScale}) painter.setRenderHint(QtGui.QPainter.Antialiasing, self.params['antialias']) self.getScene().render(painter, QtCore.QRectF(targetRect), QtCore.QRectF(sourceRect)) finally: self.setExportMode(False) painter.end() if self.params['invertValue']: mn = bg[...,:3].min(axis=2) mx = bg[...,:3].max(axis=2) d = (255 - mx) - mn bg[...,:3] += d[...,np.newaxis] if copy: QtGui.QApplication.clipboard().setImage(self.png) elif toBytes: return self.png else: return self.png.save(fileName) ImageExporter.register()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/__init__.py
.py
253
12
from .Exporter import Exporter from .ImageExporter import * from .SVGExporter import * from .Matplotlib import * from .CSVExporter import * from .PrintExporter import * from .HDF5Exporter import * def listExporters(): return Exporter.Exporters[:]
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/PrintExporter.py
.py
2,671
69
from .Exporter import Exporter from ..parametertree import Parameter from ..Qt import QtGui, QtCore, QtSvg import re __all__ = ['PrintExporter'] #__all__ = [] ## Printer is disabled for now--does not work very well. class PrintExporter(Exporter): Name = "Printer" def __init__(self, item): Exporter.__init__(self, item) tr = self.getTargetRect() self.params = Parameter(name='params', type='group', children=[ {'name': 'width', 'type': 'float', 'value': 0.1, 'limits': (0, None), 'suffix': 'm', 'siPrefix': True}, {'name': 'height', 'type': 'float', 'value': (0.1 * tr.height()) / tr.width(), 'limits': (0, None), 'suffix': 'm', 'siPrefix': True}, ]) self.params.param('width').sigValueChanged.connect(self.widthChanged) self.params.param('height').sigValueChanged.connect(self.heightChanged) def widthChanged(self): sr = self.getSourceRect() ar = sr.height() / sr.width() self.params.param('height').setValue(self.params['width'] * ar, blockSignal=self.heightChanged) def heightChanged(self): sr = self.getSourceRect() ar = sr.width() / sr.height() self.params.param('width').setValue(self.params['height'] * ar, blockSignal=self.widthChanged) def parameters(self): return self.params def export(self, fileName=None): printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution) dialog = QtGui.QPrintDialog(printer) dialog.setWindowTitle("Print Document") if dialog.exec_() != QtGui.QDialog.Accepted: return #dpi = QtGui.QDesktopWidget().physicalDpiX() #self.svg.setSize(QtCore.QSize(100,100)) #self.svg.setResolution(600) #res = printer.resolution() sr = self.getSourceRect() #res = sr.width() * .4 / (self.params['width'] * 100 / 2.54) res = QtGui.QDesktopWidget().physicalDpiX() printer.setResolution(res) rect = printer.pageRect() center = rect.center() h = self.params['height'] * res * 100. / 2.54 w = self.params['width'] * res * 100. / 2.54 x = center.x() - w/2. y = center.y() - h/2. targetRect = QtCore.QRect(x, y, w, h) sourceRect = self.getSourceRect() painter = QtGui.QPainter(printer) try: self.setExportMode(True, {'painter': painter}) self.getScene().render(painter, QtCore.QRectF(targetRect), QtCore.QRectF(sourceRect)) finally: self.setExportMode(False) painter.end() #PrintExporter.register()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/Matplotlib.py
.py
4,842
128
from ..Qt import QtGui, QtCore from .Exporter import Exporter from .. import PlotItem from .. import functions as fn __all__ = ['MatplotlibExporter'] """ It is helpful when using the matplotlib Exporter if your .matplotlib/matplotlibrc file is configured appropriately. The following are suggested for getting usable PDF output that can be edited in Illustrator, etc. backend : Qt4Agg text.usetex : True # Assumes you have a findable LaTeX installation interactive : False font.family : sans-serif font.sans-serif : 'Arial' # (make first in list) mathtext.default : sf figure.facecolor : white # personal preference # next setting allows pdf font to be readable in Adobe Illustrator pdf.fonttype : 42 # set fonts to TrueType (otherwise it will be 3 # and the text will be vectorized. text.dvipnghack : True # primarily to clean up font appearance on Mac The advantage is that there is less to do to get an exported file cleaned and ready for publication. Fonts are not vectorized (outlined), and window colors are white. """ class MatplotlibExporter(Exporter): Name = "Matplotlib Window" windows = [] def __init__(self, item): Exporter.__init__(self, item) def parameters(self): return None def cleanAxes(self, axl): if type(axl) is not list: axl = [axl] for ax in axl: if ax is None: continue for loc, spine in ax.spines.items(): if loc in ['left', 'bottom']: pass elif loc in ['right', 'top']: spine.set_color('none') # do not draw the spine else: raise ValueError('Unknown spine location: %s' % loc) # turn off ticks when there is no spine ax.xaxis.set_ticks_position('bottom') def export(self, fileName=None): if isinstance(self.item, PlotItem): mpw = MatplotlibWindow() MatplotlibExporter.windows.append(mpw) stdFont = 'Arial' fig = mpw.getFigure() # get labels from the graphic item xlabel = self.item.axes['bottom']['item'].label.toPlainText() ylabel = self.item.axes['left']['item'].label.toPlainText() title = self.item.titleLabel.text ax = fig.add_subplot(111, title=title) ax.clear() self.cleanAxes(ax) #ax.grid(True) for item in self.item.curves: x, y = item.getData() opts = item.opts pen = fn.mkPen(opts['pen']) if pen.style() == QtCore.Qt.NoPen: linestyle = '' else: linestyle = '-' color = tuple([c/255. for c in fn.colorTuple(pen.color())]) symbol = opts['symbol'] if symbol == 't': symbol = '^' symbolPen = fn.mkPen(opts['symbolPen']) symbolBrush = fn.mkBrush(opts['symbolBrush']) markeredgecolor = tuple([c/255. for c in fn.colorTuple(symbolPen.color())]) markerfacecolor = tuple([c/255. for c in fn.colorTuple(symbolBrush.color())]) markersize = opts['symbolSize'] if opts['fillLevel'] is not None and opts['fillBrush'] is not None: fillBrush = fn.mkBrush(opts['fillBrush']) fillcolor = tuple([c/255. for c in fn.colorTuple(fillBrush.color())]) ax.fill_between(x=x, y1=y, y2=opts['fillLevel'], facecolor=fillcolor) pl = ax.plot(x, y, marker=symbol, color=color, linewidth=pen.width(), linestyle=linestyle, markeredgecolor=markeredgecolor, markerfacecolor=markerfacecolor, markersize=markersize) xr, yr = self.item.viewRange() ax.set_xbound(*xr) ax.set_ybound(*yr) ax.set_xlabel(xlabel) # place the labels. ax.set_ylabel(ylabel) mpw.draw() else: raise Exception("Matplotlib export currently only works with plot items") MatplotlibExporter.register() class MatplotlibWindow(QtGui.QMainWindow): def __init__(self): from ..widgets import MatplotlibWidget QtGui.QMainWindow.__init__(self) self.mpl = MatplotlibWidget.MatplotlibWidget() self.setCentralWidget(self.mpl) self.show() def __getattr__(self, attr): return getattr(self.mpl, attr) def closeEvent(self, ev): MatplotlibExporter.windows.remove(self) self.deleteLater()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/tests/test_csv.py
.py
1,704
59
""" CSV export test """ from __future__ import division, print_function, absolute_import import pyqtgraph as pg import csv import os import tempfile app = pg.mkQApp() def approxeq(a, b): return (a-b) <= ((a + b) * 1e-6) def test_CSVExporter(): tempfilename = tempfile.NamedTemporaryFile(suffix='.csv').name print("using %s as a temporary file" % tempfilename) plt = pg.plot() y1 = [1,3,2,3,1,6,9,8,4,2] plt.plot(y=y1, name='myPlot') y2 = [3,4,6,1,2,4,2,3,5,3,5,1,3] x2 = pg.np.linspace(0, 1.0, len(y2)) plt.plot(x=x2, y=y2) y3 = [1,5,2,3,4,6,1,2,4,2,3,5,3] x3 = pg.np.linspace(0, 1.0, len(y3)+1) plt.plot(x=x3, y=y3, stepMode=True) ex = pg.exporters.CSVExporter(plt.plotItem) ex.export(fileName=tempfilename) with open(tempfilename, 'r') as csv_file: r = csv.reader(csv_file) lines = [line for line in r] header = lines.pop(0) assert header == ['myPlot_x', 'myPlot_y', 'x0001', 'y0001', 'x0002', 'y0002'] i = 0 for vals in lines: vals = list(map(str.strip, vals)) assert (i >= len(y1) and vals[0] == '') or approxeq(float(vals[0]), i) assert (i >= len(y1) and vals[1] == '') or approxeq(float(vals[1]), y1[i]) assert (i >= len(x2) and vals[2] == '') or approxeq(float(vals[2]), x2[i]) assert (i >= len(y2) and vals[3] == '') or approxeq(float(vals[3]), y2[i]) assert (i >= len(x3) and vals[4] == '') or approxeq(float(vals[4]), x3[i]) assert (i >= len(y3) and vals[5] == '') or approxeq(float(vals[5]), y3[i]) i += 1 os.unlink(tempfilename) if __name__ == '__main__': test_CSVExporter()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/tests/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/tests/test_svg.py
.py
2,206
79
""" SVG export test """ from __future__ import division, print_function, absolute_import import pyqtgraph as pg import tempfile import os app = pg.mkQApp() def test_plotscene(): tempfilename = tempfile.NamedTemporaryFile(suffix='.svg').name print("using %s as a temporary file" % tempfilename) pg.setConfigOption('foreground', (0,0,0)) w = pg.GraphicsWindow() w.show() p1 = w.addPlot() p2 = w.addPlot() p1.plot([1,3,2,3,1,6,9,8,4,2,3,5,3], pen={'color':'k'}) p1.setXRange(0,5) p2.plot([1,5,2,3,4,6,1,2,4,2,3,5,3], pen={'color':'k', 'cosmetic':False, 'width': 0.3}) app.processEvents() app.processEvents() ex = pg.exporters.SVGExporter(w.scene()) ex.export(fileName=tempfilename) # clean up after the test is done os.unlink(tempfilename) w.close() def test_simple(): tempfilename = tempfile.NamedTemporaryFile(suffix='.svg').name print("using %s as a temporary file" % tempfilename) scene = pg.QtGui.QGraphicsScene() #rect = pg.QtGui.QGraphicsRectItem(0, 0, 100, 100) #scene.addItem(rect) #rect.setPos(20,20) #rect.translate(50, 50) #rect.rotate(30) #rect.scale(0.5, 0.5) #rect1 = pg.QtGui.QGraphicsRectItem(0, 0, 100, 100) #rect1.setParentItem(rect) #rect1.setFlag(rect1.ItemIgnoresTransformations) #rect1.setPos(20, 20) #rect1.scale(2,2) #el1 = pg.QtGui.QGraphicsEllipseItem(0, 0, 100, 100) #el1.setParentItem(rect1) ##grp = pg.ItemGroup() #grp.setParentItem(rect) #grp.translate(200,0) ##grp.rotate(30) #rect2 = pg.QtGui.QGraphicsRectItem(0, 0, 100, 25) #rect2.setFlag(rect2.ItemClipsChildrenToShape) #rect2.setParentItem(grp) #rect2.setPos(0,25) #rect2.rotate(30) #el = pg.QtGui.QGraphicsEllipseItem(0, 0, 100, 50) #el.translate(10,-5) #el.scale(0.5,2) #el.setParentItem(rect2) grp2 = pg.ItemGroup() scene.addItem(grp2) grp2.scale(100,100) rect3 = pg.QtGui.QGraphicsRectItem(0,0,2,2) rect3.setPen(pg.mkPen(width=1, cosmetic=False)) grp2.addItem(rect3) ex = pg.exporters.SVGExporter(scene) ex.export(fileName=tempfilename) os.unlink(tempfilename)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/tests/test_hdf5.py
.py
2,058
72
# -*- coding: utf-8 -*- import pytest import pyqtgraph as pg from pyqtgraph.exporters import HDF5Exporter import numpy as np from numpy.testing import assert_equal import h5py import os @pytest.fixture def tmp_h5(tmp_path): yield tmp_path / "data.h5" @pytest.mark.parametrize("combine", [False, True]) def test_HDF5Exporter(tmp_h5, combine): # Basic test of functionality: multiple curves with shared x array. Tests # both options for stacking the data (columnMode). x = np.linspace(0, 1, 100) y1 = np.sin(x) y2 = np.cos(x) plt = pg.plot() plt.plot(x=x, y=y1) plt.plot(x=x, y=y2) ex = HDF5Exporter(plt.plotItem) if combine: ex.parameters()['columnMode'] = '(x,y,y,y) for all plots' ex.export(fileName=tmp_h5) with h5py.File(tmp_h5, 'r') as f: # should be a single dataset with the name of the exporter dset = f[ex.parameters()['Name']] assert isinstance(dset, h5py.Dataset) if combine: assert_equal(np.array([x, y1, y2]), dset) else: assert_equal(np.array([x, y1, x, y2]), dset) def test_HDF5Exporter_unequal_lengths(tmp_h5): # Test export with multiple curves of different size. The exporter should # detect this and create multiple hdf5 datasets under a group. x1 = np.linspace(0, 1, 10) y1 = np.sin(x1) x2 = np.linspace(0, 1, 100) y2 = np.cos(x2) plt = pg.plot() plt.plot(x=x1, y=y1, name='plot0') plt.plot(x=x2, y=y2) ex = HDF5Exporter(plt.plotItem) ex.export(fileName=tmp_h5) with h5py.File(tmp_h5, 'r') as f: # should be a group with the name of the exporter group = f[ex.parameters()['Name']] assert isinstance(group, h5py.Group) # should be a dataset under the group with the name of the PlotItem assert_equal(np.array([x1, y1]), group['plot0']) # should be a dataset under the group with a default name that's the # index of the curve in the PlotItem assert_equal(np.array([x2, y2]), group['1'])
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/exporters/tests/test_image.py
.py
341
14
# -*- coding: utf-8 -*- import pyqtgraph as pg from pyqtgraph.exporters import ImageExporter app = pg.mkQApp() def test_ImageExporter_filename_dialog(): """Tests ImageExporter code path that opens a file dialog. Regression test for pull request 1133.""" p = pg.plot() exp = ImageExporter(p.getPlotItem()) exp.export()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/util/garbage_collector.py
.py
1,599
51
import gc from ..Qt import QtCore class GarbageCollector(object): ''' Disable automatic garbage collection and instead collect manually on a timer. This is done to ensure that garbage collection only happens in the GUI thread, as otherwise Qt can crash. Credit: Erik Janssens Source: http://pydev.blogspot.com/2014/03/should-python-garbage-collector-be.html ''' def __init__(self, interval=1.0, debug=False): self.debug = debug if debug: gc.set_debug(gc.DEBUG_LEAK) self.timer = QtCore.QTimer() self.timer.timeout.connect(self.check) self.threshold = gc.get_threshold() gc.disable() self.timer.start(interval * 1000) def check(self): #return self.debug_cycles() # uncomment to just debug cycles l0, l1, l2 = gc.get_count() if self.debug: print('gc_check called:', l0, l1, l2) if l0 > self.threshold[0]: num = gc.collect(0) if self.debug: print('collecting gen 0, found: %d unreachable' % num) if l1 > self.threshold[1]: num = gc.collect(1) if self.debug: print('collecting gen 1, found: %d unreachable' % num) if l2 > self.threshold[2]: num = gc.collect(2) if self.debug: print('collecting gen 2, found: %d unreachable' % num) def debug_cycles(self): gc.collect() for obj in gc.garbage: print(obj, repr(obj), type(obj))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/util/lru_cache.py
.py
4,236
122
import operator import sys import itertools _IS_PY3 = sys.version_info[0] == 3 class LRUCache(object): ''' This LRU cache should be reasonable for short collections (until around 100 items), as it does a sort on the items if the collection would become too big (so, it is very fast for getting and setting but when its size would become higher than the max size it does one sort based on the internal time to decide which items should be removed -- which should be Ok if the resizeTo isn't too close to the maxSize so that it becomes an operation that doesn't happen all the time). ''' def __init__(self, maxSize=100, resizeTo=70): ''' ============== ========================================================= **Arguments:** maxSize (int) This is the maximum size of the cache. When some item is added and the cache would become bigger than this, it's resized to the value passed on resizeTo. resizeTo (int) When a resize operation happens, this is the size of the final cache. ============== ========================================================= ''' assert resizeTo < maxSize self.maxSize = maxSize self.resizeTo = resizeTo self._counter = 0 self._dict = {} if _IS_PY3: self._nextTime = itertools.count(0).__next__ else: self._nextTime = itertools.count(0).next def __getitem__(self, key): item = self._dict[key] item[2] = self._nextTime() return item[1] def __len__(self): return len(self._dict) def __setitem__(self, key, value): item = self._dict.get(key) if item is None: if len(self._dict) + 1 > self.maxSize: self._resizeTo() item = [key, value, self._nextTime()] self._dict[key] = item else: item[1] = value item[2] = self._nextTime() def __delitem__(self, key): del self._dict[key] def get(self, key, default=None): try: return self[key] except KeyError: return default def clear(self): self._dict.clear() if _IS_PY3: def values(self): return [i[1] for i in self._dict.values()] def keys(self): return [x[0] for x in self._dict.values()] def _resizeTo(self): ordered = sorted(self._dict.values(), key=operator.itemgetter(2))[:self.resizeTo] for i in ordered: del self._dict[i[0]] def items(self, accessTime=False): ''' :param bool accessTime: If True sorts the returned items by the internal access time. ''' if accessTime: for x in sorted(self._dict.values(), key=operator.itemgetter(2)): yield x[0], x[1] else: for x in self._dict.items(): yield x[0], x[1] else: def values(self): return [i[1] for i in self._dict.values()] def keys(self): return [x[0] for x in self._dict.values()] def _resizeTo(self): ordered = sorted(self._dict.values(), key=operator.itemgetter(2))[:self.resizeTo] for i in ordered: del self._dict[i[0]] def items(self, accessTime=False): ''' ============= ====================================================== **Arguments** accessTime (bool) If True sorts the returned items by the internal access time. ============= ====================================================== ''' if accessTime: for x in sorted(self._dict.values(), key=operator.itemgetter(2)): yield x[0], x[1] else: for x in self._dict.items(): yield x[0], x[1]
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/util/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/util/cprint.py
.py
3,028
103
""" Cross-platform color text printing Based on colorama (see pyqtgraph/util/colorama/README.txt) """ import sys, re from .colorama.winterm import WinTerm, WinColor, WinStyle from .colorama.win32 import windll from ..python2_3 import basestring _WIN = sys.platform.startswith('win') if windll is not None: winterm = WinTerm() else: _WIN = False def winset(reset=False, fore=None, back=None, style=None, stderr=False): if reset: winterm.reset_all() if fore is not None: winterm.fore(fore, stderr) if back is not None: winterm.back(back, stderr) if style is not None: winterm.style(style, stderr) ANSI = {} WIN = {} for i,color in enumerate(['BLACK', 'RED', 'GREEN', 'YELLOW', 'BLUE', 'MAGENTA', 'CYAN', 'WHITE']): globals()[color] = i globals()['BR_' + color] = i + 8 globals()['BACK_' + color] = i + 40 ANSI[i] = "\033[%dm" % (30+i) ANSI[i+8] = "\033[2;%dm" % (30+i) ANSI[i+40] = "\033[%dm" % (40+i) color = 'GREY' if color == 'WHITE' else color WIN[i] = {'fore': getattr(WinColor, color), 'style': WinStyle.NORMAL} WIN[i+8] = {'fore': getattr(WinColor, color), 'style': WinStyle.BRIGHT} WIN[i+40] = {'back': getattr(WinColor, color)} RESET = -1 ANSI[RESET] = "\033[0m" WIN[RESET] = {'reset': True} def cprint(stream, *args, **kwds): """ Print with color. Examples:: # colors are BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE cprint('stdout', RED, 'This is in red. ', RESET, 'and this is normal\n') # Adding BR_ before the color manes it bright cprint('stdout', BR_GREEN, 'This is bright green.\n', RESET) # Adding BACK_ changes background color cprint('stderr', BACK_BLUE, WHITE, 'This is white-on-blue.', -1) # Integers 0-7 for normal, 8-15 for bright, and 40-47 for background. # -1 to reset. cprint('stderr', 1, 'This is in red.', -1) """ if isinstance(stream, basestring): stream = kwds.get('stream', 'stdout') err = stream == 'stderr' stream = getattr(sys, stream) else: err = kwds.get('stderr', False) if hasattr(stream, 'isatty') and stream.isatty(): if _WIN: # convert to win32 calls for arg in args: if isinstance(arg, basestring): stream.write(arg) else: kwds = WIN[arg] winset(stderr=err, **kwds) else: # convert to ANSI for arg in args: if isinstance(arg, basestring): stream.write(arg) else: stream.write(ANSI[arg]) else: # ignore colors for arg in args: if isinstance(arg, basestring): stream.write(arg) def cout(*args): """Shorthand for cprint('stdout', ...)""" cprint('stdout', *args) def cerr(*args): """Shorthand for cprint('stderr', ...)""" cprint('stderr', *args)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/util/pil_fix.py
.py
2,053
64
# -*- coding: utf-8 -*- """ Importing this module installs support for 16-bit images in PIL. This works by patching objects in the PIL namespace; no files are modified. """ from PIL import Image if Image.VERSION == '1.1.7': Image._MODE_CONV["I;16"] = ('%su2' % Image._ENDIAN, None) Image._fromarray_typemap[((1, 1), "<u2")] = ("I", "I;16") if Image.VERSION == '1.1.6': Image._MODE_CONV["I;16"] = ('%su2' % Image._ENDIAN, None) ## just a copy of fromarray() from Image.py with I;16 added in def fromarray(obj, mode=None): arr = obj.__array_interface__ shape = arr['shape'] ndim = len(shape) try: strides = arr['strides'] except KeyError: strides = None if mode is None: typestr = arr['typestr'] if not (typestr[0] == '|' or typestr[0] == Image._ENDIAN or typestr[1:] not in ['u1', 'b1', 'i4', 'f4']): raise TypeError("cannot handle data-type") if typestr[0] == Image._ENDIAN: typestr = typestr[1:3] else: typestr = typestr[:2] if typestr == 'i4': mode = 'I' if typestr == 'u2': mode = 'I;16' elif typestr == 'f4': mode = 'F' elif typestr == 'b1': mode = '1' elif ndim == 2: mode = 'L' elif ndim == 3: mode = 'RGB' elif ndim == 4: mode = 'RGBA' else: raise TypeError("Do not understand data.") ndmax = 4 bad_dims=0 if mode in ['1','L','I','P','F']: ndmax = 2 elif mode == 'RGB': ndmax = 3 if ndim > ndmax: raise ValueError("Too many dimensions.") size = shape[:2][::-1] if strides is not None: obj = obj.tostring() return frombuffer(mode, size, obj, "raw", mode, 0, 1) Image.fromarray=fromarray
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/util/get_resolution.py
.py
527
15
from .. import mkQApp def test_screenInformation(): qApp = mkQApp() desktop = qApp.desktop() resolution = desktop.screenGeometry() availableResolution = desktop.availableGeometry() print("Screen resolution: {}x{}".format(resolution.width(), resolution.height())) print("Available geometry: {}x{}".format(availableResolution.width(), availableResolution.height())) print("Number of Screens: {}".format(desktop.screenCount())) return None if __name__ == "__main__": test_screenInformation()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/util/mutex.py
.py
3,466
115
# -*- coding: utf-8 -*- import traceback from ..Qt import QtCore class Mutex(QtCore.QMutex): """ Subclass of QMutex that provides useful debugging information during deadlocks--tracebacks are printed for both the code location that is attempting to lock the mutex as well as the location that has already acquired the lock. Also provides __enter__ and __exit__ methods for use in "with" statements. """ def __init__(self, *args, **kargs): if kargs.get('recursive', False): args = (QtCore.QMutex.Recursive,) QtCore.QMutex.__init__(self, *args) self.l = QtCore.QMutex() ## for serializing access to self.tb self.tb = [] self.debug = kargs.pop('debug', False) ## True to enable debugging functions def tryLock(self, timeout=None, id=None): if timeout is None: locked = QtCore.QMutex.tryLock(self) else: locked = QtCore.QMutex.tryLock(self, timeout) if self.debug and locked: self.l.lock() try: if id is None: self.tb.append(''.join(traceback.format_stack()[:-1])) else: self.tb.append(" " + str(id)) #print 'trylock', self, len(self.tb) finally: self.l.unlock() return locked def lock(self, id=None): c = 0 waitTime = 5000 # in ms while True: if self.tryLock(waitTime, id): break c += 1 if self.debug: self.l.lock() try: print("Waiting for mutex lock (%0.1f sec). Traceback follows:" % (c*waitTime/1000.)) traceback.print_stack() if len(self.tb) > 0: print("Mutex is currently locked from:\n") print(self.tb[-1]) else: print("Mutex is currently locked from [???]") finally: self.l.unlock() #print 'lock', self, len(self.tb) def unlock(self): QtCore.QMutex.unlock(self) if self.debug: self.l.lock() try: #print 'unlock', self, len(self.tb) if len(self.tb) > 0: self.tb.pop() else: raise Exception("Attempt to unlock mutex before it has been locked") finally: self.l.unlock() def acquire(self, blocking=True): """Mimics threading.Lock.acquire() to allow this class as a drop-in replacement. """ return self.tryLock() def release(self): """Mimics threading.Lock.release() to allow this class as a drop-in replacement. """ self.unlock() def depth(self): self.l.lock() n = len(self.tb) self.l.unlock() return n def traceback(self): self.l.lock() try: ret = self.tb[:] finally: self.l.unlock() return ret def __exit__(self, *args): self.unlock() def __enter__(self): self.lock() return self class RecursiveMutex(Mutex): """Mimics threading.RLock class. """ def __init__(self, **kwds): kwds['recursive'] = True Mutex.__init__(self, **kwds)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/util/colorama/winterm.py
.py
4,205
121
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. from . import win32 # from wincon.h class WinColor(object): BLACK = 0 BLUE = 1 GREEN = 2 CYAN = 3 RED = 4 MAGENTA = 5 YELLOW = 6 GREY = 7 # from wincon.h class WinStyle(object): NORMAL = 0x00 # dim text, dim background BRIGHT = 0x08 # bright text, dim background class WinTerm(object): def __init__(self): self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes self.set_attrs(self._default) self._default_fore = self._fore self._default_back = self._back self._default_style = self._style def get_attrs(self): return self._fore + self._back * 16 + self._style def set_attrs(self, value): self._fore = value & 7 self._back = (value >> 4) & 7 self._style = value & WinStyle.BRIGHT def reset_all(self, on_stderr=None): self.set_attrs(self._default) self.set_console(attrs=self._default) def fore(self, fore=None, on_stderr=False): if fore is None: fore = self._default_fore self._fore = fore self.set_console(on_stderr=on_stderr) def back(self, back=None, on_stderr=False): if back is None: back = self._default_back self._back = back self.set_console(on_stderr=on_stderr) def style(self, style=None, on_stderr=False): if style is None: style = self._default_style self._style = style self.set_console(on_stderr=on_stderr) def set_console(self, attrs=None, on_stderr=False): if attrs is None: attrs = self.get_attrs() handle = win32.STDOUT if on_stderr: handle = win32.STDERR win32.SetConsoleTextAttribute(handle, attrs) def get_position(self, handle): position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition # Because Windows coordinates are 0-based, # and win32.SetConsoleCursorPosition expects 1-based. position.X += 1 position.Y += 1 return position def set_cursor_position(self, position=None, on_stderr=False): if position is None: #I'm not currently tracking the position, so there is no default. #position = self.get_position() return handle = win32.STDOUT if on_stderr: handle = win32.STDERR win32.SetConsoleCursorPosition(handle, position) def cursor_up(self, num_rows=0, on_stderr=False): if num_rows == 0: return handle = win32.STDOUT if on_stderr: handle = win32.STDERR position = self.get_position(handle) adjusted_position = (position.Y - num_rows, position.X) self.set_cursor_position(adjusted_position, on_stderr) def erase_data(self, mode=0, on_stderr=False): # 0 (or None) should clear from the cursor to the end of the screen. # 1 should clear from the cursor to the beginning of the screen. # 2 should clear the entire screen. (And maybe move cursor to (1,1)?) # # At the moment, I only support mode 2. From looking at the API, it # should be possible to calculate a different number of bytes to clear, # and to do so relative to the cursor position. if mode[0] not in (2,): return handle = win32.STDOUT if on_stderr: handle = win32.STDERR # here's where we'll home the cursor coord_screen = win32.COORD(0,0) csbi = win32.GetConsoleScreenBufferInfo(handle) # get the number of character cells in the current buffer dw_con_size = csbi.dwSize.X * csbi.dwSize.Y # fill the entire screen with blanks win32.FillConsoleOutputCharacter(handle, ' ', dw_con_size, coord_screen) # now set the buffer's attributes accordingly win32.FillConsoleOutputAttribute(handle, self.get_attrs(), dw_con_size, coord_screen ) # put the cursor at (0, 0) win32.SetConsoleCursorPosition(handle, (coord_screen.X, coord_screen.Y))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/util/colorama/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/util/colorama/win32.py
.py
4,901
138
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. # from winbase.h STDOUT = -11 STDERR = -12 try: from ctypes import windll from ctypes import wintypes except ImportError: windll = None SetConsoleTextAttribute = lambda *_: None else: from ctypes import ( byref, Structure, c_char, c_short, c_int, c_uint32, c_ushort, c_void_p, POINTER ) class CONSOLE_SCREEN_BUFFER_INFO(Structure): """struct in wincon.h.""" _fields_ = [ ("dwSize", wintypes._COORD), ("dwCursorPosition", wintypes._COORD), ("wAttributes", wintypes.WORD), ("srWindow", wintypes.SMALL_RECT), ("dwMaximumWindowSize", wintypes._COORD), ] def __str__(self): return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % ( self.dwSize.Y, self.dwSize.X , self.dwCursorPosition.Y, self.dwCursorPosition.X , self.wAttributes , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X ) _GetStdHandle = windll.kernel32.GetStdHandle _GetStdHandle.argtypes = [ wintypes.DWORD, ] _GetStdHandle.restype = wintypes.HANDLE _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo _GetConsoleScreenBufferInfo.argtypes = [ wintypes.HANDLE, c_void_p, #POINTER(CONSOLE_SCREEN_BUFFER_INFO), ] _GetConsoleScreenBufferInfo.restype = wintypes.BOOL _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute _SetConsoleTextAttribute.argtypes = [ wintypes.HANDLE, wintypes.WORD, ] _SetConsoleTextAttribute.restype = wintypes.BOOL _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition _SetConsoleCursorPosition.argtypes = [ wintypes.HANDLE, c_int, #wintypes._COORD, ] _SetConsoleCursorPosition.restype = wintypes.BOOL _FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA _FillConsoleOutputCharacterA.argtypes = [ wintypes.HANDLE, c_char, wintypes.DWORD, wintypes._COORD, POINTER(wintypes.DWORD), ] _FillConsoleOutputCharacterA.restype = wintypes.BOOL _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute _FillConsoleOutputAttribute.argtypes = [ wintypes.HANDLE, wintypes.WORD, wintypes.DWORD, c_int, #wintypes._COORD, POINTER(wintypes.DWORD), ] _FillConsoleOutputAttribute.restype = wintypes.BOOL handles = { STDOUT: _GetStdHandle(STDOUT), STDERR: _GetStdHandle(STDERR), } def GetConsoleScreenBufferInfo(stream_id=STDOUT): handle = handles[stream_id] csbi = CONSOLE_SCREEN_BUFFER_INFO() success = _GetConsoleScreenBufferInfo( handle, byref(csbi)) return csbi def SetConsoleTextAttribute(stream_id, attrs): handle = handles[stream_id] return _SetConsoleTextAttribute(handle, attrs) def SetConsoleCursorPosition(stream_id, position): position = wintypes._COORD(*position) # If the position is out of range, do nothing. if position.Y <= 0 or position.X <= 0: return # Adjust for Windows' SetConsoleCursorPosition: # 1. being 0-based, while ANSI is 1-based. # 2. expecting (x,y), while ANSI uses (y,x). adjusted_position = wintypes._COORD(position.Y - 1, position.X - 1) # Adjust for viewport's scroll position sr = GetConsoleScreenBufferInfo(STDOUT).srWindow adjusted_position.Y += sr.Top adjusted_position.X += sr.Left # Resume normal processing handle = handles[stream_id] return _SetConsoleCursorPosition(handle, adjusted_position) def FillConsoleOutputCharacter(stream_id, char, length, start): handle = handles[stream_id] char = c_char(char) length = wintypes.DWORD(length) num_written = wintypes.DWORD(0) # Note that this is hard-coded for ANSI (vs wide) bytes. success = _FillConsoleOutputCharacterA( handle, char, length, start, byref(num_written)) return num_written.value def FillConsoleOutputAttribute(stream_id, attr, length, start): ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )''' handle = handles[stream_id] attribute = wintypes.WORD(attr) length = wintypes.DWORD(length) num_written = wintypes.DWORD(0) # Note that this is hard-coded for ANSI (vs wide) bytes. return _FillConsoleOutputAttribute( handle, attribute, length, start, byref(num_written))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/util/tests/test_lru_cache.py
.py
1,191
51
from pyqtgraph.util.lru_cache import LRUCache def testLRU(): lru = LRUCache(2, 1) # check twice checkLru(lru) checkLru(lru) def checkLru(lru): lru[1] = 1 lru[2] = 2 lru[3] = 3 assert len(lru) == 2 assert set([2, 3]) == set(lru.keys()) assert set([2, 3]) == set(lru.values()) lru[2] = 2 assert set([2, 3]) == set(lru.values()) lru[1] = 1 set([2, 1]) == set(lru.values()) #Iterates from the used in the last access to others based on access time. assert [(2, 2), (1, 1)] == list(lru.items(accessTime=True)) lru[2] = 2 assert [(1, 1), (2, 2)] == list(lru.items(accessTime=True)) del lru[2] assert [(1, 1), ] == list(lru.items(accessTime=True)) lru[2] = 2 assert [(1, 1), (2, 2)] == list(lru.items(accessTime=True)) _a = lru[1] assert [(2, 2), (1, 1)] == list(lru.items(accessTime=True)) _a = lru[2] assert [(1, 1), (2, 2)] == list(lru.items(accessTime=True)) assert lru.get(2) == 2 assert lru.get(3) == None assert [(1, 1), (2, 2)] == list(lru.items(accessTime=True)) lru.clear() assert [] == list(lru.items()) if __name__ == '__main__': testLRU()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/pixmaps/compile.py
.py
627
20
# -*- coding: utf-8 -*- import numpy as np from PyQt4 import QtGui import os, pickle, sys path = os.path.abspath(os.path.split(__file__)[0]) pixmaps = {} for f in os.listdir(path): if not f.endswith('.png'): continue print(f) img = QtGui.QImage(os.path.join(path, f)) ptr = img.bits() ptr.setsize(img.byteCount()) arr = np.asarray(ptr).reshape(img.height(), img.width(), 4).transpose(1,0,2) pixmaps[f] = pickle.dumps(arr) ver = sys.version_info[0] with open(os.path.join(path, 'pixmapData_%d.py' % (ver, )), 'w') as fh: fh.write("import numpy as np; pixmapData=%s" % (repr(pixmaps), ))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/pixmaps/__init__.py
.py
803
28
""" Allows easy loading of pixmaps used in UI elements. Provides support for frozen environments as well. """ import os, sys, pickle from ..functions import makeQImage from ..Qt import QtGui from ..python2_3 import basestring if sys.version_info[0] == 2: from . import pixmapData_2 as pixmapData else: from . import pixmapData_3 as pixmapData def getPixmap(name): """ Return a QPixmap corresponding to the image file with the given name. (eg. getPixmap('auto') loads pyqtgraph/pixmaps/auto.png) """ key = name+'.png' data = pixmapData.pixmapData[key] if isinstance(data, basestring) or isinstance(data, bytes): pixmapData.pixmapData[key] = pickle.loads(data) arr = pixmapData.pixmapData[key] return QtGui.QPixmap(makeQImage(arr, alpha=True))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/pixmaps/pixmapData_2.py
.py
65,632
1
import numpy as np; pixmapData={'lock.png': "cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I32\nI32\nI4\ntp6\ncnumpy\ndtype\np7\n(S'u1'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS'\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xad\\xad\\xad\\x19\\xa8\\xa8\\xa8\\x8d\\xa9\\xa9\\xa9\\xc1\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xaa\\xaa\\xaa\\xc2\\xa9\\xa9\\xa9\\x8e\\xad\\xad\\xad\\x19\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xa8\\xa8\\xa8X\\xa9\\xa9\\xa9\\xed\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xed\\xa8\\xa8\\xa8X\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaaW\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa6\\xa6\\xa6\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\xa6\\xa6\\xa6\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xaa\\xaa\\xaaW\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaa\\x15\\xa9\\xa9\\xa9\\xeb\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x88\\x88\\x88\\xff)))\\xff\\x05\\x05\\x05\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff)))\\xff\\x88\\x88\\x88\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xeb\\xaa\\xaa\\xaa\\x15\\xa9\\xa9\\xa9\\x88\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x88\\x88\\x88\\xff\\x03\\x03\\x03\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x03\\x03\\x03\\xff\\x88\\x88\\x88\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\x88\\xa9\\xa9\\xa9\\xbe\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff)))\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff)))\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xbe\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa6\\xa6\\xa6\\xff\\x05\\x05\\x05\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x0c\\x0c\\x0c\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff\\xa6\\xa6\\xa6\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff@@@\\xff\\xd2\\xd2\\xd2\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe1\\xe1\\xe1\\xff{{{\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x0e\\x0e\\x0e\\xff***\\xff+++\\xff+++\\xff\\xaf\\xaf\\xaf\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe2\\xe2\\xe2\\xff\\x10\\x10\\x10\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x1e\\x1e\\x1e\\xff\\x93\\x93\\x93\\xff\\xc6\\xc6\\xc6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xffaaa\\xff\\xdc\\xdc\\xdc\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\\\\\\\\\\\\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe2\\xe2\\xe2\\xff\\xbb\\xbb\\xbb\\xff\\x9f\\x9f\\x9f\\xff\\x9f\\x9f\\x9f\\xff\\x9f\\x9f\\x9f\\xff\\xd7\\xd7\\xd7\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x1c\\x1c\\x1c\\xff\\xda\\xda\\xda\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x91\\x91\\x91\\xff\\x0f\\x0f\\x0f\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xb4\\xb4\\xb4\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x87\\x87\\x87\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x98\\x98\\x98\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xb4\\xb4\\xb4\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xba\\xba\\xba\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x19\\x19\\x19\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xb4\\xb4\\xb4\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x08\\x08\\x08\\xff\\xe2\\xe2\\xe2\\xff\\xe6\\xe6\\xe6\\xff\\xcc\\xcc\\xcc\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xb4\\xb4\\xb4\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x08\\x08\\x08\\xff\\xe2\\xe2\\xe2\\xff\\xe6\\xe6\\xe6\\xff\\xcc\\xcc\\xcc\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xb4\\xb4\\xb4\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xba\\xba\\xba\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x19\\x19\\x19\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xb4\\xb4\\xb4\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x85\\x85\\x85\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x98\\x98\\x98\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xb4\\xb4\\xb4\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x19\\x19\\x19\\xff\\xd9\\xd9\\xd9\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x91\\x91\\x91\\xff\\x0f\\x0f\\x0f\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xb4\\xb4\\xb4\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xffZZZ\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe2\\xe2\\xe2\\xff\\xbc\\xbc\\xbc\\xff\\x9f\\x9f\\x9f\\xff\\x9f\\x9f\\x9f\\xff\\x9f\\x9f\\x9f\\xff\\xd7\\xd7\\xd7\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xffaaa\\xff\\xdc\\xdc\\xdc\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x1e\\x1e\\x1e\\xff\\x93\\x93\\x93\\xff\\xc6\\xc6\\xc6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\x1d\\x1d\\x1d\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x0e\\x0e\\x0e\\xff***\\xff+++\\xff+++\\xff\\xaf\\xaf\\xaf\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe2\\xe2\\xe2\\xff\\x10\\x10\\x10\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff@@@\\xff\\xd2\\xd2\\xd2\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe6\\xe6\\xe6\\xff\\xe1\\xe1\\xe1\\xff{{{\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa6\\xa6\\xa6\\xff\\x05\\x05\\x05\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x16\\x16\\x16\\xff\\x0c\\x0c\\x0c\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff\\xa6\\xa6\\xa6\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xbd\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff)))\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff)))\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xbd\\xa9\\xa9\\xa9\\x88\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x88\\x88\\x88\\xff\\x03\\x03\\x03\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x03\\x03\\x03\\xff\\x88\\x88\\x88\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\x88\\xaa\\xaa\\xaa\\x15\\xa9\\xa9\\xa9\\xeb\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x88\\x88\\x88\\xff)))\\xff\\x05\\x05\\x05\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff)))\\xff\\x88\\x88\\x88\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xeb\\xaa\\xaa\\xaa\\x15\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaaW\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa6\\xa6\\xa6\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\xa6\\xa6\\xa6\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xaa\\xaa\\xaaW\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaaW\\xa9\\xa9\\xa9\\xeb\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xeb\\xaa\\xaa\\xaaW\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaa\\x15\\xa9\\xa9\\xa9\\x88\\xa9\\xa9\\xa9\\xbd\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xbe\\xa9\\xa9\\xa9\\x88\\xaa\\xaa\\xaa\\x15\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00'\np13\ntp14\nb.", 'default.png': 'cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS\'b\'\np3\ntp4\nRp5\n(I1\n(I16\nI16\nI4\ntp6\ncnumpy\ndtype\np7\n(S\'u1\'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS\'|\'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS\'\\x00\\x7f\\xa6\\x1b\\x0c\\x8a\\xad\\xdc\\r\\x91\\xb0\\xf3\\r\\x91\\xb0\\xf3\\r\\x91\\xb0\\xf4\\r\\x91\\xb1\\xf4\\r\\x90\\xb0\\xf4\\x05\\x85\\xa9\\xef\\x00\\x7f\\xa6<\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\x00\\x7f\\xa6!\\x1d\\x9c\\xb9\\xf5g\\xd9\\xf1\\xffi\\xd9\\xf3\\xffd\\xd1\\xee\\xff]\\xcb\\xeb\\xff@\\xbb\\xe3\\xff\\x16\\x9c\\xc2\\xf8\\x00\\x7f\\xa6\\xb4\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\x00\\x7f\\xa6U\\\'\\xac\\xc5\\xf9i\\xd9\\xf3\\xffc\\xd3\\xef\\xff\\\\\\xcf\\xeb\\xffP\\xc8\\xe6\\xff\\x17\\x9f\\xc4\\xfd\\x00\\x7f\\xa6\\xfc\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\x02\\x83\\xa8lH\\xc5\\xdd\\xfah\\xdc\\xf3\\xffc\\xd4\\xef\\xffV\\xce\\xe9\\xffN\\xcf\\xe7\\xff&\\xaa\\xca\\xfd\\x00\\x7f\\xa6\\xff\\x03\\x81\\xc7\\x01\\x04\\x8d\\xda\\x01\\t\\x94\\xd9\\x01\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\x00\\x7f\\xa6"$\\xa9\\xc4\\xf7g\\xdf\\xf5\\xfff\\xdb\\xf3\\xffU\\xcd\\xeb\\xff\\x16\\xb3\\xda\\xff.\\xc9\\xe1\\xff(\\xb2\\xd0\\xfe\\x01\\x7f\\xa6\\xff\\x04\\x84\\xc9\\x05\\t\\x94\\xd9\\x06\\x10\\x9c\\xd7\\x01\\x16\\xa2\\xd6\\x01\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\x02\\x83\\xa9\\x81T\\xd3\\xeb\\xffg\\xe5\\xf7\\xffe\\xda\\xf3\\xff!\\xaa\\xde\\xff\\x11\\x9d\\xc3\\xfe\\x11\\xba\\xd7\\xff \\xb9\\xd5\\xfe\\x00\\x7f\\xa6\\xff\\x16u\\x8d\\x03\\x14\\x84\\xae\\x05\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\x10\\x92\\xb4\\xc0d\\xde\\xf3\\xffg\\xe5\\xf7\\xff_\\xcc\\xef\\xff\\x0e\\x9c\\xd5\\xff\\rx\\x95\\xf6\\x0e\\x89\\xab\\xf4\\x18\\xb2\\xd1\\xfc\\x00\\x7f\\xa6\\xff\\xff\\xff\\xff\\x00\\x1a~\\x91\\x01\\x1d\\xa5\\xce\\x01\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x005\\xa9\\xc3\\xefq\\xec\\xf9\\xffg\\xe5\\xf7\\xff>\\xb7\\xe8\\xff\\x14\\x96\\xc8\\xfe\\x02}\\xa3\\xb1\\x00\\x7f\\xa6Q\\x03\\x82\\xa9\\xe8\\x00\\x7f\\xa6\\xe9\\xff\\xff\\xff\\x00\\x00\\x7f\\xa6\\x11\\x1c\\x98\\xb8\\x04%\\xb5\\xd3\\x01\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00D\\xad\\xc8\\xf3r\\xec\\xf9\\xffg\\xe5\\xf7\\xff:\\xb7\\xe8\\xff\\x19\\x90\\xc5\\xfe\\x03{\\xa0\\xa6\\xff\\xff\\xff\\x00\\x00\\x7f\\xa6*\\x00\\x7f\\xa6*\\xff\\xff\\xff\\x00\\x00\\x7f\\xa6\\x98\\x0f\\x8f\\xb1\\x13&\\xb5\\xd3\\x04.\\xc0\\xd1\\x01\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\x19\\x93\\xb7\\xc6i\\xdf\\xf4\\xffg\\xe5\\xf7\\xffT\\xc8\\xee\\xff\\x06\\x88\\xcd\\xff\\x08g\\x85\\xf7\\x00\\x7f\\xa6\\x15\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\x00\\x7f\\xa6\\x1b\\x01\\x80\\xa7\\xeb\\x1d\\xa3\\xca\\x16#\\xb2\\xd4\\n*\\xbb\\xd2\\x04.\\xbc\\xd7\\x01\\xff\\xff\\xff\\x00\\x01\\x81\\xa7\\x88Y\\xd1\\xee\\xffg\\xe5\\xf7\\xfff\\xd9\\xf3\\xff\\\'\\xa2\\xe2\\xff\\x05e\\x99\\xf9\\x06~\\xa5\\xf3\\x01\\x81\\xa8\\x9c\\x01\\x80\\xa8\\x9f\\x04\\x85\\xad\\xef\\x08\\x8f\\xb9\\x92\\x17\\xa4\\xd6*\\x1e\\xac\\xd5\\x1a$\\xb3\\xd3\\x0c\\x19\\xa7\\xd5\\x02\\xff\\xff\\xff\\x00\\x00\\x7f\\xa6+!\\xa3\\xc8\\xf5i\\xe0\\xf5\\xffe\\xd9\\xf3\\xff\\\\\\xca\\xee\\xff\\x1f\\x9c\\xe0\\xfa\\x03\\x84\\xca\\xd6\\x07\\x8b\\xc5\\xca\\x06\\x88\\xc1\\xb8\\x08\\x8e\\xd0l\\x0b\\x96\\xd8I\\x11\\x9e\\xd74\\x17\\xa5\\xd6 \\xab\\xd7\\x0b\\x17\\xa2\\xdc\\x01\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\x01\\x80\\xa8~?\\xb9\\xe0\\xf9h\\xda\\xf3\\xff_\\xcc\\xef\\xffV\\xc1\\xec\\xfd3\\xa7\\xe3\\xe3\\x1a\\x96\\xde\\xae\\x04\\x8b\\xdb\\x89\\x00\\x89\\xdao\\x05\\x8f\\xd9T\\x0b\\x96\\xd8<\\x11\\x9b\\xd7\\x1d\\x18\\x95\\xc9\\x0c\\x00\\x80\\xd5\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\x00\\x7f\\xa6\\x04\\x03\\x83\\xaa\\xcd5\\xa2\\xc9\\xf9[\\xc6\\xea\\xffU\\xc1\\xec\\xffH\\xb4\\xe8\\xf39\\xa8\\xe4\\xc5\\x0b\\x8f\\xdc\\x9f\\x00\\x89\\xda{\\x00\\x89\\xda_\\x07\\x87\\xc4I\\x05|\\xa5s\\x05m\\xa3\\x02\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\x00\\x7f\\xa6\\x06\\x01\\x7f\\xa6\\x89\\x12x\\x9e\\xf63\\x88\\xae\\xfe6\\x93\\xc3\\xfe4\\x9d\\xd6\\xdf\\x08\\x82\\xc7\\xb8\\x03k\\xa2\\xab\\x04k\\x97\\xa8\\x02w\\x9e\\xeb\\x00\\x7f\\xa6j\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\x00\\x7f\\xa67\\x00~\\xa5\\x95\\x03v\\x9c\\xd4\\x03h\\x8c\\xfa\\x02i\\x8e\\xf9\\x01x\\x9f\\xcc\\x00\\x7f\\xa6\\x92\\x00\\x7f\\xa63\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\'\np13\ntp14\nb.', 'ctrl.png': "cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I32\nI32\nI4\ntp6\ncnumpy\ndtype\np7\n(S'u1'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS'\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xad\\xad\\xad\\x19\\xa8\\xa8\\xa8\\x8d\\xa9\\xa9\\xa9\\xc1\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xaa\\xaa\\xaa\\xc2\\xa9\\xa9\\xa9\\x8e\\xad\\xad\\xad\\x19\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xa8\\xa8\\xa8X\\xa9\\xa9\\xa9\\xed\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xed\\xa8\\xa8\\xa8X\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaaW\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa6\\xa6\\xa6\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\xa6\\xa6\\xa6\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xaa\\xaa\\xaaW\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaa\\x15\\xa9\\xa9\\xa9\\xeb\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x88\\x88\\x88\\xff)))\\xff\\x05\\x05\\x05\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff)))\\xff\\x88\\x88\\x88\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xeb\\xaa\\xaa\\xaa\\x15\\xa9\\xa9\\xa9\\x88\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x88\\x88\\x88\\xff\\x03\\x03\\x03\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x03\\x03\\x03\\xff\\x88\\x88\\x88\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\x88\\xa9\\xa9\\xa9\\xbe\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff)))\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff555\\xffPPP\\xff\\x13\\x13\\x13\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff)))\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xbe\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa6\\xa6\\xa6\\xff\\x05\\x05\\x05\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x01\\x01\\x01\\xff\\xb2\\xb2\\xb2\\xff\\xe3\\xe3\\xe3\\xff\\xd9\\xd9\\xd9\\xff]]]\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff\\xa6\\xa6\\xa6\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x13\\x13\\x13\\xff\\xbb\\xbb\\xbb\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xffFFF\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x13\\x13\\x13\\xff\\xbb\\xbb\\xbb\\xff\\xe3\\xe3\\xe3\\xff\\xc4\\xc4\\xc4\\xff\\x06\\x06\\x06\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff```\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff:::\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff666\\xff\\xaf\\xaf\\xaf\\xff\\x10\\x10\\x10\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9b\\x9b\\x9b\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff@@@\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xffSSS\\xff\\xe3\\xe3\\xe3\\xff\\xb7\\xb7\\xb7\\xff\\x10\\x10\\x10\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x04\\x04\\x04\\xff\\xd5\\xd5\\xd5\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xffXXX\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x17\\x17\\x17\\xff\\xdb\\xdb\\xdb\\xff\\xe3\\xe3\\xe3\\xff\\xb7\\xb7\\xb7\\xff[[[\\xff\\x97\\x97\\x97\\xff\\xd4\\xd4\\xd4\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xda\\xda\\xda\\xff;;;\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff```\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xda\\xda\\xda\\xff;;;\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xffHHH\\xff\\xc6\\xc6\\xc6\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xda\\xda\\xda\\xff;;;\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x07\\x07\\x07\\xff;;;\\xffAAA\\xff\\\\\\\\\\\\\\xff\\xdd\\xdd\\xdd\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xda\\xda\\xda\\xff;;;\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff@@@\\xff\\xdd\\xdd\\xdd\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xda\\xda\\xda\\xff;;;\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff@@@\\xff\\xdd\\xdd\\xdd\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xda\\xda\\xda\\xff;;;\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff@@@\\xff\\xdd\\xdd\\xdd\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xda\\xda\\xda\\xff;;;\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff@@@\\xff\\xdd\\xdd\\xdd\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xda\\xda\\xda\\xff;;;\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff@@@\\xff\\xdd\\xdd\\xdd\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xda\\xda\\xda\\xff;;;\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff@@@\\xff\\xdd\\xdd\\xdd\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xda\\xda\\xda\\xff;;;\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff@@@\\xff\\xdd\\xdd\\xdd\\xff\\xe3\\xe3\\xe3\\xff\\xe3\\xe3\\xe3\\xff\\xc7\\xc7\\xc7\\xffZZZ\\xff~~~\\xff\\xd9\\xd9\\xd9\\xff\\x10\\x10\\x10\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff@@@\\xff\\xdd\\xdd\\xdd\\xff\\xe3\\xe3\\xe3\\xffXXX\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xb0\\xb0\\xb0\\xfffff\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff@@@\\xff\\xdd\\xdd\\xdd\\xffyyy\\xff\\x00\\x00\\x00\\xff\\x06\\x06\\x06\\xff\\xcd\\xcd\\xcd\\xfffff\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa6\\xa6\\xa6\\xff\\x05\\x05\\x05\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff@@@\\xff\\xda\\xda\\xda\\xff\\xaf\\xaf\\xaf\\xff\\xcd\\xcd\\xcd\\xff\\xd7\\xd7\\xd7\\xff\\x10\\x10\\x10\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff\\xa6\\xa6\\xa6\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xbd\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff)))\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x12\\x12\\x12\\xffiii\\xffccc\\xff\\x0e\\x0e\\x0e\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff)))\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xbd\\xa9\\xa9\\xa9\\x88\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x88\\x88\\x88\\xff\\x03\\x03\\x03\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x03\\x03\\x03\\xff\\x88\\x88\\x88\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\x88\\xaa\\xaa\\xaa\\x15\\xa9\\xa9\\xa9\\xeb\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x88\\x88\\x88\\xff)))\\xff\\x05\\x05\\x05\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff)))\\xff\\x88\\x88\\x88\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xeb\\xaa\\xaa\\xaa\\x15\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaaW\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa6\\xa6\\xa6\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\xa6\\xa6\\xa6\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xaa\\xaa\\xaaW\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaaW\\xa9\\xa9\\xa9\\xeb\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xeb\\xaa\\xaa\\xaaW\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaa\\x15\\xa9\\xa9\\xa9\\x88\\xa9\\xa9\\xa9\\xbd\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xbe\\xa9\\xa9\\xa9\\x88\\xaa\\xaa\\xaa\\x15\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00'\np13\ntp14\nb.", 'auto.png': "cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I32\nI32\nI4\ntp6\ncnumpy\ndtype\np7\n(S'u1'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'|'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS'\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xad\\xad\\xad\\x19\\xa8\\xa8\\xa8\\x8d\\xa9\\xa9\\xa9\\xc1\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xaa\\xaa\\xaa\\xc2\\xa9\\xa9\\xa9\\x8e\\xad\\xad\\xad\\x19\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xa8\\xa8\\xa8X\\xa9\\xa9\\xa9\\xed\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xed\\xa8\\xa8\\xa8X\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaaW\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa6\\xa6\\xa6\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\xa6\\xa6\\xa6\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xaa\\xaa\\xaaW\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaa\\x15\\xa9\\xa9\\xa9\\xeb\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x88\\x88\\x88\\xff)))\\xff\\x05\\x05\\x05\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff)))\\xff\\x88\\x88\\x88\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xeb\\xaa\\xaa\\xaa\\x15\\xa9\\xa9\\xa9\\x88\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x88\\x88\\x88\\xff\\x03\\x03\\x03\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x19\\x19\\x19\\xff\\x03\\x03\\x03\\xff\\x88\\x88\\x88\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\x88\\xa9\\xa9\\xa9\\xbe\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff)))\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x04\\x04\\x04\\xffHHH\\xff\\xa4\\xa4\\xa4\\xff\\xe5\\xe5\\xe5\\xff\\x00\\x00\\x00\\xff)))\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xbe\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa6\\xa6\\xa6\\xff\\x05\\x05\\x05\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff \\xffyyy\\xff\\xd1\\xd1\\xd1\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff\\xa6\\xa6\\xa6\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x06\\x06\\x06\\xffPPP\\xff\\xab\\xab\\xab\\xff\\xe6\\xe6\\xe6\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff&&&\\xff\\x82\\x82\\x82\\xff\\xd6\\xd6\\xd6\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\t\\t\\t\\xffWWW\\xff\\xb2\\xb2\\xb2\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe5\\xe5\\xe5\\xff\\xa8\\xa8\\xa8\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff---\\xff\\x89\\x89\\x89\\xff\\xda\\xda\\xda\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xc1\\xc1\\xc1\\xfflll\\xff\\x18\\x18\\x18\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\r\\r\\r\\xff^^^\\xff\\xba\\xba\\xba\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xda\\xda\\xda\\xff...\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff555\\xff\\x90\\x90\\x90\\xff\\xde\\xde\\xde\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe2\\xe2\\xe2\\xff\\xe3\\xe3\\xe3\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xd2\\xd2\\xd2\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff;;;\\xff\\xc1\\xc1\\xc1\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xb7\\xb7\\xb7\\xffbbb\\xff\\x12\\x12\\x12\\xff\\xcb\\xcb\\xcb\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xd2\\xd2\\xd2\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xffmmm\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xcd\\xcd\\xcd\\xffyyy\\xff$$$\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xcb\\xcb\\xcb\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xd2\\xd2\\xd2\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xffmmm\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe3\\xe3\\xe3\\xff\\x91\\x91\\x91\\xff<<<\\xff\\x01\\x01\\x01\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xcb\\xcb\\xcb\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xd2\\xd2\\xd2\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xffmmm\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xc3\\xc3\\xc3\\xfflll\\xff\\x18\\x18\\x18\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xcb\\xcb\\xcb\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xd2\\xd2\\xd2\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xffmmm\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe4\\xe4\\xe4\\xff\\xa6\\xa6\\xa6\\xffOOO\\xff\\x07\\x07\\x07\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\xcb\\xcb\\xcb\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xd2\\xd2\\xd2\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff555\\xff\\xb4\\xb4\\xb4\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xd9\\xd9\\xd9\\xff\\x8a\\x8a\\x8a\\xff333\\xff\\xcb\\xcb\\xcb\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xd2\\xd2\\xd2\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff+++\\xff\\x88\\x88\\x88\\xff\\xda\\xda\\xda\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xd2\\xd2\\xd2\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\n\\n\\n\\xff[[[\\xff\\xb8\\xb8\\xb8\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xdc\\xdc\\xdc\\xffAAA\\xff\\x02\\x02\\x02\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff...\\xff\\x8c\\x8c\\x8c\\xff\\xdc\\xdc\\xdc\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xcc\\xcc\\xcc\\xffsss\\xff\\x1a\\x1a\\x1a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x0c\\x0c\\x0c\\xff___\\xff\\xbc\\xbc\\xbc\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe5\\xe5\\xe5\\xff\\xa5\\xa5\\xa5\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff222\\xff\\x8f\\x8f\\x8f\\xff\\xde\\xde\\xde\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x9a\\x9a\\x9a\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x0e\\x0e\\x0e\\xffccc\\xff\\xc0\\xc0\\xc0\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x9a\\x9a\\x9a\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa6\\xa6\\xa6\\xff\\x05\\x05\\x05\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff555\\xff\\x94\\x94\\x94\\xff\\xe0\\xe0\\xe0\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\xe7\\xe7\\xe7\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff\\xa6\\xa6\\xa6\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xbd\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff)))\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x10\\x10\\x10\\xfffff\\xff\\xc4\\xc4\\xc4\\xff\\xe7\\xe7\\xe7\\xff\\x00\\x00\\x00\\xff)))\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xbd\\xa9\\xa9\\xa9\\x88\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x88\\x88\\x88\\xff\\x03\\x03\\x03\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff:::\\xff\\x03\\x03\\x03\\xff\\x88\\x88\\x88\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\x88\\xaa\\xaa\\xaa\\x15\\xa9\\xa9\\xa9\\xeb\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\x88\\x88\\x88\\xff)))\\xff\\x05\\x05\\x05\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x00\\x00\\x00\\xff\\x05\\x05\\x05\\xff)))\\xff\\x88\\x88\\x88\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xeb\\xaa\\xaa\\xaa\\x15\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaaW\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa6\\xa6\\xa6\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\x9a\\x9a\\x9a\\xff\\xa6\\xa6\\xa6\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xaa\\xaa\\xaaW\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaaW\\xa9\\xa9\\xa9\\xeb\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xeb\\xaa\\xaa\\xaaW\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xaa\\xaa\\xaa\\x15\\xa9\\xa9\\xa9\\x88\\xa9\\xa9\\xa9\\xbd\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xff\\xa9\\xa9\\xa9\\xf1\\xa9\\xa9\\xa9\\xbe\\xa9\\xa9\\xa9\\x88\\xaa\\xaa\\xaa\\x15\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\x00'\np13\ntp14\nb."}
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/pixmaps/pixmapData_3.py
.py
53,111
1
import numpy as np; pixmapData={'lock.png': b'\x80\x03cnumpy.core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02C\x01bq\x03\x87q\x04Rq\x05(K\x01K K K\x04\x87q\x06cnumpy\ndtype\nq\x07X\x02\x00\x00\x00u1q\x08K\x00K\x01\x87q\tRq\n(K\x03X\x01\x00\x00\x00|q\x0bNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x0cb\x89B\x00\x10\x00\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xad\xad\xad\x19\xa8\xa8\xa8\x8d\xa9\xa9\xa9\xc1\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xaa\xaa\xaa\xc2\xa9\xa9\xa9\x8e\xad\xad\xad\x19\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xa8\xa8\xa8X\xa9\xa9\xa9\xed\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xed\xa8\xa8\xa8X\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xaa\xaa\xaaW\xff\xff\xff\x00\xaa\xaa\xaa\x15\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff)))\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff)))\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaa\x15\xa9\xa9\xa9\x88\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff\x03\x03\x03\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x03\x03\x03\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\x88\xa9\xa9\xa9\xbe\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff)))\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff)))\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xbe\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x0c\x0c\x0c\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xd2\xd2\xd2\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe1\xe1\xe1\xff{{{\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x0e\x0e\x0e\xff***\xff+++\xff+++\xff\xaf\xaf\xaf\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe2\xe2\xe2\xff\x10\x10\x10\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x1e\x1e\x1e\xff\x93\x93\x93\xff\xc6\xc6\xc6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xffaaa\xff\xdc\xdc\xdc\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\\\\\\\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe2\xe2\xe2\xff\xbb\xbb\xbb\xff\x9f\x9f\x9f\xff\x9f\x9f\x9f\xff\x9f\x9f\x9f\xff\xd7\xd7\xd7\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x1c\x1c\x1c\xff\xda\xda\xda\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x91\x91\x91\xff\x0f\x0f\x0f\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x87\x87\x87\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x98\x98\x98\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\xba\xba\xba\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x19\x19\x19\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x08\x08\x08\xff\xe2\xe2\xe2\xff\xe6\xe6\xe6\xff\xcc\xcc\xcc\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x08\x08\x08\xff\xe2\xe2\xe2\xff\xe6\xe6\xe6\xff\xcc\xcc\xcc\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\xba\xba\xba\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x19\x19\x19\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x85\x85\x85\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x98\x98\x98\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x19\x19\x19\xff\xd9\xd9\xd9\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x91\x91\x91\xff\x0f\x0f\x0f\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb4\xb4\xb4\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xffZZZ\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe2\xe2\xe2\xff\xbc\xbc\xbc\xff\x9f\x9f\x9f\xff\x9f\x9f\x9f\xff\x9f\x9f\x9f\xff\xd7\xd7\xd7\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xffaaa\xff\xdc\xdc\xdc\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x1e\x1e\x1e\xff\x93\x93\x93\xff\xc6\xc6\xc6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\x1d\x1d\x1d\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x0e\x0e\x0e\xff***\xff+++\xff+++\xff\xaf\xaf\xaf\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe2\xe2\xe2\xff\x10\x10\x10\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xd2\xd2\xd2\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe6\xe6\xe6\xff\xe1\xe1\xe1\xff{{{\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x16\x16\x16\xff\x0c\x0c\x0c\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xbd\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff)))\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff)))\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xbd\xa9\xa9\xa9\x88\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff\x03\x03\x03\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x03\x03\x03\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\x88\xaa\xaa\xaa\x15\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff)))\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff)))\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaa\x15\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xaa\xaa\xaaW\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaaW\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaa\x15\xa9\xa9\xa9\x88\xa9\xa9\xa9\xbd\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xbe\xa9\xa9\xa9\x88\xaa\xaa\xaa\x15\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00q\rtq\x0eb.', 'default.png': b'\x80\x03cnumpy.core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02C\x01bq\x03\x87q\x04Rq\x05(K\x01K\x10K\x10K\x04\x87q\x06cnumpy\ndtype\nq\x07X\x02\x00\x00\x00u1q\x08K\x00K\x01\x87q\tRq\n(K\x03X\x01\x00\x00\x00|q\x0bNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x0cb\x89B\x00\x04\x00\x00\x00\x7f\xa6\x1b\x0c\x8a\xad\xdc\r\x91\xb0\xf3\r\x91\xb0\xf3\r\x91\xb0\xf4\r\x91\xb1\xf4\r\x90\xb0\xf4\x05\x85\xa9\xef\x00\x7f\xa6<\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa6!\x1d\x9c\xb9\xf5g\xd9\xf1\xffi\xd9\xf3\xffd\xd1\xee\xff]\xcb\xeb\xff@\xbb\xe3\xff\x16\x9c\xc2\xf8\x00\x7f\xa6\xb4\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa6U\'\xac\xc5\xf9i\xd9\xf3\xffc\xd3\xef\xff\\\xcf\xeb\xffP\xc8\xe6\xff\x17\x9f\xc4\xfd\x00\x7f\xa6\xfc\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x02\x83\xa8lH\xc5\xdd\xfah\xdc\xf3\xffc\xd4\xef\xffV\xce\xe9\xffN\xcf\xe7\xff&\xaa\xca\xfd\x00\x7f\xa6\xff\x03\x81\xc7\x01\x04\x8d\xda\x01\t\x94\xd9\x01\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa6"$\xa9\xc4\xf7g\xdf\xf5\xfff\xdb\xf3\xffU\xcd\xeb\xff\x16\xb3\xda\xff.\xc9\xe1\xff(\xb2\xd0\xfe\x01\x7f\xa6\xff\x04\x84\xc9\x05\t\x94\xd9\x06\x10\x9c\xd7\x01\x16\xa2\xd6\x01\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x02\x83\xa9\x81T\xd3\xeb\xffg\xe5\xf7\xffe\xda\xf3\xff!\xaa\xde\xff\x11\x9d\xc3\xfe\x11\xba\xd7\xff \xb9\xd5\xfe\x00\x7f\xa6\xff\x16u\x8d\x03\x14\x84\xae\x05\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x10\x92\xb4\xc0d\xde\xf3\xffg\xe5\xf7\xff_\xcc\xef\xff\x0e\x9c\xd5\xff\rx\x95\xf6\x0e\x89\xab\xf4\x18\xb2\xd1\xfc\x00\x7f\xa6\xff\xff\xff\xff\x00\x1a~\x91\x01\x1d\xa5\xce\x01\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x005\xa9\xc3\xefq\xec\xf9\xffg\xe5\xf7\xff>\xb7\xe8\xff\x14\x96\xc8\xfe\x02}\xa3\xb1\x00\x7f\xa6Q\x03\x82\xa9\xe8\x00\x7f\xa6\xe9\xff\xff\xff\x00\x00\x7f\xa6\x11\x1c\x98\xb8\x04%\xb5\xd3\x01\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00D\xad\xc8\xf3r\xec\xf9\xffg\xe5\xf7\xff:\xb7\xe8\xff\x19\x90\xc5\xfe\x03{\xa0\xa6\xff\xff\xff\x00\x00\x7f\xa6*\x00\x7f\xa6*\xff\xff\xff\x00\x00\x7f\xa6\x98\x0f\x8f\xb1\x13&\xb5\xd3\x04.\xc0\xd1\x01\xff\xff\xff\x00\xff\xff\xff\x00\x19\x93\xb7\xc6i\xdf\xf4\xffg\xe5\xf7\xffT\xc8\xee\xff\x06\x88\xcd\xff\x08g\x85\xf7\x00\x7f\xa6\x15\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa6\x1b\x01\x80\xa7\xeb\x1d\xa3\xca\x16#\xb2\xd4\n*\xbb\xd2\x04.\xbc\xd7\x01\xff\xff\xff\x00\x01\x81\xa7\x88Y\xd1\xee\xffg\xe5\xf7\xfff\xd9\xf3\xff\'\xa2\xe2\xff\x05e\x99\xf9\x06~\xa5\xf3\x01\x81\xa8\x9c\x01\x80\xa8\x9f\x04\x85\xad\xef\x08\x8f\xb9\x92\x17\xa4\xd6*\x1e\xac\xd5\x1a$\xb3\xd3\x0c\x19\xa7\xd5\x02\xff\xff\xff\x00\x00\x7f\xa6+!\xa3\xc8\xf5i\xe0\xf5\xffe\xd9\xf3\xff\\\xca\xee\xff\x1f\x9c\xe0\xfa\x03\x84\xca\xd6\x07\x8b\xc5\xca\x06\x88\xc1\xb8\x08\x8e\xd0l\x0b\x96\xd8I\x11\x9e\xd74\x17\xa5\xd6 \xab\xd7\x0b\x17\xa2\xdc\x01\xff\xff\xff\x00\xff\xff\xff\x00\x01\x80\xa8~?\xb9\xe0\xf9h\xda\xf3\xff_\xcc\xef\xffV\xc1\xec\xfd3\xa7\xe3\xe3\x1a\x96\xde\xae\x04\x8b\xdb\x89\x00\x89\xdao\x05\x8f\xd9T\x0b\x96\xd8<\x11\x9b\xd7\x1d\x18\x95\xc9\x0c\x00\x80\xd5\x00\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa6\x04\x03\x83\xaa\xcd5\xa2\xc9\xf9[\xc6\xea\xffU\xc1\xec\xffH\xb4\xe8\xf39\xa8\xe4\xc5\x0b\x8f\xdc\x9f\x00\x89\xda{\x00\x89\xda_\x07\x87\xc4I\x05|\xa5s\x05m\xa3\x02\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa6\x06\x01\x7f\xa6\x89\x12x\x9e\xf63\x88\xae\xfe6\x93\xc3\xfe4\x9d\xd6\xdf\x08\x82\xc7\xb8\x03k\xa2\xab\x04k\x97\xa8\x02w\x9e\xeb\x00\x7f\xa6j\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\x00\x7f\xa67\x00~\xa5\x95\x03v\x9c\xd4\x03h\x8c\xfa\x02i\x8e\xf9\x01x\x9f\xcc\x00\x7f\xa6\x92\x00\x7f\xa63\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00q\rtq\x0eb.', 'ctrl.png': b'\x80\x03cnumpy.core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02C\x01bq\x03\x87q\x04Rq\x05(K\x01K K K\x04\x87q\x06cnumpy\ndtype\nq\x07X\x02\x00\x00\x00u1q\x08K\x00K\x01\x87q\tRq\n(K\x03X\x01\x00\x00\x00|q\x0bNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x0cb\x89B\x00\x10\x00\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xad\xad\xad\x19\xa8\xa8\xa8\x8d\xa9\xa9\xa9\xc1\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xaa\xaa\xaa\xc2\xa9\xa9\xa9\x8e\xad\xad\xad\x19\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xa8\xa8\xa8X\xa9\xa9\xa9\xed\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xed\xa8\xa8\xa8X\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xaa\xaa\xaaW\xff\xff\xff\x00\xaa\xaa\xaa\x15\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff)))\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff)))\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaa\x15\xa9\xa9\xa9\x88\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff\x03\x03\x03\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x03\x03\x03\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\x88\xa9\xa9\xa9\xbe\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff)))\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff555\xffPPP\xff\x13\x13\x13\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff)))\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xbe\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x01\x01\x01\xff\xb2\xb2\xb2\xff\xe3\xe3\xe3\xff\xd9\xd9\xd9\xff]]]\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x13\x13\x13\xff\xbb\xbb\xbb\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xffFFF\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x13\x13\x13\xff\xbb\xbb\xbb\xff\xe3\xe3\xe3\xff\xc4\xc4\xc4\xff\x06\x06\x06\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff```\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff:::\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff666\xff\xaf\xaf\xaf\xff\x10\x10\x10\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9b\x9b\x9b\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff@@@\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xffSSS\xff\xe3\xe3\xe3\xff\xb7\xb7\xb7\xff\x10\x10\x10\xff\x00\x00\x00\xff\x00\x00\x00\xff\x04\x04\x04\xff\xd5\xd5\xd5\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xffXXX\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x17\x17\x17\xff\xdb\xdb\xdb\xff\xe3\xe3\xe3\xff\xb7\xb7\xb7\xff[[[\xff\x97\x97\x97\xff\xd4\xd4\xd4\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff```\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xffHHH\xff\xc6\xc6\xc6\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x07\x07\x07\xff;;;\xffAAA\xff\\\\\\\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xda\xda\xda\xff;;;\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xff\xe3\xe3\xe3\xff\xc7\xc7\xc7\xffZZZ\xff~~~\xff\xd9\xd9\xd9\xff\x10\x10\x10\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xff\xe3\xe3\xe3\xffXXX\xff\x00\x00\x00\xff\x00\x00\x00\xff\xb0\xb0\xb0\xfffff\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xdd\xdd\xdd\xffyyy\xff\x00\x00\x00\xff\x06\x06\x06\xff\xcd\xcd\xcd\xfffff\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff@@@\xff\xda\xda\xda\xff\xaf\xaf\xaf\xff\xcd\xcd\xcd\xff\xd7\xd7\xd7\xff\x10\x10\x10\xff\x00\x00\x00\xff\x05\x05\x05\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xbd\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff)))\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x12\x12\x12\xffiii\xffccc\xff\x0e\x0e\x0e\xff\x00\x00\x00\xff\x00\x00\x00\xff)))\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xbd\xa9\xa9\xa9\x88\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff\x03\x03\x03\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x03\x03\x03\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\x88\xaa\xaa\xaa\x15\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff)))\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff)))\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaa\x15\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xaa\xaa\xaaW\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaaW\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaa\x15\xa9\xa9\xa9\x88\xa9\xa9\xa9\xbd\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xbe\xa9\xa9\xa9\x88\xaa\xaa\xaa\x15\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00q\rtq\x0eb.', 'auto.png': b'\x80\x03cnumpy.core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02C\x01bq\x03\x87q\x04Rq\x05(K\x01K K K\x04\x87q\x06cnumpy\ndtype\nq\x07X\x02\x00\x00\x00u1q\x08K\x00K\x01\x87q\tRq\n(K\x03X\x01\x00\x00\x00|q\x0bNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x0cb\x89B\x00\x10\x00\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xad\xad\xad\x19\xa8\xa8\xa8\x8d\xa9\xa9\xa9\xc1\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xaa\xaa\xaa\xc2\xa9\xa9\xa9\x8e\xad\xad\xad\x19\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xa8\xa8\xa8X\xa9\xa9\xa9\xed\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xed\xa8\xa8\xa8X\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xaa\xaa\xaaW\xff\xff\xff\x00\xaa\xaa\xaa\x15\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff)))\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff)))\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaa\x15\xa9\xa9\xa9\x88\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff\x03\x03\x03\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x19\x19\x19\xff\x03\x03\x03\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\x88\xa9\xa9\xa9\xbe\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff)))\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x04\x04\x04\xffHHH\xff\xa4\xa4\xa4\xff\xe5\xe5\xe5\xff\x00\x00\x00\xff)))\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xbe\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff \xffyyy\xff\xd1\xd1\xd1\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff\x05\x05\x05\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x06\x06\x06\xffPPP\xff\xab\xab\xab\xff\xe6\xe6\xe6\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff&&&\xff\x82\x82\x82\xff\xd6\xd6\xd6\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\t\t\t\xffWWW\xff\xb2\xb2\xb2\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe5\xe5\xe5\xff\xa8\xa8\xa8\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff---\xff\x89\x89\x89\xff\xda\xda\xda\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xc1\xc1\xc1\xfflll\xff\x18\x18\x18\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\r\r\r\xff^^^\xff\xba\xba\xba\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xda\xda\xda\xff...\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff555\xff\x90\x90\x90\xff\xde\xde\xde\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe2\xe2\xe2\xff\xe3\xe3\xe3\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff;;;\xff\xc1\xc1\xc1\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xb7\xb7\xb7\xffbbb\xff\x12\x12\x12\xff\xcb\xcb\xcb\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xffmmm\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xcd\xcd\xcd\xffyyy\xff$$$\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xcb\xcb\xcb\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xffmmm\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe3\xe3\xe3\xff\x91\x91\x91\xff<<<\xff\x01\x01\x01\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xcb\xcb\xcb\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xffmmm\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xc3\xc3\xc3\xfflll\xff\x18\x18\x18\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\xcb\xcb\xcb\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xffmmm\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe4\xe4\xe4\xff\xa6\xa6\xa6\xffOOO\xff\x07\x07\x07\xff\x00\x00\x00\xff\x00\x00\x00\xff\xcb\xcb\xcb\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff555\xff\xb4\xb4\xb4\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd9\xd9\xd9\xff\x8a\x8a\x8a\xff333\xff\xcb\xcb\xcb\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff+++\xff\x88\x88\x88\xff\xda\xda\xda\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xd2\xd2\xd2\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\n\n\n\xff[[[\xff\xb8\xb8\xb8\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xdc\xdc\xdc\xffAAA\xff\x02\x02\x02\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff...\xff\x8c\x8c\x8c\xff\xdc\xdc\xdc\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xcc\xcc\xcc\xffsss\xff\x1a\x1a\x1a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x0c\x0c\x0c\xff___\xff\xbc\xbc\xbc\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe5\xe5\xe5\xff\xa5\xa5\xa5\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff222\xff\x8f\x8f\x8f\xff\xde\xde\xde\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x9a\x9a\x9a\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x0e\x0e\x0e\xffccc\xff\xc0\xc0\xc0\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff\x00\x00\x00\xff\x9a\x9a\x9a\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff555\xff\x94\x94\x94\xff\xe0\xe0\xe0\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff\x05\x05\x05\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xbd\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff)))\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x10\x10\x10\xfffff\xff\xc4\xc4\xc4\xff\xe7\xe7\xe7\xff\x00\x00\x00\xff)))\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xbd\xa9\xa9\xa9\x88\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff\x03\x03\x03\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff:::\xff\x03\x03\x03\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\x88\xaa\xaa\xaa\x15\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\x88\x88\x88\xff)))\xff\x05\x05\x05\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x05\x05\x05\xff)))\xff\x88\x88\x88\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaa\x15\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa6\xa6\xa6\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\x9a\x9a\x9a\xff\xa6\xa6\xa6\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xaa\xaa\xaaW\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaaW\xa9\xa9\xa9\xeb\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xeb\xaa\xaa\xaaW\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00\xaa\xaa\xaa\x15\xa9\xa9\xa9\x88\xa9\xa9\xa9\xbd\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xff\xa9\xa9\xa9\xf1\xa9\xa9\xa9\xbe\xa9\xa9\xa9\x88\xaa\xaa\xaa\x15\xff\xff\xff\x00\xff\xff\xff\x00\xff\xff\xff\x00q\rtq\x0eb.'}
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/parametertree/__init__.py
.py
234
5
from .Parameter import Parameter, registerParameterType from .ParameterTree import ParameterTree from .ParameterItem import ParameterItem from .ParameterSystem import ParameterSystem, SystemSolver from . import parameterTypes as types
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/parametertree/Parameter.py
.py
32,590
779
from ..Qt import QtGui, QtCore import os, weakref, re from ..pgcollections import OrderedDict from ..python2_3 import asUnicode, basestring from .ParameterItem import ParameterItem PARAM_TYPES = {} PARAM_NAMES = {} def registerParameterType(name, cls, override=False): global PARAM_TYPES if name in PARAM_TYPES and not override: raise Exception("Parameter type '%s' already exists (use override=True to replace)" % name) PARAM_TYPES[name] = cls PARAM_NAMES[cls] = name def __reload__(old): PARAM_TYPES.update(old.get('PARAM_TYPES', {})) PARAM_NAMES.update(old.get('PARAM_NAMES', {})) class Parameter(QtCore.QObject): """ A Parameter is the basic unit of data in a parameter tree. Each parameter has a name, a type, a value, and several other properties that modify the behavior of the Parameter. Parameters may have parent / child / sibling relationships to construct organized hierarchies. Parameters generally do not have any inherent GUI or visual interpretation; instead they manage ParameterItem instances which take care of display and user interaction. Note: It is fairly uncommon to use the Parameter class directly; mostly you will use subclasses which provide specialized type and data handling. The static pethod Parameter.create(...) is an easy way to generate instances of these subclasses. For more Parameter types, see ParameterTree.parameterTypes module. =================================== ========================================================= **Signals:** sigStateChanged(self, change, info) Emitted when anything changes about this parameter at all. The second argument is a string indicating what changed ('value', 'childAdded', etc..) The third argument can be any extra information about the change sigTreeStateChanged(self, changes) Emitted when any child in the tree changes state (but only if monitorChildren() is called) the format of *changes* is [(param, change, info), ...] sigValueChanged(self, value) Emitted when value is finished changing sigValueChanging(self, value) Emitted immediately for all value changes, including during editing. sigChildAdded(self, child, index) Emitted when a child is added sigChildRemoved(self, child) Emitted when a child is removed sigRemoved(self) Emitted when this parameter is removed sigParentChanged(self, parent) Emitted when this parameter's parent has changed sigLimitsChanged(self, limits) Emitted when this parameter's limits have changed sigDefaultChanged(self, default) Emitted when this parameter's default value has changed sigNameChanged(self, name) Emitted when this parameter's name has changed sigOptionsChanged(self, opts) Emitted when any of this parameter's options have changed =================================== ========================================================= """ ## name, type, limits, etc. ## can also carry UI hints (slider vs spinbox, etc.) sigValueChanged = QtCore.Signal(object, object) ## self, value emitted when value is finished being edited sigValueChanging = QtCore.Signal(object, object) ## self, value emitted as value is being edited sigChildAdded = QtCore.Signal(object, object, object) ## self, child, index sigChildRemoved = QtCore.Signal(object, object) ## self, child sigRemoved = QtCore.Signal(object) ## self sigParentChanged = QtCore.Signal(object, object) ## self, parent sigLimitsChanged = QtCore.Signal(object, object) ## self, limits sigDefaultChanged = QtCore.Signal(object, object) ## self, default sigNameChanged = QtCore.Signal(object, object) ## self, name sigOptionsChanged = QtCore.Signal(object, object) ## self, {opt:val, ...} ## Emitted when anything changes about this parameter at all. ## The second argument is a string indicating what changed ('value', 'childAdded', etc..) ## The third argument can be any extra information about the change sigStateChanged = QtCore.Signal(object, object, object) ## self, change, info ## emitted when any child in the tree changes state ## (but only if monitorChildren() is called) sigTreeStateChanged = QtCore.Signal(object, object) # self, changes # changes = [(param, change, info), ...] # bad planning. #def __new__(cls, *args, **opts): #try: #cls = PARAM_TYPES[opts['type']] #except KeyError: #pass #return QtCore.QObject.__new__(cls, *args, **opts) @staticmethod def create(**opts): """ Static method that creates a new Parameter (or subclass) instance using opts['type'] to select the appropriate class. All options are passed directly to the new Parameter's __init__ method. Use registerParameterType() to add new class types. """ typ = opts.get('type', None) if typ is None: cls = Parameter else: cls = PARAM_TYPES[opts['type']] return cls(**opts) def __init__(self, **opts): """ Initialize a Parameter object. Although it is rare to directly create a Parameter instance, the options available to this method are also allowed by most Parameter subclasses. ======================= ========================================================= **Keyword Arguments:** name The name to give this Parameter. This is the name that will appear in the left-most column of a ParameterTree for this Parameter. value The value to initially assign to this Parameter. default The default value for this Parameter (most Parameters provide an option to 'reset to default'). children A list of children for this Parameter. Children may be given either as a Parameter instance or as a dictionary to pass to Parameter.create(). In this way, it is possible to specify complex hierarchies of Parameters from a single nested data structure. readonly If True, the user will not be allowed to edit this Parameter. (default=False) enabled If False, any widget(s) for this parameter will appear disabled. (default=True) visible If False, the Parameter will not appear when displayed in a ParameterTree. (default=True) renamable If True, the user may rename this Parameter. (default=False) removable If True, the user may remove this Parameter. (default=False) expanded If True, the Parameter will appear expanded when displayed in a ParameterTree (its children will be visible). (default=True) title (str or None) If specified, then the parameter will be displayed to the user using this string as its name. However, the parameter will still be referred to internally using the *name* specified above. Note that this option is not compatible with renamable=True. (default=None; added in version 0.9.9) ======================= ========================================================= """ QtCore.QObject.__init__(self) self.opts = { 'type': None, 'readonly': False, 'visible': True, 'enabled': True, 'renamable': False, 'removable': False, 'strictNaming': False, # forces name to be usable as a python variable 'expanded': True, 'title': None, #'limits': None, ## This is a bad plan--each parameter type may have a different data type for limits. } value = opts.get('value', None) name = opts.get('name', None) self.opts.update(opts) self.opts['value'] = None # will be set later. self.opts['name'] = None self.childs = [] self.names = {} ## map name:child self.items = weakref.WeakKeyDictionary() ## keeps track of tree items representing this parameter self._parent = None self.treeStateChanges = [] ## cache of tree state changes to be delivered on next emit self.blockTreeChangeEmit = 0 #self.monitoringChildren = False ## prevent calling monitorChildren more than once if not isinstance(name, basestring): raise Exception("Parameter must have a string name specified in opts.") self.setName(name) self.addChildren(self.opts.pop('children', [])) self.opts['value'] = None if value is not None: self.setValue(value) if 'default' not in self.opts: self.opts['default'] = None self.setDefault(self.opts['value']) ## Connect all state changed signals to the general sigStateChanged self.sigValueChanged.connect(lambda param, data: self.emitStateChanged('value', data)) self.sigChildAdded.connect(lambda param, *data: self.emitStateChanged('childAdded', data)) self.sigChildRemoved.connect(lambda param, data: self.emitStateChanged('childRemoved', data)) self.sigParentChanged.connect(lambda param, data: self.emitStateChanged('parent', data)) self.sigLimitsChanged.connect(lambda param, data: self.emitStateChanged('limits', data)) self.sigDefaultChanged.connect(lambda param, data: self.emitStateChanged('default', data)) self.sigNameChanged.connect(lambda param, data: self.emitStateChanged('name', data)) self.sigOptionsChanged.connect(lambda param, data: self.emitStateChanged('options', data)) #self.watchParam(self) ## emit treechange signals if our own state changes def name(self): """Return the name of this Parameter.""" return self.opts['name'] def setName(self, name): """Attempt to change the name of this parameter; return the actual name. (The parameter may reject the name change or automatically pick a different name)""" if self.opts['strictNaming']: if len(name) < 1 or re.search(r'\W', name) or re.match(r'\d', name[0]): raise Exception("Parameter name '%s' is invalid. (Must contain only alphanumeric and underscore characters and may not start with a number)" % name) parent = self.parent() if parent is not None: name = parent._renameChild(self, name) ## first ask parent if it's ok to rename if self.opts['name'] != name: self.opts['name'] = name self.sigNameChanged.emit(self, name) return name def type(self): """Return the type string for this Parameter.""" return self.opts['type'] def isType(self, typ): """ Return True if this parameter type matches the name *typ*. This can occur either of two ways: - If self.type() == *typ* - If this parameter's class is registered with the name *typ* """ if self.type() == typ: return True global PARAM_TYPES cls = PARAM_TYPES.get(typ, None) if cls is None: raise Exception("Type name '%s' is not registered." % str(typ)) return self.__class__ is cls def childPath(self, child): """ Return the path of parameter names from self to child. If child is not a (grand)child of self, return None. """ path = [] while child is not self: path.insert(0, child.name()) child = child.parent() if child is None: return None return path def setValue(self, value, blockSignal=None): """ Set the value of this Parameter; return the actual value that was set. (this may be different from the value that was requested) """ try: if blockSignal is not None: self.sigValueChanged.disconnect(blockSignal) value = self._interpretValue(value) if self.opts['value'] == value: return value self.opts['value'] = value self.sigValueChanged.emit(self, value) finally: if blockSignal is not None: self.sigValueChanged.connect(blockSignal) return value def _interpretValue(self, v): return v def value(self): """ Return the value of this Parameter. """ return self.opts['value'] def getValues(self): """Return a tree of all values that are children of this parameter""" vals = OrderedDict() for ch in self: vals[ch.name()] = (ch.value(), ch.getValues()) return vals def saveState(self, filter=None): """ Return a structure representing the entire state of the parameter tree. The tree state may be restored from this structure using restoreState(). If *filter* is set to 'user', then only user-settable data will be included in the returned state. """ if filter is None: state = self.opts.copy() if state['type'] is None: global PARAM_NAMES state['type'] = PARAM_NAMES.get(type(self), None) elif filter == 'user': state = {'value': self.value()} else: raise ValueError("Unrecognized filter argument: '%s'" % filter) ch = OrderedDict([(ch.name(), ch.saveState(filter=filter)) for ch in self]) if len(ch) > 0: state['children'] = ch return state def restoreState(self, state, recursive=True, addChildren=True, removeChildren=True, blockSignals=True): """ Restore the state of this parameter and its children from a structure generated using saveState() If recursive is True, then attempt to restore the state of child parameters as well. If addChildren is True, then any children which are referenced in the state object will be created if they do not already exist. If removeChildren is True, then any children which are not referenced in the state object will be removed. If blockSignals is True, no signals will be emitted until the tree has been completely restored. This prevents signal handlers from responding to a partially-rebuilt network. """ state = state.copy() childState = state.pop('children', []) ## list of children may be stored either as list or dict. if isinstance(childState, dict): cs = [] for k,v in childState.items(): cs.append(v.copy()) cs[-1].setdefault('name', k) childState = cs if blockSignals: self.blockTreeChangeSignal() try: self.setOpts(**state) if not recursive: return ptr = 0 ## pointer to first child that has not been restored yet foundChilds = set() #print "==============", self.name() for ch in childState: name = ch['name'] #typ = ch.get('type', None) #print('child: %s, %s' % (self.name()+'.'+name, typ)) ## First, see if there is already a child with this name gotChild = False for i, ch2 in enumerate(self.childs[ptr:]): #print " ", ch2.name(), ch2.type() if ch2.name() != name: # or not ch2.isType(typ): continue gotChild = True #print " found it" if i != 0: ## move parameter to next position #self.removeChild(ch2) self.insertChild(ptr, ch2) #print " moved to position", ptr ch2.restoreState(ch, recursive=recursive, addChildren=addChildren, removeChildren=removeChildren) foundChilds.add(ch2) break if not gotChild: if not addChildren: #print " ignored child" continue #print " created new" ch2 = Parameter.create(**ch) self.insertChild(ptr, ch2) foundChilds.add(ch2) ptr += 1 if removeChildren: for ch in self.childs[:]: if ch not in foundChilds: #print " remove:", ch self.removeChild(ch) finally: if blockSignals: self.unblockTreeChangeSignal() def defaultValue(self): """Return the default value for this parameter.""" return self.opts['default'] def setDefault(self, val): """Set the default value for this parameter.""" if self.opts['default'] == val: return self.opts['default'] = val self.sigDefaultChanged.emit(self, val) def setToDefault(self): """Set this parameter's value to the default.""" if self.hasDefault(): self.setValue(self.defaultValue()) def hasDefault(self): """Returns True if this parameter has a default value.""" return 'default' in self.opts def valueIsDefault(self): """Returns True if this parameter's value is equal to the default value.""" return self.value() == self.defaultValue() def setLimits(self, limits): """Set limits on the acceptable values for this parameter. The format of limits depends on the type of the parameter and some parameters do not make use of limits at all.""" if 'limits' in self.opts and self.opts['limits'] == limits: return self.opts['limits'] = limits self.sigLimitsChanged.emit(self, limits) return limits def writable(self): """ Returns True if this parameter's value can be changed by the user. Note that the value of the parameter can *always* be changed by calling setValue(). """ return not self.readonly() def setWritable(self, writable=True): """Set whether this Parameter should be editable by the user. (This is exactly the opposite of setReadonly).""" self.setOpts(readonly=not writable) def readonly(self): """ Return True if this parameter is read-only. (this is the opposite of writable()) """ return self.opts.get('readonly', False) def setReadonly(self, readonly=True): """Set whether this Parameter's value may be edited by the user (this is the opposite of setWritable()).""" self.setOpts(readonly=readonly) def setOpts(self, **opts): """ Set any arbitrary options on this parameter. The exact behavior of this function will depend on the parameter type, but most parameters will accept a common set of options: value, name, limits, default, readonly, removable, renamable, visible, enabled, and expanded. See :func:`Parameter.__init__ <pyqtgraph.parametertree.Parameter.__init__>` for more information on default options. """ changed = OrderedDict() for k in opts: if k == 'value': self.setValue(opts[k]) elif k == 'name': self.setName(opts[k]) elif k == 'limits': self.setLimits(opts[k]) elif k == 'default': self.setDefault(opts[k]) elif k not in self.opts or self.opts[k] != opts[k]: self.opts[k] = opts[k] changed[k] = opts[k] if len(changed) > 0: self.sigOptionsChanged.emit(self, changed) def emitStateChanged(self, changeDesc, data): ## Emits stateChanged signal and ## requests emission of new treeStateChanged signal self.sigStateChanged.emit(self, changeDesc, data) #self.treeStateChanged(self, changeDesc, data) self.treeStateChanges.append((self, changeDesc, data)) self.emitTreeChanges() def makeTreeItem(self, depth): """ Return a TreeWidgetItem suitable for displaying/controlling the content of this parameter. This is called automatically when a ParameterTree attempts to display this Parameter. Most subclasses will want to override this function. """ if hasattr(self, 'itemClass'): #print "Param:", self, "Make item from itemClass:", self.itemClass return self.itemClass(self, depth) else: return ParameterItem(self, depth=depth) def addChild(self, child, autoIncrementName=None): """ Add another parameter to the end of this parameter's child list. See insertChild() for a description of the *autoIncrementName* argument. """ return self.insertChild(len(self.childs), child, autoIncrementName=autoIncrementName) def addChildren(self, children): """ Add a list or dict of children to this parameter. This method calls addChild once for each value in *children*. """ ## If children was specified as dict, then assume keys are the names. if isinstance(children, dict): ch2 = [] for name, opts in children.items(): if isinstance(opts, dict) and 'name' not in opts: opts = opts.copy() opts['name'] = name ch2.append(opts) children = ch2 for chOpts in children: #print self, "Add child:", type(chOpts), id(chOpts) self.addChild(chOpts) def insertChild(self, pos, child, autoIncrementName=None): """ Insert a new child at pos. If pos is a Parameter, then insert at the position of that Parameter. If child is a dict, then a parameter is constructed using :func:`Parameter.create <pyqtgraph.parametertree.Parameter.create>`. By default, the child's 'autoIncrementName' option determines whether the name will be adjusted to avoid prior name collisions. This behavior may be overridden by specifying the *autoIncrementName* argument. This argument was added in version 0.9.9. """ if isinstance(child, dict): child = Parameter.create(**child) name = child.name() if name in self.names and child is not self.names[name]: if autoIncrementName is True or (autoIncrementName is None and child.opts.get('autoIncrementName', False)): name = self.incrementName(name) child.setName(name) else: raise Exception("Already have child named %s" % str(name)) if isinstance(pos, Parameter): pos = self.childs.index(pos) with self.treeChangeBlocker(): if child.parent() is not None: child.remove() self.names[name] = child self.childs.insert(pos, child) child.parentChanged(self) child.sigTreeStateChanged.connect(self.treeStateChanged) self.sigChildAdded.emit(self, child, pos) return child def removeChild(self, child): """Remove a child parameter.""" name = child.name() if name not in self.names or self.names[name] is not child: raise Exception("Parameter %s is not my child; can't remove." % str(child)) del self.names[name] self.childs.pop(self.childs.index(child)) child.parentChanged(None) try: child.sigTreeStateChanged.disconnect(self.treeStateChanged) except (TypeError, RuntimeError): ## already disconnected pass self.sigChildRemoved.emit(self, child) def clearChildren(self): """Remove all child parameters.""" for ch in self.childs[:]: self.removeChild(ch) def children(self): """Return a list of this parameter's children. Warning: this overrides QObject.children """ return self.childs[:] def hasChildren(self): """Return True if this Parameter has children.""" return len(self.childs) > 0 def parentChanged(self, parent): """This method is called when the parameter's parent has changed. It may be useful to extend this method in subclasses.""" self._parent = parent self.sigParentChanged.emit(self, parent) def parent(self): """Return the parent of this parameter.""" return self._parent def remove(self): """Remove this parameter from its parent's child list""" parent = self.parent() if parent is None: raise Exception("Cannot remove; no parent.") parent.removeChild(self) self.sigRemoved.emit(self) def incrementName(self, name): ## return an unused name by adding a number to the name given base, num = re.match(r'(.*)(\d*)', name).groups() numLen = len(num) if numLen == 0: num = 2 numLen = 1 else: num = int(num) while True: newName = base + ("%%0%dd"%numLen) % num if newName not in self.names: return newName num += 1 def __iter__(self): for ch in self.childs: yield ch def __getitem__(self, names): """Get the value of a child parameter. The name may also be a tuple giving the path to a sub-parameter:: value = param[('child', 'grandchild')] """ if not isinstance(names, tuple): names = (names,) return self.param(*names).value() def __setitem__(self, names, value): """Set the value of a child parameter. The name may also be a tuple giving the path to a sub-parameter:: param[('child', 'grandchild')] = value """ if isinstance(names, basestring): names = (names,) return self.param(*names).setValue(value) def child(self, *names): """Return a child parameter. Accepts the name of the child or a tuple (path, to, child) Added in version 0.9.9. Earlier versions used the 'param' method, which is still implemented for backward compatibility. """ try: param = self.names[names[0]] except KeyError: raise KeyError("Parameter %s has no child named %s" % (self.name(), names[0])) if len(names) > 1: return param.child(*names[1:]) else: return param def param(self, *names): # for backward compatibility. return self.child(*names) def __repr__(self): return asUnicode("<%s '%s' at 0x%x>") % (self.__class__.__name__, self.name(), id(self)) def __getattr__(self, attr): ## Leaving this undocumented because I might like to remove it in the future.. #print type(self), attr if 'names' not in self.__dict__: raise AttributeError(attr) if attr in self.names: import traceback traceback.print_stack() print("Warning: Use of Parameter.subParam is deprecated. Use Parameter.param(name) instead.") return self.param(attr) else: raise AttributeError(attr) def _renameChild(self, child, name): ## Only to be called from Parameter.rename if name in self.names: return child.name() self.names[name] = child del self.names[child.name()] return name def registerItem(self, item): self.items[item] = None def hide(self): """Hide this parameter. It and its children will no longer be visible in any ParameterTree widgets it is connected to.""" self.show(False) def show(self, s=True): """Show this parameter. """ self.opts['visible'] = s self.sigOptionsChanged.emit(self, {'visible': s}) def treeChangeBlocker(self): """ Return an object that can be used to temporarily block and accumulate sigTreeStateChanged signals. This is meant to be used when numerous changes are about to be made to the tree and only one change signal should be emitted at the end. Example:: with param.treeChangeBlocker(): param.addChild(...) param.removeChild(...) param.setValue(...) """ return SignalBlocker(self.blockTreeChangeSignal, self.unblockTreeChangeSignal) def blockTreeChangeSignal(self): """ Used to temporarily block and accumulate tree change signals. *You must remember to unblock*, so it is advisable to use treeChangeBlocker() instead. """ self.blockTreeChangeEmit += 1 def unblockTreeChangeSignal(self): """Unblocks enission of sigTreeStateChanged and flushes the changes out through a single signal.""" self.blockTreeChangeEmit -= 1 self.emitTreeChanges() def treeStateChanged(self, param, changes): """ Called when the state of any sub-parameter has changed. ============== ================================================================ **Arguments:** param The immediate child whose tree state has changed. note that the change may have originated from a grandchild. changes List of tuples describing all changes that have been made in this event: (param, changeDescr, data) ============== ================================================================ This function can be extended to react to tree state changes. """ self.treeStateChanges.extend(changes) self.emitTreeChanges() def emitTreeChanges(self): if self.blockTreeChangeEmit == 0: changes = self.treeStateChanges self.treeStateChanges = [] if len(changes) > 0: self.sigTreeStateChanged.emit(self, changes) class SignalBlocker(object): def __init__(self, enterFn, exitFn): self.enterFn = enterFn self.exitFn = exitFn def __enter__(self): self.enterFn() def __exit__(self, exc_type, exc_value, tb): self.exitFn()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/parametertree/parameterTypes.py
.py
25,922
688
from ..Qt import QtCore, QtGui from ..python2_3 import asUnicode from .Parameter import Parameter, registerParameterType from .ParameterItem import ParameterItem from ..widgets.SpinBox import SpinBox from ..widgets.ColorButton import ColorButton from ..colormap import ColorMap #from ..widgets.GradientWidget import GradientWidget ## creates import loop from .. import pixmaps as pixmaps from .. import functions as fn import os, sys from ..pgcollections import OrderedDict class WidgetParameterItem(ParameterItem): """ ParameterTree item with: * label in second column for displaying value * simple widget for editing value (displayed instead of label when item is selected) * button that resets value to default ========================== ============================================================= **Registered Types:** int Displays a :class:`SpinBox <pyqtgraph.SpinBox>` in integer mode. float Displays a :class:`SpinBox <pyqtgraph.SpinBox>`. bool Displays a QCheckBox str Displays a QLineEdit color Displays a :class:`ColorButton <pyqtgraph.ColorButton>` colormap Displays a :class:`GradientWidget <pyqtgraph.GradientWidget>` ========================== ============================================================= This class can be subclassed by overriding makeWidget() to provide a custom widget. """ def __init__(self, param, depth): ParameterItem.__init__(self, param, depth) self.hideWidget = True ## hide edit widget, replace with label when not selected ## set this to False to keep the editor widget always visible ## build widget into column 1 with a display label and default button. w = self.makeWidget() self.widget = w self.eventProxy = EventProxy(w, self.widgetEventFilter) opts = self.param.opts if 'tip' in opts: w.setToolTip(opts['tip']) self.defaultBtn = QtGui.QPushButton() self.defaultBtn.setFixedWidth(20) self.defaultBtn.setFixedHeight(20) modDir = os.path.dirname(__file__) self.defaultBtn.setIcon(QtGui.QIcon(pixmaps.getPixmap('default'))) self.defaultBtn.clicked.connect(self.defaultClicked) self.displayLabel = QtGui.QLabel() layout = QtGui.QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) layout.addWidget(w) layout.addWidget(self.displayLabel) layout.addWidget(self.defaultBtn) self.layoutWidget = QtGui.QWidget() self.layoutWidget.setLayout(layout) if w.sigChanged is not None: w.sigChanged.connect(self.widgetValueChanged) if hasattr(w, 'sigChanging'): w.sigChanging.connect(self.widgetValueChanging) ## update value shown in widget. if opts.get('value', None) is not None: self.valueChanged(self, opts['value'], force=True) else: ## no starting value was given; use whatever the widget has self.widgetValueChanged() self.updateDefaultBtn() def makeWidget(self): """ Return a single widget that should be placed in the second tree column. The widget must be given three attributes: ========== ============================================================ sigChanged a signal that is emitted when the widget's value is changed value a function that returns the value setValue a function that sets the value ========== ============================================================ This is a good function to override in subclasses. """ opts = self.param.opts t = opts['type'] if t in ('int', 'float'): defs = { 'value': 0, 'min': None, 'max': None, 'step': 1.0, 'dec': False, 'siPrefix': False, 'suffix': '', 'decimals': 3, } if t == 'int': defs['int'] = True defs['minStep'] = 1.0 defs['format'] = '{value:d}' for k in defs: if k in opts: defs[k] = opts[k] if 'limits' in opts: defs['min'], defs['max'] = opts['limits'] w = SpinBox() w.setOpts(**defs) w.sigChanged = w.sigValueChanged w.sigChanging = w.sigValueChanging elif t == 'bool': w = QtGui.QCheckBox() w.sigChanged = w.toggled w.value = w.isChecked w.setValue = w.setChecked w.setEnabled(not opts.get('readonly', False)) self.hideWidget = False elif t == 'str': w = QtGui.QLineEdit() w.setStyleSheet('border: 0px') w.sigChanged = w.editingFinished w.value = lambda: asUnicode(w.text()) w.setValue = lambda v: w.setText(asUnicode(v)) w.sigChanging = w.textChanged elif t == 'color': w = ColorButton() w.sigChanged = w.sigColorChanged w.sigChanging = w.sigColorChanging w.value = w.color w.setValue = w.setColor self.hideWidget = False w.setFlat(True) w.setEnabled(not opts.get('readonly', False)) elif t == 'colormap': from ..widgets.GradientWidget import GradientWidget ## need this here to avoid import loop w = GradientWidget(orientation='bottom') w.sigChanged = w.sigGradientChangeFinished w.sigChanging = w.sigGradientChanged w.value = w.colorMap w.setValue = w.setColorMap self.hideWidget = False else: raise Exception("Unknown type '%s'" % asUnicode(t)) return w def widgetEventFilter(self, obj, ev): ## filter widget's events ## catch TAB to change focus ## catch focusOut to hide editor if ev.type() == ev.KeyPress: if ev.key() == QtCore.Qt.Key_Tab: self.focusNext(forward=True) return True ## don't let anyone else see this event elif ev.key() == QtCore.Qt.Key_Backtab: self.focusNext(forward=False) return True ## don't let anyone else see this event #elif ev.type() == ev.FocusOut: #self.hideEditor() return False def setFocus(self): self.showEditor() def isFocusable(self): return self.param.writable() def valueChanged(self, param, val, force=False): ## called when the parameter's value has changed ParameterItem.valueChanged(self, param, val) self.widget.sigChanged.disconnect(self.widgetValueChanged) try: if force or val != self.widget.value(): self.widget.setValue(val) self.updateDisplayLabel(val) ## always make sure label is updated, even if values match! finally: self.widget.sigChanged.connect(self.widgetValueChanged) self.updateDefaultBtn() def updateDefaultBtn(self): ## enable/disable default btn self.defaultBtn.setEnabled(not self.param.valueIsDefault() and self.param.writable()) # hide / show self.defaultBtn.setVisible(not self.param.readonly()) def updateDisplayLabel(self, value=None): """Update the display label to reflect the value of the parameter.""" if value is None: value = self.param.value() opts = self.param.opts if isinstance(self.widget, QtGui.QAbstractSpinBox): text = asUnicode(self.widget.lineEdit().text()) elif isinstance(self.widget, QtGui.QComboBox): text = self.widget.currentText() else: text = asUnicode(value) self.displayLabel.setText(text) def widgetValueChanged(self): ## called when the widget's value has been changed by the user val = self.widget.value() newVal = self.param.setValue(val) def widgetValueChanging(self, *args): """ Called when the widget's value is changing, but not finalized. For example: editing text before pressing enter or changing focus. """ # This is a bit sketchy: assume the last argument of each signal is # the value.. self.param.sigValueChanging.emit(self.param, args[-1]) def selected(self, sel): """Called when this item has been selected (sel=True) OR deselected (sel=False)""" ParameterItem.selected(self, sel) if self.widget is None: return if sel and self.param.writable(): self.showEditor() elif self.hideWidget: self.hideEditor() def showEditor(self): self.widget.show() self.displayLabel.hide() self.widget.setFocus(QtCore.Qt.OtherFocusReason) if isinstance(self.widget, SpinBox): self.widget.selectNumber() # select the numerical portion of the text for quick editing def hideEditor(self): self.widget.hide() self.displayLabel.show() def limitsChanged(self, param, limits): """Called when the parameter's limits have changed""" ParameterItem.limitsChanged(self, param, limits) t = self.param.opts['type'] if t == 'int' or t == 'float': self.widget.setOpts(bounds=limits) else: return ## don't know what to do with any other types.. def defaultChanged(self, param, value): self.updateDefaultBtn() def treeWidgetChanged(self): """Called when this item is added or removed from a tree.""" ParameterItem.treeWidgetChanged(self) ## add all widgets for this item into the tree if self.widget is not None: tree = self.treeWidget() if tree is None: return tree.setItemWidget(self, 1, self.layoutWidget) self.displayLabel.hide() self.selected(False) def defaultClicked(self): self.param.setToDefault() def optsChanged(self, param, opts): """Called when any options are changed that are not name, value, default, or limits""" #print "opts changed:", opts ParameterItem.optsChanged(self, param, opts) if 'readonly' in opts: self.updateDefaultBtn() if isinstance(self.widget, (QtGui.QCheckBox,ColorButton)): self.widget.setEnabled(not opts['readonly']) ## If widget is a SpinBox, pass options straight through if isinstance(self.widget, SpinBox): # send only options supported by spinbox sbOpts = {} if 'units' in opts and 'suffix' not in opts: sbOpts['suffix'] = opts['units'] for k,v in opts.items(): if k in self.widget.opts: sbOpts[k] = v self.widget.setOpts(**sbOpts) self.updateDisplayLabel() class EventProxy(QtCore.QObject): def __init__(self, qobj, callback): QtCore.QObject.__init__(self) self.callback = callback qobj.installEventFilter(self) def eventFilter(self, obj, ev): return self.callback(obj, ev) class SimpleParameter(Parameter): itemClass = WidgetParameterItem def __init__(self, *args, **kargs): Parameter.__init__(self, *args, **kargs) ## override a few methods for color parameters if self.opts['type'] == 'color': self.value = self.colorValue self.saveState = self.saveColorState def colorValue(self): return fn.mkColor(Parameter.value(self)) def saveColorState(self, *args, **kwds): state = Parameter.saveState(self, *args, **kwds) state['value'] = fn.colorTuple(self.value()) return state def _interpretValue(self, v): fn = { 'int': int, 'float': float, 'bool': bool, 'str': asUnicode, 'color': self._interpColor, 'colormap': self._interpColormap, }[self.opts['type']] return fn(v) def _interpColor(self, v): return fn.mkColor(v) def _interpColormap(self, v): if not isinstance(v, ColorMap): raise TypeError("Cannot set colormap parameter from object %r" % v) return v registerParameterType('int', SimpleParameter, override=True) registerParameterType('float', SimpleParameter, override=True) registerParameterType('bool', SimpleParameter, override=True) registerParameterType('str', SimpleParameter, override=True) registerParameterType('color', SimpleParameter, override=True) registerParameterType('colormap', SimpleParameter, override=True) class GroupParameterItem(ParameterItem): """ Group parameters are used mainly as a generic parent item that holds (and groups!) a set of child parameters. It also provides a simple mechanism for displaying a button or combo that can be used to add new parameters to the group. """ def __init__(self, param, depth): ParameterItem.__init__(self, param, depth) self.updateDepth(depth) self.addItem = None if 'addText' in param.opts: addText = param.opts['addText'] if 'addList' in param.opts: self.addWidget = QtGui.QComboBox() self.addWidget.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents) self.updateAddList() self.addWidget.currentIndexChanged.connect(self.addChanged) else: self.addWidget = QtGui.QPushButton(addText) self.addWidget.clicked.connect(self.addClicked) w = QtGui.QWidget() l = QtGui.QHBoxLayout() l.setContentsMargins(0,0,0,0) w.setLayout(l) l.addWidget(self.addWidget) l.addStretch() #l.addItem(QtGui.QSpacerItem(200, 10, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)) self.addWidgetBox = w self.addItem = QtGui.QTreeWidgetItem([]) self.addItem.setFlags(QtCore.Qt.ItemIsEnabled) ParameterItem.addChild(self, self.addItem) def updateDepth(self, depth): ## Change item's appearance based on its depth in the tree ## This allows highest-level groups to be displayed more prominently. if depth == 0: for c in [0,1]: self.setBackground(c, QtGui.QBrush(QtGui.QColor(100,100,100))) self.setForeground(c, QtGui.QBrush(QtGui.QColor(220,220,255))) font = self.font(c) font.setBold(True) font.setPointSize(font.pointSize()+1) self.setFont(c, font) self.setSizeHint(0, QtCore.QSize(0, 25)) else: for c in [0,1]: self.setBackground(c, QtGui.QBrush(QtGui.QColor(220,220,220))) self.setForeground(c, QtGui.QBrush(QtGui.QColor(50,50,50))) font = self.font(c) font.setBold(True) #font.setPointSize(font.pointSize()+1) self.setFont(c, font) self.setSizeHint(0, QtCore.QSize(0, 20)) def addClicked(self): """Called when "add new" button is clicked The parameter MUST have an 'addNew' method defined. """ self.param.addNew() def addChanged(self): """Called when "add new" combo is changed The parameter MUST have an 'addNew' method defined. """ if self.addWidget.currentIndex() == 0: return typ = asUnicode(self.addWidget.currentText()) self.param.addNew(typ) self.addWidget.setCurrentIndex(0) def treeWidgetChanged(self): ParameterItem.treeWidgetChanged(self) self.treeWidget().setFirstItemColumnSpanned(self, True) if self.addItem is not None: self.treeWidget().setItemWidget(self.addItem, 0, self.addWidgetBox) self.treeWidget().setFirstItemColumnSpanned(self.addItem, True) def addChild(self, child): ## make sure added childs are actually inserted before add btn if self.addItem is not None: ParameterItem.insertChild(self, self.childCount()-1, child) else: ParameterItem.addChild(self, child) def optsChanged(self, param, changed): if 'addList' in changed: self.updateAddList() def updateAddList(self): self.addWidget.blockSignals(True) try: self.addWidget.clear() self.addWidget.addItem(self.param.opts['addText']) for t in self.param.opts['addList']: self.addWidget.addItem(t) finally: self.addWidget.blockSignals(False) class GroupParameter(Parameter): """ Group parameters are used mainly as a generic parent item that holds (and groups!) a set of child parameters. It also provides a simple mechanism for displaying a button or combo that can be used to add new parameters to the group. To enable this, the group must be initialized with the 'addText' option (the text will be displayed on a button which, when clicked, will cause addNew() to be called). If the 'addList' option is specified as well, then a dropdown-list of addable items will be displayed instead of a button. """ itemClass = GroupParameterItem sigAddNew = QtCore.Signal(object, object) # self, type def addNew(self, typ=None): """ This method is called when the user has requested to add a new item to the group. By default, it emits ``sigAddNew(self, typ)``. """ self.sigAddNew.emit(self, typ) def setAddList(self, vals): """Change the list of options available for the user to add to the group.""" self.setOpts(addList=vals) registerParameterType('group', GroupParameter, override=True) class ListParameterItem(WidgetParameterItem): """ WidgetParameterItem subclass providing comboBox that lets the user select from a list of options. """ def __init__(self, param, depth): self.targetValue = None WidgetParameterItem.__init__(self, param, depth) def makeWidget(self): opts = self.param.opts t = opts['type'] w = QtGui.QComboBox() w.setMaximumHeight(20) ## set to match height of spin box and line edit w.sigChanged = w.currentIndexChanged w.value = self.value w.setValue = self.setValue self.widget = w ## needs to be set before limits are changed self.limitsChanged(self.param, self.param.opts['limits']) if len(self.forward) > 0: self.setValue(self.param.value()) return w def value(self): key = asUnicode(self.widget.currentText()) return self.forward.get(key, None) def setValue(self, val): self.targetValue = val if val not in self.reverse[0]: self.widget.setCurrentIndex(0) else: key = self.reverse[1][self.reverse[0].index(val)] ind = self.widget.findText(key) self.widget.setCurrentIndex(ind) def limitsChanged(self, param, limits): # set up forward / reverse mappings for name:value if len(limits) == 0: limits = [''] ## Can never have an empty list--there is always at least a singhe blank item. self.forward, self.reverse = ListParameter.mapping(limits) try: self.widget.blockSignals(True) val = self.targetValue #asUnicode(self.widget.currentText()) self.widget.clear() for k in self.forward: self.widget.addItem(k) if k == val: self.widget.setCurrentIndex(self.widget.count()-1) self.updateDisplayLabel() finally: self.widget.blockSignals(False) class ListParameter(Parameter): itemClass = ListParameterItem def __init__(self, **opts): self.forward = OrderedDict() ## {name: value, ...} self.reverse = ([], []) ## ([value, ...], [name, ...]) ## Parameter uses 'limits' option to define the set of allowed values if 'values' in opts: opts['limits'] = opts['values'] if opts.get('limits', None) is None: opts['limits'] = [] Parameter.__init__(self, **opts) self.setLimits(opts['limits']) def setLimits(self, limits): self.forward, self.reverse = self.mapping(limits) Parameter.setLimits(self, limits) if len(self.reverse[0]) > 0 and self.value() not in self.reverse[0]: self.setValue(self.reverse[0][0]) #def addItem(self, name, value=None): #if name in self.forward: #raise Exception("Name '%s' is already in use for this parameter" % name) #limits = self.opts['limits'] #if isinstance(limits, dict): #limits = limits.copy() #limits[name] = value #self.setLimits(limits) #else: #if value is not None: #raise Exception ## raise exception or convert to dict? #limits = limits[:] #limits.append(name) ## what if limits == None? @staticmethod def mapping(limits): ## Return forward and reverse mapping objects given a limit specification forward = OrderedDict() ## {name: value, ...} reverse = ([], []) ## ([value, ...], [name, ...]) if isinstance(limits, dict): for k, v in limits.items(): forward[k] = v reverse[0].append(v) reverse[1].append(k) else: for v in limits: n = asUnicode(v) forward[n] = v reverse[0].append(v) reverse[1].append(n) return forward, reverse registerParameterType('list', ListParameter, override=True) class ActionParameterItem(ParameterItem): def __init__(self, param, depth): ParameterItem.__init__(self, param, depth) self.layoutWidget = QtGui.QWidget() self.layout = QtGui.QHBoxLayout() self.layout.setContentsMargins(0, 0, 0, 0) self.layoutWidget.setLayout(self.layout) title = param.opts.get('title', None) if title is None: title = param.name() self.button = QtGui.QPushButton(title) #self.layout.addSpacing(100) self.layout.addWidget(self.button) self.layout.addStretch() self.button.clicked.connect(self.buttonClicked) param.sigNameChanged.connect(self.paramRenamed) self.setText(0, '') def treeWidgetChanged(self): ParameterItem.treeWidgetChanged(self) tree = self.treeWidget() if tree is None: return tree.setFirstItemColumnSpanned(self, True) tree.setItemWidget(self, 0, self.layoutWidget) def paramRenamed(self, param, name): self.button.setText(name) def buttonClicked(self): self.param.activate() class ActionParameter(Parameter): """Used for displaying a button within the tree.""" itemClass = ActionParameterItem sigActivated = QtCore.Signal(object) def activate(self): self.sigActivated.emit(self) self.emitStateChanged('activated', None) registerParameterType('action', ActionParameter, override=True) class TextParameterItem(WidgetParameterItem): def __init__(self, param, depth): WidgetParameterItem.__init__(self, param, depth) self.hideWidget = False self.subItem = QtGui.QTreeWidgetItem() self.addChild(self.subItem) def treeWidgetChanged(self): ## TODO: fix so that superclass method can be called ## (WidgetParameter should just natively support this style) #WidgetParameterItem.treeWidgetChanged(self) self.treeWidget().setFirstItemColumnSpanned(self.subItem, True) self.treeWidget().setItemWidget(self.subItem, 0, self.textBox) # for now, these are copied from ParameterItem.treeWidgetChanged self.setHidden(not self.param.opts.get('visible', True)) self.setExpanded(self.param.opts.get('expanded', True)) def makeWidget(self): self.textBox = QtGui.QTextEdit() self.textBox.setMaximumHeight(100) self.textBox.setReadOnly(self.param.opts.get('readonly', False)) self.textBox.value = lambda: str(self.textBox.toPlainText()) self.textBox.setValue = self.textBox.setPlainText self.textBox.sigChanged = self.textBox.textChanged return self.textBox class TextParameter(Parameter): """Editable string; displayed as large text box in the tree.""" itemClass = TextParameterItem registerParameterType('text', TextParameter, override=True)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/parametertree/ParameterTree.py
.py
5,662
155
from ..Qt import QtCore, QtGui from ..widgets.TreeWidget import TreeWidget import os, weakref, re from .ParameterItem import ParameterItem #import functions as fn class ParameterTree(TreeWidget): """Widget used to display or control data from a hierarchy of Parameters""" def __init__(self, parent=None, showHeader=True): """ ============== ======================================================== **Arguments:** parent (QWidget) An optional parent widget showHeader (bool) If True, then the QTreeView header is displayed. ============== ======================================================== """ TreeWidget.__init__(self, parent) self.setVerticalScrollMode(self.ScrollPerPixel) self.setHorizontalScrollMode(self.ScrollPerPixel) self.setAnimated(False) self.setColumnCount(2) self.setHeaderLabels(["Parameter", "Value"]) self.setAlternatingRowColors(True) self.paramSet = None self.header().setResizeMode(QtGui.QHeaderView.ResizeToContents) self.setHeaderHidden(not showHeader) self.itemChanged.connect(self.itemChangedEvent) self.lastSel = None self.setRootIsDecorated(False) def setParameters(self, param, showTop=True): """ Set the top-level :class:`Parameter <pyqtgraph.parametertree.Parameter>` to be displayed in this ParameterTree. If *showTop* is False, then the top-level parameter is hidden and only its children will be visible. This is a convenience method equivalent to:: tree.clear() tree.addParameters(param, showTop) """ self.clear() self.addParameters(param, showTop=showTop) def addParameters(self, param, root=None, depth=0, showTop=True): """ Adds one top-level :class:`Parameter <pyqtgraph.parametertree.Parameter>` to the view. ============== ========================================================== **Arguments:** param The :class:`Parameter <pyqtgraph.parametertree.Parameter>` to add. root The item within the tree to which *param* should be added. By default, *param* is added as a top-level item. showTop If False, then *param* will be hidden, and only its children will be visible in the tree. ============== ========================================================== """ item = param.makeTreeItem(depth=depth) if root is None: root = self.invisibleRootItem() ## Hide top-level item if not showTop: item.setText(0, '') item.setSizeHint(0, QtCore.QSize(1,1)) item.setSizeHint(1, QtCore.QSize(1,1)) depth -= 1 root.addChild(item) item.treeWidgetChanged() for ch in param: self.addParameters(ch, root=item, depth=depth+1) def clear(self): """ Remove all parameters from the tree. """ self.invisibleRootItem().takeChildren() def focusNext(self, item, forward=True): """Give input focus to the next (or previous) item after *item* """ while True: parent = item.parent() if parent is None: return nextItem = self.nextFocusableChild(parent, item, forward=forward) if nextItem is not None: nextItem.setFocus() self.setCurrentItem(nextItem) return item = parent def focusPrevious(self, item): self.focusNext(item, forward=False) def nextFocusableChild(self, root, startItem=None, forward=True): if startItem is None: if forward: index = 0 else: index = root.childCount()-1 else: if forward: index = root.indexOfChild(startItem) + 1 else: index = root.indexOfChild(startItem) - 1 if forward: inds = list(range(index, root.childCount())) else: inds = list(range(index, -1, -1)) for i in inds: item = root.child(i) if hasattr(item, 'isFocusable') and item.isFocusable(): return item else: item = self.nextFocusableChild(item, forward=forward) if item is not None: return item return None def contextMenuEvent(self, ev): item = self.currentItem() if hasattr(item, 'contextMenuEvent'): item.contextMenuEvent(ev) def itemChangedEvent(self, item, col): if hasattr(item, 'columnChangedEvent'): item.columnChangedEvent(col) def selectionChanged(self, *args): sel = self.selectedItems() if len(sel) != 1: sel = None if self.lastSel is not None and isinstance(self.lastSel, ParameterItem): self.lastSel.selected(False) if sel is None: self.lastSel = None return self.lastSel = sel[0] if hasattr(sel[0], 'selected'): sel[0].selected(True) return TreeWidget.selectionChanged(self, *args) def wheelEvent(self, ev): self.clearSelection() return TreeWidget.wheelEvent(self, ev)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/parametertree/ParameterSystem.py
.py
4,598
128
from .parameterTypes import GroupParameter from .. import functions as fn from .SystemSolver import SystemSolver class ParameterSystem(GroupParameter): """ ParameterSystem is a subclass of GroupParameter that manages a tree of sub-parameters with a set of interdependencies--changing any one parameter may affect other parameters in the system. See parametertree/SystemSolver for more information. NOTE: This API is experimental and may change substantially across minor version numbers. """ def __init__(self, *args, **kwds): GroupParameter.__init__(self, *args, **kwds) self._system = None self._fixParams = [] # all auto-generated 'fixed' params sys = kwds.pop('system', None) if sys is not None: self.setSystem(sys) self._ignoreChange = [] # params whose changes should be ignored temporarily self.sigTreeStateChanged.connect(self.updateSystem) def setSystem(self, sys): self._system = sys # auto-generate defaults to match child parameters defaults = {} vals = {} for param in self: name = param.name() constraints = '' if hasattr(sys, '_' + name): constraints += 'n' if not param.readonly(): constraints += 'f' if 'n' in constraints: ch = param.addChild(dict(name='fixed', type='bool', value=False)) self._fixParams.append(ch) param.setReadonly(True) param.setOpts(expanded=False) else: vals[name] = param.value() ch = param.addChild(dict(name='fixed', type='bool', value=True, readonly=True)) #self._fixParams.append(ch) defaults[name] = [None, param.type(), None, constraints] sys.defaultState.update(defaults) sys.reset() for name, value in vals.items(): setattr(sys, name, value) self.updateAllParams() def updateSystem(self, param, changes): changes = [ch for ch in changes if ch[0] not in self._ignoreChange] #resets = [ch[0] for ch in changes if ch[1] == 'setToDefault'] sets = [ch[0] for ch in changes if ch[1] == 'value'] #for param in resets: #setattr(self._system, param.name(), None) for param in sets: #if param in resets: #continue #if param in self._fixParams: #param.parent().setWritable(param.value()) #else: if param in self._fixParams: parent = param.parent() if param.value(): setattr(self._system, parent.name(), parent.value()) else: setattr(self._system, parent.name(), None) else: setattr(self._system, param.name(), param.value()) self.updateAllParams() def updateAllParams(self): try: self.sigTreeStateChanged.disconnect(self.updateSystem) for name, state in self._system._vars.items(): param = self.child(name) try: v = getattr(self._system, name) if self._system._vars[name][2] is None: self.updateParamState(self.child(name), 'autoSet') param.setValue(v) else: self.updateParamState(self.child(name), 'fixed') except RuntimeError: self.updateParamState(param, 'autoUnset') finally: self.sigTreeStateChanged.connect(self.updateSystem) def updateParamState(self, param, state): if state == 'autoSet': bg = fn.mkBrush((200, 255, 200, 255)) bold = False readonly = True elif state == 'autoUnset': bg = fn.mkBrush(None) bold = False readonly = False elif state == 'fixed': bg = fn.mkBrush('y') bold = True readonly = False param.setReadonly(readonly) #for item in param.items: #item.setBackground(0, bg) #f = item.font(0) #f.setWeight(f.Bold if bold else f.Normal) #item.setFont(0, f)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/parametertree/SystemSolver.py
.py
17,816
425
from ..pgcollections import OrderedDict import numpy as np import copy class SystemSolver(object): """ This abstract class is used to formalize and manage user interaction with a complex system of equations (related to "constraint satisfaction problems"). It is often the case that devices must be controlled through a large number of free variables, and interactions between these variables make the system difficult to manage and conceptualize as a user interface. This class does _not_ attempt to numerically solve the system of equations. Rather, it provides a framework for subdividing the system into manageable pieces and specifying closed-form solutions to these small pieces. For an example, see the simple Camera class below. Theory of operation: Conceptualize the system as 1) a set of variables whose values may be either user-specified or automatically generated, and 2) a set of functions that define *how* each variable should be generated. When a variable is accessed (as an instance attribute), the solver first checks to see if it already has a value (either user-supplied, or cached from a previous calculation). If it does not, then the solver calls a method on itself (the method must be named `_variableName`) that will either return the calculated value (which usually involves acccessing other variables in the system), or raise RuntimeError if it is unable to calculate the value (usually because the user has not provided sufficient input to fully constrain the system). Each method that calculates a variable value may include multiple try/except blocks, so that if one method generates a RuntimeError, it may fall back on others. In this way, the system may be solved by recursively searching the tree of possible relationships between variables. This allows the user flexibility in deciding which variables are the most important to specify, while avoiding the apparent combinatorial explosion of calculation pathways that must be considered by the developer. Solved values are cached for efficiency, and automatically cleared when a state change invalidates the cache. The rules for this are simple: any time a value is set, it invalidates the cache *unless* the previous value was None (which indicates that no other variable has yet requested that value). More complex cache management may be defined in subclasses. Subclasses must define: 1) The *defaultState* class attribute: This is a dict containing a description of the variables in the system--their default values, data types, and the ways they can be constrained. The format is:: { name: [value, type, constraint, allowed_constraints], ...} * *value* is the default value. May be None if it has not been specified yet. * *type* may be float, int, bool, np.ndarray, ... * *constraint* may be None, single value, or (min, max) * None indicates that the value is not constrained--it may be automatically generated if the value is requested. * *allowed_constraints* is a string composed of (n)one, (f)ixed, and (r)ange. Note: do not put mutable objects inside defaultState! 2) For each variable that may be automatically determined, a method must be defined with the name `_variableName`. This method may either return the """ defaultState = OrderedDict() def __init__(self): self.__dict__['_vars'] = OrderedDict() self.__dict__['_currentGets'] = set() self.reset() def copy(self): sys = type(self)() sys.__dict__['_vars'] = copy.deepcopy(self.__dict__['_vars']) sys.__dict__['_currentGets'] = copy.deepcopy(self.__dict__['_currentGets']) return sys def reset(self): """ Reset all variables in the solver to their default state. """ self._currentGets.clear() for k in self.defaultState: self._vars[k] = self.defaultState[k][:] def __getattr__(self, name): if name in self._vars: return self.get(name) raise AttributeError(name) def __setattr__(self, name, value): """ Set the value of a state variable. If None is given for the value, then the constraint will also be set to None. If a tuple is given for a scalar variable, then the tuple is used as a range constraint instead of a value. Otherwise, the constraint is set to 'fixed'. """ # First check this is a valid attribute if name in self._vars: if value is None: self.set(name, value, None) elif isinstance(value, tuple) and self._vars[name][1] is not np.ndarray: self.set(name, None, value) else: self.set(name, value, 'fixed') else: # also allow setting any other pre-existing attribute if hasattr(self, name): object.__setattr__(self, name, value) else: raise AttributeError(name) def get(self, name): """ Return the value for parameter *name*. If the value has not been specified, then attempt to compute it from other interacting parameters. If no value can be determined, then raise RuntimeError. """ if name in self._currentGets: raise RuntimeError("Cyclic dependency while calculating '%s'." % name) self._currentGets.add(name) try: v = self._vars[name][0] if v is None: cfunc = getattr(self, '_' + name, None) if cfunc is None: v = None else: v = cfunc() if v is None: raise RuntimeError("Parameter '%s' is not specified." % name) v = self.set(name, v) finally: self._currentGets.remove(name) return v def set(self, name, value=None, constraint=True): """ Set a variable *name* to *value*. The actual set value is returned (in some cases, the value may be cast into another type). If *value* is None, then the value is left to be determined in the future. At any time, the value may be re-assigned arbitrarily unless a constraint is given. If *constraint* is True (the default), then supplying a value that violates a previously specified constraint will raise an exception. If *constraint* is 'fixed', then the value is set (if provided) and the variable will not be updated automatically in the future. If *constraint* is a tuple, then the value is constrained to be within the given (min, max). Either constraint may be None to disable it. In some cases, a constraint cannot be satisfied automatically, and the user will be forced to resolve the constraint manually. If *constraint* is None, then any constraints are removed for the variable. """ var = self._vars[name] if constraint is None: if 'n' not in var[3]: raise TypeError("Empty constraints not allowed for '%s'" % name) var[2] = constraint elif constraint == 'fixed': if 'f' not in var[3]: raise TypeError("Fixed constraints not allowed for '%s'" % name) # This is nice, but not reliable because sometimes there is 1 DOF but we set 2 # values simultaneously. # if var[2] is None: # try: # self.get(name) # # has already been computed by the system; adding a fixed constraint # # would overspecify the system. # raise ValueError("Cannot fix parameter '%s'; system would become overconstrained." % name) # except RuntimeError: # pass var[2] = constraint elif isinstance(constraint, tuple): if 'r' not in var[3]: raise TypeError("Range constraints not allowed for '%s'" % name) assert len(constraint) == 2 var[2] = constraint elif constraint is not True: raise TypeError("constraint must be None, True, 'fixed', or tuple. (got %s)" % constraint) # type checking / massaging if var[1] is np.ndarray and value is not None: value = np.array(value, dtype=float) elif var[1] in (int, float, tuple) and value is not None: value = var[1](value) # constraint checks if constraint is True and not self.check_constraint(name, value): raise ValueError("Setting %s = %s violates constraint %s" % (name, value, var[2])) # invalidate other dependent values if var[0] is not None or value is None: # todo: we can make this more clever..(and might need to) # we just know that a value of None cannot have dependencies # (because if anyone else had asked for this value, it wouldn't be # None anymore) self.resetUnfixed() var[0] = value return value def check_constraint(self, name, value): c = self._vars[name][2] if c is None or value is None: return True if isinstance(c, tuple): return ((c[0] is None or c[0] <= value) and (c[1] is None or c[1] >= value)) else: return value == c def saveState(self): """ Return a serializable description of the solver's current state. """ state = OrderedDict() for name, var in self._vars.items(): state[name] = (var[0], var[2]) return state def restoreState(self, state): """ Restore the state of all values and constraints in the solver. """ self.reset() for name, var in state.items(): self.set(name, var[0], var[1]) def resetUnfixed(self): """ For any variable that does not have a fixed value, reset its value to None. """ for var in self._vars.values(): if var[2] != 'fixed': var[0] = None def solve(self): for k in self._vars: getattr(self, k) def checkOverconstraint(self): """Check whether the system is overconstrained. If so, return the name of the first overconstrained parameter. Overconstraints occur when any fixed parameter can be successfully computed by the system. (Ideally, all parameters are either fixed by the user or constrained by the system, but never both). """ for k,v in self._vars.items(): if v[2] == 'fixed' and 'n' in v[3]: oldval = v[:] self.set(k, None, None) try: self.get(k) return k except RuntimeError: pass finally: self._vars[k] = oldval return False def __repr__(self): state = OrderedDict() for name, var in self._vars.items(): if var[2] == 'fixed': state[name] = var[0] state = ', '.join(["%s=%s" % (n, v) for n,v in state.items()]) return "<%s %s>" % (self.__class__.__name__, state) if __name__ == '__main__': class Camera(SystemSolver): """ Consider a simple SLR camera. The variables we will consider that affect the camera's behavior while acquiring a photo are aperture, shutter speed, ISO, and flash (of course there are many more, but let's keep the example simple). In rare cases, the user wants to manually specify each of these variables and no more work needs to be done to take the photo. More often, the user wants to specify more interesting constraints like depth of field, overall exposure, or maximum allowed ISO value. If we add a simple light meter measurement into this system and an 'exposure' variable that indicates the desired exposure (0 is "perfect", -1 is one stop darker, etc), then the system of equations governing the camera behavior would have the following variables: aperture, shutter, iso, flash, exposure, light meter The first four variables are the "outputs" of the system (they directly drive the camera), the last is a constant (the camera itself cannot affect the reading on the light meter), and 'exposure' specifies a desired relationship between other variables in the system. So the question is: how can I formalize a system like this as a user interface? Typical cameras have a fairly limited approach: provide the user with a list of modes, each of which defines a particular set of constraints. For example: manual: user provides aperture, shutter, iso, and flash aperture priority: user provides aperture and exposure, camera selects iso, shutter, and flash automatically shutter priority: user provides shutter and exposure, camera selects iso, aperture, and flash program: user specifies exposure, camera selects all other variables automatically action: camera selects all variables while attempting to maximize shutter speed portrait: camera selects all variables while attempting to minimize aperture A more general approach might allow the user to provide more explicit constraints on each variable (for example: I want a shutter speed of 1/30 or slower, an ISO no greater than 400, an exposure between -1 and 1, and the smallest aperture possible given all other constraints) and have the camera solve the system of equations, with a warning if no solution is found. This is exactly what we will implement in this example class. """ defaultState = OrderedDict([ # Field stop aperture ('aperture', [None, float, None, 'nf']), # Duration that shutter is held open. ('shutter', [None, float, None, 'nf']), # ISO (sensitivity) value. 100, 200, 400, 800, 1600.. ('iso', [None, int, None, 'nf']), # Flash is a value indicating the brightness of the flash. A table # is used to decide on "balanced" settings for each flash level: # 0: no flash # 1: s=1/60, a=2.0, iso=100 # 2: s=1/60, a=4.0, iso=100 ..and so on.. ('flash', [None, float, None, 'nf']), # exposure is a value indicating how many stops brighter (+1) or # darker (-1) the photographer would like the photo to appear from # the 'balanced' settings indicated by the light meter (see below). ('exposure', [None, float, None, 'f']), # Let's define this as an external light meter (not affected by # aperture) with logarithmic output. We arbitrarily choose the # following settings as "well balanced" for each light meter value: # -1: s=1/60, a=2.0, iso=100 # 0: s=1/60, a=4.0, iso=100 # 1: s=1/120, a=4.0, iso=100 ..and so on.. # Note that the only allowed constraint mode is (f)ixed, since the # camera never _computes_ the light meter value, it only reads it. ('lightMeter', [None, float, None, 'f']), # Indicates the camera's final decision on how it thinks the photo will # look, given the chosen settings. This value is _only_ determined # automatically. ('balance', [None, float, None, 'n']), ]) def _aperture(self): """ Determine aperture automatically under a variety of conditions. """ iso = self.iso exp = self.exposure light = self.lightMeter try: # shutter-priority mode sh = self.shutter # this raises RuntimeError if shutter has not # been specified ap = 4.0 * (sh / (1./60.)) * (iso / 100.) * (2 ** exp) * (2 ** light) ap = np.clip(ap, 2.0, 16.0) except RuntimeError: # program mode; we can select a suitable shutter # value at the same time. sh = (1./60.) raise return ap def _balance(self): iso = self.iso light = self.lightMeter sh = self.shutter ap = self.aperture fl = self.flash bal = (4.0 / ap) * (sh / (1./60.)) * (iso / 100.) * (2 ** light) return np.log2(bal) camera = Camera() camera.iso = 100 camera.exposure = 0 camera.lightMeter = 2 camera.shutter = 1./60. camera.flash = 0 camera.solve() print(camera.saveState())
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/parametertree/ParameterItem.py
.py
6,541
172
from ..Qt import QtGui, QtCore from ..python2_3 import asUnicode import os, weakref, re class ParameterItem(QtGui.QTreeWidgetItem): """ Abstract ParameterTree item. Used to represent the state of a Parameter from within a ParameterTree. - Sets first column of item to name - generates context menu if item is renamable or removable - handles child added / removed events - provides virtual functions for handling changes from parameter For more ParameterItem types, see ParameterTree.parameterTypes module. """ def __init__(self, param, depth=0): title = param.opts.get('title', None) if title is None: title = param.name() QtGui.QTreeWidgetItem.__init__(self, [title, '']) self.param = param self.param.registerItem(self) ## let parameter know this item is connected to it (for debugging) self.depth = depth param.sigValueChanged.connect(self.valueChanged) param.sigChildAdded.connect(self.childAdded) param.sigChildRemoved.connect(self.childRemoved) param.sigNameChanged.connect(self.nameChanged) param.sigLimitsChanged.connect(self.limitsChanged) param.sigDefaultChanged.connect(self.defaultChanged) param.sigOptionsChanged.connect(self.optsChanged) param.sigParentChanged.connect(self.parentChanged) opts = param.opts ## Generate context menu for renaming/removing parameter self.contextMenu = QtGui.QMenu() self.contextMenu.addSeparator() flags = QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled if opts.get('renamable', False): if param.opts.get('title', None) is not None: raise Exception("Cannot make parameter with both title != None and renamable == True.") flags |= QtCore.Qt.ItemIsEditable self.contextMenu.addAction('Rename').triggered.connect(self.editName) if opts.get('removable', False): self.contextMenu.addAction("Remove").triggered.connect(self.requestRemove) ## handle movable / dropEnabled options if opts.get('movable', False): flags |= QtCore.Qt.ItemIsDragEnabled if opts.get('dropEnabled', False): flags |= QtCore.Qt.ItemIsDropEnabled self.setFlags(flags) ## flag used internally during name editing self.ignoreNameColumnChange = False def valueChanged(self, param, val): ## called when the parameter's value has changed pass def isFocusable(self): """Return True if this item should be included in the tab-focus order""" return False def setFocus(self): """Give input focus to this item. Can be reimplemented to display editor widgets, etc. """ pass def focusNext(self, forward=True): """Give focus to the next (or previous) focusable item in the parameter tree""" self.treeWidget().focusNext(self, forward=forward) def treeWidgetChanged(self): """Called when this item is added or removed from a tree. Expansion, visibility, and column widgets must all be configured AFTER the item is added to a tree, not during __init__. """ self.setHidden(not self.param.opts.get('visible', True)) self.setExpanded(self.param.opts.get('expanded', True)) def childAdded(self, param, child, pos): item = child.makeTreeItem(depth=self.depth+1) self.insertChild(pos, item) item.treeWidgetChanged() for i, ch in enumerate(child): item.childAdded(child, ch, i) def childRemoved(self, param, child): for i in range(self.childCount()): item = self.child(i) if item.param is child: self.takeChild(i) break def parentChanged(self, param, parent): ## called when the parameter's parent has changed. pass def contextMenuEvent(self, ev): if not self.param.opts.get('removable', False) and not self.param.opts.get('renamable', False): return self.contextMenu.popup(ev.globalPos()) def columnChangedEvent(self, col): """Called when the text in a column has been edited (or otherwise changed). By default, we only use changes to column 0 to rename the parameter. """ if col == 0 and (self.param.opts.get('title', None) is None): if self.ignoreNameColumnChange: return try: newName = self.param.setName(asUnicode(self.text(col))) except Exception: self.setText(0, self.param.name()) raise try: self.ignoreNameColumnChange = True self.nameChanged(self, newName) ## If the parameter rejects the name change, we need to set it back. finally: self.ignoreNameColumnChange = False def nameChanged(self, param, name): ## called when the parameter's name has changed. if self.param.opts.get('title', None) is None: self.setText(0, name) def limitsChanged(self, param, limits): """Called when the parameter's limits have changed""" pass def defaultChanged(self, param, default): """Called when the parameter's default value has changed""" pass def optsChanged(self, param, opts): """Called when any options are changed that are not name, value, default, or limits""" #print opts if 'visible' in opts: self.setHidden(not opts['visible']) def editName(self): self.treeWidget().editItem(self, 0) def selected(self, sel): """Called when this item has been selected (sel=True) OR deselected (sel=False)""" pass def requestRemove(self): ## called when remove is selected from the context menu. ## we need to delay removal until the action is complete ## since destroying the menu in mid-action will cause a crash. QtCore.QTimer.singleShot(0, self.param.remove) ## for python 3 support, we need to redefine hash and eq methods. def __hash__(self): return id(self) def __eq__(self, x): return x is self
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/parametertree/tests/test_parametertypes.py
.py
4,884
134
# ~*~ coding: utf8 ~*~ import sys import pytest from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph.parametertree as pt import pyqtgraph as pg from pyqtgraph.python2_3 import asUnicode from pyqtgraph.functions import eq import numpy as np app = pg.mkQApp() def _getWidget(param): return list(param.items.keys())[0].widget def test_opts(): paramSpec = [ dict(name='bool', type='bool', readonly=True), dict(name='color', type='color', readonly=True), ] param = pt.Parameter.create(name='params', type='group', children=paramSpec) tree = pt.ParameterTree() tree.setParameters(param) assert _getWidget(param.param('bool')).isEnabled() is False assert _getWidget(param.param('bool')).isEnabled() is False def test_types(): paramSpec = [ dict(name='float', type='float'), dict(name='int', type='int'), dict(name='str', type='str'), dict(name='list', type='list', values=['x','y','z']), dict(name='dict', type='list', values={'x':1, 'y':3, 'z':7}), dict(name='bool', type='bool'), dict(name='color', type='color'), ] param = pt.Parameter.create(name='params', type='group', children=paramSpec) tree = pt.ParameterTree() tree.setParameters(param) all_objs = { 'int0': 0, 'int':7, 'float': -0.35, 'bigfloat': 1e129, 'npfloat': np.float(5), 'npint': np.int(5),'npinf': np.inf, 'npnan': np.nan, 'bool': True, 'complex': 5+3j, 'str': 'xxx', 'unicode': asUnicode('µ'), 'list': [1,2,3], 'dict': {'1': 2}, 'color': pg.mkColor('k'), 'brush': pg.mkBrush('k'), 'pen': pg.mkPen('k'), 'none': None } if hasattr(QtCore, 'QString'): all_objs['qstring'] = QtCore.QString('xxxµ') # float types = ['int0', 'int', 'float', 'bigfloat', 'npfloat', 'npint', 'npinf', 'npnan', 'bool'] check_param_types(param.child('float'), float, float, 0.0, all_objs, types) # int types = ['int0', 'int', 'float', 'bigfloat', 'npfloat', 'npint', 'bool'] inttyps = int if sys.version[0] >= '3' else (int, long) check_param_types(param.child('int'), inttyps, int, 0, all_objs, types) # str (should be able to make a string out of any type) types = all_objs.keys() strtyp = str if sys.version[0] >= '3' else unicode check_param_types(param.child('str'), strtyp, asUnicode, '', all_objs, types) # bool (should be able to make a boolean out of any type?) types = all_objs.keys() check_param_types(param.child('bool'), bool, bool, False, all_objs, types) # color types = ['color', 'int0', 'int', 'float', 'npfloat', 'npint', 'list'] init = QtGui.QColor(128, 128, 128, 255) check_param_types(param.child('color'), QtGui.QColor, pg.mkColor, init, all_objs, types) def check_param_types(param, types, map_func, init, objs, keys): """Check that parameter setValue() accepts or rejects the correct types and that value() returns the correct type. Parameters ---------- param : Parameter instance types : type or tuple of types The allowed types for this parameter to return from value(). map_func : function Converts an input value to the expected output value. init : object The expected initial value of the parameter objs : dict Contains a variety of objects that will be tested as arguments to param.setValue(). keys : list The list of keys indicating the valid objects in *objs*. When param.setValue() is teasted with each value from *objs*, we expect an exception to be raised if the associated key is not in *keys*. """ val = param.value() if not isinstance(types, tuple): types = (types,) assert val == init and type(val) in types # test valid input types good_inputs = [objs[k] for k in keys if k in objs] good_outputs = map(map_func, good_inputs) for x,y in zip(good_inputs, good_outputs): param.setValue(x) val = param.value() if not (eq(val, y) and type(val) in types): raise Exception("Setting parameter %s with value %r should have resulted in %r (types: %r), " "but resulted in %r (type: %r) instead." % (param, x, y, types, val, type(val))) # test invalid input types for k,v in objs.items(): if k in keys: continue try: param.setValue(v) except (TypeError, ValueError, OverflowError): continue except Exception as exc: raise Exception("Setting %s parameter value to %r raised %r." % (param, v, exc)) raise Exception("Setting %s parameter value to %r should have raised an exception." % (param, v))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/metaarray/__init__.py
.py
25
2
from .MetaArray import *
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/metaarray/MetaArray.py
.py
57,689
1,510
# -*- coding: utf-8 -*- """ MetaArray.py - Class encapsulating ndarray with meta data Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more information. MetaArray is an array class based on numpy.ndarray that allows storage of per-axis meta data such as axis values, names, units, column names, etc. It also enables several new methods for slicing and indexing the array based on this meta data. More info at http://www.scipy.org/Cookbook/MetaArray """ import types, copy, threading, os, re import pickle import numpy as np from ..python2_3 import basestring ## By default, the library will use HDF5 when writing files. ## This can be overridden by setting USE_HDF5 = False USE_HDF5 = True try: import h5py HAVE_HDF5 = True except: USE_HDF5 = False HAVE_HDF5 = False def axis(name=None, cols=None, values=None, units=None): """Convenience function for generating axis descriptions when defining MetaArrays""" ax = {} cNameOrder = ['name', 'units', 'title'] if name is not None: ax['name'] = name if values is not None: ax['values'] = values if units is not None: ax['units'] = units if cols is not None: ax['cols'] = [] for c in cols: if type(c) != list and type(c) != tuple: c = [c] col = {} for i in range(0,len(c)): col[cNameOrder[i]] = c[i] ax['cols'].append(col) return ax class sliceGenerator(object): """Just a compact way to generate tuples of slice objects.""" def __getitem__(self, arg): return arg def __getslice__(self, arg): return arg SLICER = sliceGenerator() class MetaArray(object): """N-dimensional array with meta data such as axis titles, units, and column names. May be initialized with a file name, a tuple representing the dimensions of the array, or any arguments that could be passed on to numpy.array() The info argument sets the metadata for the entire array. It is composed of a list of axis descriptions where each axis may have a name, title, units, and a list of column descriptions. An additional dict at the end of the axis list may specify parameters that apply to values in the entire array. For example: A 2D array of altitude values for a topographical map might look like info=[ {'name': 'lat', 'title': 'Lattitude'}, {'name': 'lon', 'title': 'Longitude'}, {'title': 'Altitude', 'units': 'm'} ] In this case, every value in the array represents the altitude in feet at the lat, lon position represented by the array index. All of the following return the value at lat=10, lon=5: array[10, 5] array['lon':5, 'lat':10] array['lat':10][5] Now suppose we want to combine this data with another array of equal dimensions that represents the average rainfall for each location. We could easily store these as two separate arrays or combine them into a 3D array with this description: info=[ {'name': 'vals', 'cols': [ {'name': 'altitude', 'units': 'm'}, {'name': 'rainfall', 'units': 'cm/year'} ]}, {'name': 'lat', 'title': 'Lattitude'}, {'name': 'lon', 'title': 'Longitude'} ] We can now access the altitude values with array[0] or array['altitude'], and the rainfall values with array[1] or array['rainfall']. All of the following return the rainfall value at lat=10, lon=5: array[1, 10, 5] array['lon':5, 'lat':10, 'val': 'rainfall'] array['rainfall', 'lon':5, 'lat':10] Notice that in the second example, there is no need for an extra (4th) axis description since the actual values are described (name and units) in the column info for the first axis. """ version = u'2' # Default hdf5 compression to use when writing # 'gzip' is widely available and somewhat slow # 'lzf' is faster, but generally not available outside h5py # 'szip' is also faster, but lacks write support on windows # (so by default, we use no compression) # May also be a tuple (filter, opts), such as ('gzip', 3) defaultCompression = None ## Types allowed as axis or column names nameTypes = [basestring, tuple] @staticmethod def isNameType(var): return any([isinstance(var, t) for t in MetaArray.nameTypes]) ## methods to wrap from embedded ndarray / HDF5 wrapMethods = set(['__eq__', '__ne__', '__le__', '__lt__', '__ge__', '__gt__']) def __init__(self, data=None, info=None, dtype=None, file=None, copy=False, **kwargs): object.__init__(self) #self._infoOwned = False self._isHDF = False if file is not None: self._data = None self.readFile(file, **kwargs) if kwargs.get("readAllData", True) and self._data is None: raise Exception("File read failed: %s" % file) else: self._info = info if (hasattr(data, 'implements') and data.implements('MetaArray')): self._info = data._info self._data = data.asarray() elif isinstance(data, tuple): ## create empty array with specified shape self._data = np.empty(data, dtype=dtype) else: self._data = np.array(data, dtype=dtype, copy=copy) ## run sanity checks on info structure self.checkInfo() def checkInfo(self): info = self._info if info is None: if self._data is None: return else: self._info = [{} for i in range(self.ndim + 1)] return else: try: info = list(info) except: raise Exception("Info must be a list of axis specifications") if len(info) < self.ndim+1: info.extend([{}]*(self.ndim+1-len(info))) elif len(info) > self.ndim+1: raise Exception("Info parameter must be list of length ndim+1 or less.") for i in range(len(info)): if not isinstance(info[i], dict): if info[i] is None: info[i] = {} else: raise Exception("Axis specification must be Dict or None") if i < self.ndim and 'values' in info[i]: if type(info[i]['values']) is list: info[i]['values'] = np.array(info[i]['values']) elif type(info[i]['values']) is not np.ndarray: raise Exception("Axis values must be specified as list or ndarray") if info[i]['values'].ndim != 1 or info[i]['values'].shape[0] != self.shape[i]: raise Exception("Values array for axis %d has incorrect shape. (given %s, but should be %s)" % (i, str(info[i]['values'].shape), str((self.shape[i],)))) if i < self.ndim and 'cols' in info[i]: if not isinstance(info[i]['cols'], list): info[i]['cols'] = list(info[i]['cols']) if len(info[i]['cols']) != self.shape[i]: raise Exception('Length of column list for axis %d does not match data. (given %d, but should be %d)' % (i, len(info[i]['cols']), self.shape[i])) self._info = info def implements(self, name=None): ## Rather than isinstance(obj, MetaArray) use object.implements('MetaArray') if name is None: return ['MetaArray'] else: return name == 'MetaArray' #def __array_finalize__(self,obj): ### array_finalize is called every time a MetaArray is created ### (whereas __new__ is not necessarily called every time) ### obj is the object from which this array was generated (for example, when slicing or view()ing) ## We use the getattr method to set a default if 'obj' doesn't have the 'info' attribute ##print "Create new MA from object", str(type(obj)) ##import traceback ##traceback.print_stack() ##print "finalize", type(self), type(obj) #if not hasattr(self, '_info'): ##if isinstance(obj, MetaArray): ##print " copy info:", obj._info #self._info = getattr(obj, '_info', [{}]*(obj.ndim+1)) #self._infoOwned = False ## Do not make changes to _info until it is copied at least once ##print " self info:", self._info ## We could have checked first whether self._info was already defined: ##if not hasattr(self, 'info'): ## self._info = getattr(obj, 'info', {}) def __getitem__(self, ind): #print "getitem:", ind ## should catch scalar requests as early as possible to speed things up (?) nInd = self._interpretIndexes(ind) #a = np.ndarray.__getitem__(self, nInd) a = self._data[nInd] if len(nInd) == self.ndim: if np.all([not isinstance(ind, slice) for ind in nInd]): ## no slices; we have requested a single value from the array return a #if type(a) != type(self._data) and not isinstance(a, np.ndarray): ## indexing returned single value #return a ## indexing returned a sub-array; generate new info array to go with it #print " new MA:", type(a), a.shape info = [] extraInfo = self._info[-1].copy() for i in range(0, len(nInd)): ## iterate over all axes #print " axis", i if type(nInd[i]) in [slice, list] or isinstance(nInd[i], np.ndarray): ## If the axis is sliced, keep the info but chop if necessary #print " slice axis", i, nInd[i] #a._info[i] = self._axisSlice(i, nInd[i]) #print " info:", a._info[i] info.append(self._axisSlice(i, nInd[i])) else: ## If the axis is indexed, then move the information from that single index to the last info dictionary #print "indexed:", i, nInd[i], type(nInd[i]) newInfo = self._axisSlice(i, nInd[i]) name = None colName = None for k in newInfo: if k == 'cols': if 'cols' not in extraInfo: extraInfo['cols'] = [] extraInfo['cols'].append(newInfo[k]) if 'units' in newInfo[k]: extraInfo['units'] = newInfo[k]['units'] if 'name' in newInfo[k]: colName = newInfo[k]['name'] elif k == 'name': name = newInfo[k] else: if k not in extraInfo: extraInfo[k] = newInfo[k] extraInfo[k] = newInfo[k] if 'name' not in extraInfo: if name is None: if colName is not None: extraInfo['name'] = colName else: if colName is not None: extraInfo['name'] = str(name) + ': ' + str(colName) else: extraInfo['name'] = name #print "Lost info:", newInfo #a._info[i] = None #if 'name' in newInfo: #a._info[-1][newInfo['name']] = newInfo info.append(extraInfo) #self._infoOwned = False #while None in a._info: #a._info.remove(None) return MetaArray(a, info=info) @property def ndim(self): return len(self.shape) ## hdf5 objects do not have ndim property. @property def shape(self): return self._data.shape @property def dtype(self): return self._data.dtype def __len__(self): return len(self._data) def __getslice__(self, *args): return self.__getitem__(slice(*args)) def __setitem__(self, ind, val): nInd = self._interpretIndexes(ind) try: self._data[nInd] = val except: print(self, nInd, val) raise def __getattr__(self, attr): if attr in self.wrapMethods: return getattr(self._data, attr) else: raise AttributeError(attr) #return lambda *args, **kwargs: MetaArray(getattr(a.view(ndarray), attr)(*args, **kwargs) def __eq__(self, b): return self._binop('__eq__', b) def __ne__(self, b): return self._binop('__ne__', b) #if isinstance(b, MetaArray): #b = b.asarray() #return self.asarray() != b def __sub__(self, b): return self._binop('__sub__', b) #if isinstance(b, MetaArray): #b = b.asarray() #return MetaArray(self.asarray() - b, info=self.infoCopy()) def __add__(self, b): return self._binop('__add__', b) def __mul__(self, b): return self._binop('__mul__', b) def __div__(self, b): return self._binop('__div__', b) def __truediv__(self, b): return self._binop('__truediv__', b) def _binop(self, op, b): if isinstance(b, MetaArray): b = b.asarray() a = self.asarray() c = getattr(a, op)(b) if c.shape != a.shape: raise Exception("Binary operators with MetaArray must return an array of the same shape (this shape is %s, result shape was %s)" % (a.shape, c.shape)) return MetaArray(c, info=self.infoCopy()) def asarray(self): if isinstance(self._data, np.ndarray): return self._data else: return np.array(self._data) def __array__(self, dtype=None): ## supports np.array(metaarray_instance) if dtype is None: return self.asarray() else: return self.asarray().astype(dtype) def view(self, typ): ## deprecated; kept for backward compatibility if typ is np.ndarray: return self.asarray() else: raise Exception('invalid view type: %s' % str(typ)) def axisValues(self, axis): """Return the list of values for an axis""" ax = self._interpretAxis(axis) if 'values' in self._info[ax]: return self._info[ax]['values'] else: raise Exception('Array axis %s (%d) has no associated values.' % (str(axis), ax)) def xvals(self, axis): """Synonym for axisValues()""" return self.axisValues(axis) def axisHasValues(self, axis): ax = self._interpretAxis(axis) return 'values' in self._info[ax] def axisHasColumns(self, axis): ax = self._interpretAxis(axis) return 'cols' in self._info[ax] def axisUnits(self, axis): """Return the units for axis""" ax = self._info[self._interpretAxis(axis)] if 'units' in ax: return ax['units'] def hasColumn(self, axis, col): ax = self._info[self._interpretAxis(axis)] if 'cols' in ax: for c in ax['cols']: if c['name'] == col: return True return False def listColumns(self, axis=None): """Return a list of column names for axis. If axis is not specified, then return a dict of {axisName: (column names), ...}.""" if axis is None: ret = {} for i in range(self.ndim): if 'cols' in self._info[i]: cols = [c['name'] for c in self._info[i]['cols']] else: cols = [] ret[self.axisName(i)] = cols return ret else: axis = self._interpretAxis(axis) return [c['name'] for c in self._info[axis]['cols']] def columnName(self, axis, col): ax = self._info[self._interpretAxis(axis)] return ax['cols'][col]['name'] def axisName(self, n): return self._info[n].get('name', n) def columnUnits(self, axis, column): """Return the units for column in axis""" ax = self._info[self._interpretAxis(axis)] if 'cols' in ax: for c in ax['cols']: if c['name'] == column: return c['units'] raise Exception("Axis %s has no column named %s" % (str(axis), str(column))) else: raise Exception("Axis %s has no column definitions" % str(axis)) def rowsort(self, axis, key=0): """Return this object with all records sorted along axis using key as the index to the values to compare. Does not yet modify meta info.""" ## make sure _info is copied locally before modifying it! keyList = self[key] order = keyList.argsort() if type(axis) == int: ind = [slice(None)]*axis ind.append(order) elif isinstance(axis, basestring): ind = (slice(axis, order),) return self[tuple(ind)] def append(self, val, axis): """Return this object with val appended along axis. Does not yet combine meta info.""" ## make sure _info is copied locally before modifying it! s = list(self.shape) axis = self._interpretAxis(axis) s[axis] += 1 n = MetaArray(tuple(s), info=self._info, dtype=self.dtype) ind = [slice(None)]*self.ndim ind[axis] = slice(None,-1) n[tuple(ind)] = self ind[axis] = -1 n[tuple(ind)] = val return n def extend(self, val, axis): """Return the concatenation along axis of this object and val. Does not yet combine meta info.""" ## make sure _info is copied locally before modifying it! axis = self._interpretAxis(axis) return MetaArray(np.concatenate(self, val, axis), info=self._info) def infoCopy(self, axis=None): """Return a deep copy of the axis meta info for this object""" if axis is None: return copy.deepcopy(self._info) else: return copy.deepcopy(self._info[self._interpretAxis(axis)]) def copy(self): return MetaArray(self._data.copy(), info=self.infoCopy()) def _interpretIndexes(self, ind): #print "interpret", ind if not isinstance(ind, tuple): ## a list of slices should be interpreted as a tuple of slices. if isinstance(ind, list) and len(ind) > 0 and isinstance(ind[0], slice): ind = tuple(ind) ## everything else can just be converted to a length-1 tuple else: ind = (ind,) nInd = [slice(None)]*self.ndim numOk = True ## Named indices not started yet; numbered sill ok for i in range(0,len(ind)): (axis, index, isNamed) = self._interpretIndex(ind[i], i, numOk) #try: nInd[axis] = index #except: #print "ndim:", self.ndim #print "axis:", axis #print "index spec:", ind[i] #print "index num:", index #raise if isNamed: numOk = False return tuple(nInd) def _interpretAxis(self, axis): if isinstance(axis, basestring) or isinstance(axis, tuple): return self._getAxis(axis) else: return axis def _interpretIndex(self, ind, pos, numOk): #print "Interpreting index", ind, pos, numOk ## should probably check for int first to speed things up.. if type(ind) is int: if not numOk: raise Exception("string and integer indexes may not follow named indexes") #print " normal numerical index" return (pos, ind, False) if MetaArray.isNameType(ind): if not numOk: raise Exception("string and integer indexes may not follow named indexes") #print " String index, column is ", self._getIndex(pos, ind) return (pos, self._getIndex(pos, ind), False) elif type(ind) is slice: #print " Slice index" if MetaArray.isNameType(ind.start) or MetaArray.isNameType(ind.stop): ## Not an actual slice! #print " ..not a real slice" axis = self._interpretAxis(ind.start) #print " axis is", axis ## x[Axis:Column] if MetaArray.isNameType(ind.stop): #print " column name, column is ", self._getIndex(axis, ind.stop) index = self._getIndex(axis, ind.stop) ## x[Axis:min:max] elif (isinstance(ind.stop, float) or isinstance(ind.step, float)) and ('values' in self._info[axis]): #print " axis value range" if ind.stop is None: mask = self.xvals(axis) < ind.step elif ind.step is None: mask = self.xvals(axis) >= ind.stop else: mask = (self.xvals(axis) >= ind.stop) * (self.xvals(axis) < ind.step) ##print "mask:", mask index = mask ## x[Axis:columnIndex] elif isinstance(ind.stop, int) or isinstance(ind.step, int): #print " normal slice after named axis" if ind.step is None: index = ind.stop else: index = slice(ind.stop, ind.step) ## x[Axis: [list]] elif type(ind.stop) is list: #print " list of indexes from named axis" index = [] for i in ind.stop: if type(i) is int: index.append(i) elif MetaArray.isNameType(i): index.append(self._getIndex(axis, i)) else: ## unrecognized type, try just passing on to array index = ind.stop break else: #print " other type.. forward on to array for handling", type(ind.stop) index = ind.stop #print "Axis %s (%s) : %s" % (ind.start, str(axis), str(type(index))) #if type(index) is np.ndarray: #print " ", index.shape return (axis, index, True) else: #print " Looks like a real slice, passing on to array" return (pos, ind, False) elif type(ind) is list: #print " List index., interpreting each element individually" indList = [self._interpretIndex(i, pos, numOk)[1] for i in ind] return (pos, indList, False) else: if not numOk: raise Exception("string and integer indexes may not follow named indexes") #print " normal numerical index" return (pos, ind, False) def _getAxis(self, name): for i in range(0, len(self._info)): axis = self._info[i] if 'name' in axis and axis['name'] == name: return i raise Exception("No axis named %s.\n info=%s" % (name, self._info)) def _getIndex(self, axis, name): ax = self._info[axis] if ax is not None and 'cols' in ax: for i in range(0, len(ax['cols'])): if 'name' in ax['cols'][i] and ax['cols'][i]['name'] == name: return i raise Exception("Axis %d has no column named %s.\n info=%s" % (axis, name, self._info)) def _axisCopy(self, i): return copy.deepcopy(self._info[i]) def _axisSlice(self, i, cols): #print "axisSlice", i, cols if 'cols' in self._info[i] or 'values' in self._info[i]: ax = self._axisCopy(i) if 'cols' in ax: #print " slicing columns..", array(ax['cols']), cols sl = np.array(ax['cols'])[cols] if isinstance(sl, np.ndarray): sl = list(sl) ax['cols'] = sl #print " result:", ax['cols'] if 'values' in ax: ax['values'] = np.array(ax['values'])[cols] else: ax = self._info[i] #print " ", ax return ax def prettyInfo(self): s = '' titles = [] maxl = 0 for i in range(len(self._info)-1): ax = self._info[i] axs = '' if 'name' in ax: axs += '"%s"' % str(ax['name']) else: axs += "%d" % i if 'units' in ax: axs += " (%s)" % str(ax['units']) titles.append(axs) if len(axs) > maxl: maxl = len(axs) for i in range(min(self.ndim, len(self._info) - 1)): ax = self._info[i] axs = titles[i] axs += '%s[%d] :' % (' ' * (maxl - len(axs) + 5 - len(str(self.shape[i]))), self.shape[i]) if 'values' in ax: if self.shape[i] > 0: v0 = ax['values'][0] axs += " values: [%g" % (v0) if self.shape[i] > 1: v1 = ax['values'][-1] axs += " ... %g] (step %g)" % (v1, (v1 - v0) / (self.shape[i] - 1)) else: axs += "]" else: axs += " values: []" if 'cols' in ax: axs += " columns: " colstrs = [] for c in range(len(ax['cols'])): col = ax['cols'][c] cs = str(col.get('name', c)) if 'units' in col: cs += " (%s)" % col['units'] colstrs.append(cs) axs += '[' + ', '.join(colstrs) + ']' s += axs + "\n" s += str(self._info[-1]) return s def __repr__(self): return "%s\n-----------------------------------------------\n%s" % (self.view(np.ndarray).__repr__(), self.prettyInfo()) def __str__(self): return self.__repr__() def axisCollapsingFn(self, fn, axis=None, *args, **kargs): #arr = self.view(np.ndarray) fn = getattr(self._data, fn) if axis is None: return fn(axis, *args, **kargs) else: info = self.infoCopy() axis = self._interpretAxis(axis) info.pop(axis) return MetaArray(fn(axis, *args, **kargs), info=info) def mean(self, axis=None, *args, **kargs): return self.axisCollapsingFn('mean', axis, *args, **kargs) def min(self, axis=None, *args, **kargs): return self.axisCollapsingFn('min', axis, *args, **kargs) def max(self, axis=None, *args, **kargs): return self.axisCollapsingFn('max', axis, *args, **kargs) def transpose(self, *args): if len(args) == 1 and hasattr(args[0], '__iter__'): order = args[0] else: order = args order = [self._interpretAxis(ax) for ax in order] infoOrder = order + list(range(len(order), len(self._info))) info = [self._info[i] for i in infoOrder] order = order + list(range(len(order), self.ndim)) try: if self._isHDF: return MetaArray(np.array(self._data).transpose(order), info=info) else: return MetaArray(self._data.transpose(order), info=info) except: print(order) raise #### File I/O Routines def readFile(self, filename, **kwargs): """Load the data and meta info stored in *filename* Different arguments are allowed depending on the type of file. For HDF5 files: *writable* (bool) if True, then any modifications to data in the array will be stored to disk. *readAllData* (bool) if True, then all data in the array is immediately read from disk and the file is closed (this is the default for files < 500MB). Otherwise, the file will be left open and data will be read only as requested (this is the default for files >= 500MB). """ ## decide which read function to use with open(filename, 'rb') as fd: magic = fd.read(8) if magic == b'\x89HDF\r\n\x1a\n': fd.close() self._readHDF5(filename, **kwargs) self._isHDF = True else: fd.seek(0) meta = MetaArray._readMeta(fd) if not kwargs.get("readAllData", True): self._data = np.empty(meta['shape'], dtype=meta['type']) if 'version' in meta: ver = meta['version'] else: ver = 1 rFuncName = '_readData%s' % str(ver) if not hasattr(MetaArray, rFuncName): raise Exception("This MetaArray library does not support array version '%s'" % ver) rFunc = getattr(self, rFuncName) rFunc(fd, meta, **kwargs) self._isHDF = False @staticmethod def _readMeta(fd): """Read meta array from the top of a file. Read lines until a blank line is reached. This function should ideally work for ALL versions of MetaArray. """ meta = u'' ## Read meta information until the first blank line while True: line = fd.readline().strip() if line == '': break meta += line ret = eval(meta) #print ret return ret def _readData1(self, fd, meta, mmap=False, **kwds): ## Read array data from the file descriptor for MetaArray v1 files ## read in axis values for any axis that specifies a length frameSize = 1 for ax in meta['info']: if 'values_len' in ax: ax['values'] = np.fromstring(fd.read(ax['values_len']), dtype=ax['values_type']) frameSize *= ax['values_len'] del ax['values_len'] del ax['values_type'] self._info = meta['info'] if not kwds.get("readAllData", True): return ## the remaining data is the actual array if mmap: subarr = np.memmap(fd, dtype=meta['type'], mode='r', shape=meta['shape']) else: subarr = np.fromstring(fd.read(), dtype=meta['type']) subarr.shape = meta['shape'] self._data = subarr def _readData2(self, fd, meta, mmap=False, subset=None, **kwds): ## read in axis values dynAxis = None frameSize = 1 ## read in axis values for any axis that specifies a length for i in range(len(meta['info'])): ax = meta['info'][i] if 'values_len' in ax: if ax['values_len'] == 'dynamic': if dynAxis is not None: raise Exception("MetaArray has more than one dynamic axis! (this is not allowed)") dynAxis = i else: ax['values'] = np.fromstring(fd.read(ax['values_len']), dtype=ax['values_type']) frameSize *= ax['values_len'] del ax['values_len'] del ax['values_type'] self._info = meta['info'] if not kwds.get("readAllData", True): return ## No axes are dynamic, just read the entire array in at once if dynAxis is None: #if rewriteDynamic is not None: #raise Exception("") if meta['type'] == 'object': if mmap: raise Exception('memmap not supported for arrays with dtype=object') subarr = pickle.loads(fd.read()) else: if mmap: subarr = np.memmap(fd, dtype=meta['type'], mode='r', shape=meta['shape']) else: subarr = np.fromstring(fd.read(), dtype=meta['type']) #subarr = subarr.view(subtype) subarr.shape = meta['shape'] #subarr._info = meta['info'] ## One axis is dynamic, read in a frame at a time else: if mmap: raise Exception('memmap not supported for non-contiguous arrays. Use rewriteContiguous() to convert.') ax = meta['info'][dynAxis] xVals = [] frames = [] frameShape = list(meta['shape']) frameShape[dynAxis] = 1 frameSize = np.prod(frameShape) n = 0 while True: ## Extract one non-blank line while True: line = fd.readline() if line != '\n': break if line == '': break ## evaluate line inf = eval(line) ## read data block #print "read %d bytes as %s" % (inf['len'], meta['type']) if meta['type'] == 'object': data = pickle.loads(fd.read(inf['len'])) else: data = np.fromstring(fd.read(inf['len']), dtype=meta['type']) if data.size != frameSize * inf['numFrames']: #print data.size, frameSize, inf['numFrames'] raise Exception("Wrong frame size in MetaArray file! (frame %d)" % n) ## read in data block shape = list(frameShape) shape[dynAxis] = inf['numFrames'] data.shape = shape if subset is not None: dSlice = subset[dynAxis] if dSlice.start is None: dStart = 0 else: dStart = max(0, dSlice.start - n) if dSlice.stop is None: dStop = data.shape[dynAxis] else: dStop = min(data.shape[dynAxis], dSlice.stop - n) newSubset = list(subset[:]) newSubset[dynAxis] = slice(dStart, dStop) if dStop > dStart: frames.append(data[tuple(newSubset)].copy()) else: frames.append(data) n += inf['numFrames'] if 'xVals' in inf: xVals.extend(inf['xVals']) subarr = np.concatenate(frames, axis=dynAxis) if len(xVals)> 0: ax['values'] = np.array(xVals, dtype=ax['values_type']) del ax['values_len'] del ax['values_type'] self._info = meta['info'] self._data = subarr def _readHDF5(self, fileName, readAllData=None, writable=False, **kargs): if 'close' in kargs and readAllData is None: ## for backward compatibility readAllData = kargs['close'] if readAllData is True and writable is True: raise Exception("Incompatible arguments: readAllData=True and writable=True") if not HAVE_HDF5: try: assert writable==False assert readAllData != False self._readHDF5Remote(fileName) return except: raise Exception("The file '%s' is HDF5-formatted, but the HDF5 library (h5py) was not found." % fileName) ## by default, readAllData=True for files < 500MB if readAllData is None: size = os.stat(fileName).st_size readAllData = (size < 500e6) if writable is True: mode = 'r+' else: mode = 'r' f = h5py.File(fileName, mode) ver = f.attrs['MetaArray'] try: ver = ver.decode('utf-8') except: pass if ver > MetaArray.version: print("Warning: This file was written with MetaArray version %s, but you are using version %s. (Will attempt to read anyway)" % (str(ver), str(MetaArray.version))) meta = MetaArray.readHDF5Meta(f['info']) self._info = meta if writable or not readAllData: ## read all data, convert to ndarray, close file self._data = f['data'] self._openFile = f else: self._data = f['data'][:] f.close() def _readHDF5Remote(self, fileName): ## Used to read HDF5 files via remote process. ## This is needed in the case that HDF5 is not importable due to the use of python-dbg. proc = getattr(MetaArray, '_hdf5Process', None) if proc == False: raise Exception('remote read failed') if proc == None: from .. import multiprocess as mp #print "new process" proc = mp.Process(executable='/usr/bin/python') proc.setProxyOptions(deferGetattr=True) MetaArray._hdf5Process = proc MetaArray._h5py_metaarray = proc._import('pyqtgraph.metaarray') ma = MetaArray._h5py_metaarray.MetaArray(file=fileName) self._data = ma.asarray()._getValue() self._info = ma._info._getValue() @staticmethod def mapHDF5Array(data, writable=False): off = data.id.get_offset() if writable: mode = 'r+' else: mode = 'r' if off is None: raise Exception("This dataset uses chunked storage; it can not be memory-mapped. (store using mappable=True)") return np.memmap(filename=data.file.filename, offset=off, dtype=data.dtype, shape=data.shape, mode=mode) @staticmethod def readHDF5Meta(root, mmap=False): data = {} ## Pull list of values from attributes and child objects for k in root.attrs: val = root.attrs[k] if isinstance(val, bytes): val = val.decode() if isinstance(val, basestring): ## strings need to be re-evaluated to their original types try: val = eval(val) except: raise Exception('Can not evaluate string: "%s"' % val) data[k] = val for k in root: obj = root[k] if isinstance(obj, h5py.highlevel.Group): val = MetaArray.readHDF5Meta(obj) elif isinstance(obj, h5py.highlevel.Dataset): if mmap: val = MetaArray.mapHDF5Array(obj) else: val = obj[:] else: raise Exception("Don't know what to do with type '%s'" % str(type(obj))) data[k] = val typ = root.attrs['_metaType_'] try: typ = typ.decode('utf-8') except: pass del data['_metaType_'] if typ == 'dict': return data elif typ == 'list' or typ == 'tuple': d2 = [None]*len(data) for k in data: d2[int(k)] = data[k] if typ == 'tuple': d2 = tuple(d2) return d2 else: raise Exception("Don't understand metaType '%s'" % typ) def write(self, fileName, **opts): """Write this object to a file. The object can be restored by calling MetaArray(file=fileName) opts: appendAxis: the name (or index) of the appendable axis. Allows the array to grow. appendKeys: a list of keys (other than "values") for metadata to append to on the appendable axis. compression: None, 'gzip' (good compression), 'lzf' (fast compression), etc. chunks: bool or tuple specifying chunk shape """ if USE_HDF5 is False: return self.writeMa(fileName, **opts) elif HAVE_HDF5 is True: return self.writeHDF5(fileName, **opts) else: raise Exception("h5py is required for writing .ma hdf5 files, but it could not be imported.") def writeMeta(self, fileName): """Used to re-write meta info to the given file. This feature is only available for HDF5 files.""" f = h5py.File(fileName, 'r+') if f.attrs['MetaArray'] != MetaArray.version: raise Exception("The file %s was created with a different version of MetaArray. Will not modify." % fileName) del f['info'] self.writeHDF5Meta(f, 'info', self._info) f.close() def writeHDF5(self, fileName, **opts): ## default options for writing datasets comp = self.defaultCompression if isinstance(comp, tuple): comp, copts = comp else: copts = None dsOpts = { 'compression': comp, 'chunks': True, } if copts is not None: dsOpts['compression_opts'] = copts ## if there is an appendable axis, then we can guess the desired chunk shape (optimized for appending) appAxis = opts.get('appendAxis', None) if appAxis is not None: appAxis = self._interpretAxis(appAxis) cs = [min(100000, x) for x in self.shape] cs[appAxis] = 1 dsOpts['chunks'] = tuple(cs) ## if there are columns, then we can guess a different chunk shape ## (read one column at a time) else: cs = [min(100000, x) for x in self.shape] for i in range(self.ndim): if 'cols' in self._info[i]: cs[i] = 1 dsOpts['chunks'] = tuple(cs) ## update options if they were passed in for k in dsOpts: if k in opts: dsOpts[k] = opts[k] ## If mappable is in options, it disables chunking/compression if opts.get('mappable', False): dsOpts = { 'chunks': None, 'compression': None } ## set maximum shape to allow expansion along appendAxis append = False if appAxis is not None: maxShape = list(self.shape) ax = self._interpretAxis(appAxis) maxShape[ax] = None if os.path.exists(fileName): append = True dsOpts['maxshape'] = tuple(maxShape) else: dsOpts['maxshape'] = None if append: f = h5py.File(fileName, 'r+') if f.attrs['MetaArray'] != MetaArray.version: raise Exception("The file %s was created with a different version of MetaArray. Will not modify." % fileName) ## resize data and write in new values data = f['data'] shape = list(data.shape) shape[ax] += self.shape[ax] data.resize(tuple(shape)) sl = [slice(None)] * len(data.shape) sl[ax] = slice(-self.shape[ax], None) data[tuple(sl)] = self.view(np.ndarray) ## add axis values if they are present. axKeys = ["values"] axKeys.extend(opts.get("appendKeys", [])) axInfo = f['info'][str(ax)] for key in axKeys: if key in axInfo: v = axInfo[key] v2 = self._info[ax][key] shape = list(v.shape) shape[0] += v2.shape[0] v.resize(shape) v[-v2.shape[0]:] = v2 else: raise TypeError('Cannot append to axis info key "%s"; this key is not present in the target file.' % key) f.close() else: f = h5py.File(fileName, 'w') f.attrs['MetaArray'] = MetaArray.version #print dsOpts f.create_dataset('data', data=self.view(np.ndarray), **dsOpts) ## dsOpts is used when storing meta data whenever an array is encountered ## however, 'chunks' will no longer be valid for these arrays if it specifies a chunk shape. ## 'maxshape' is right-out. if isinstance(dsOpts['chunks'], tuple): dsOpts['chunks'] = True if 'maxshape' in dsOpts: del dsOpts['maxshape'] self.writeHDF5Meta(f, 'info', self._info, **dsOpts) f.close() def writeHDF5Meta(self, root, name, data, **dsOpts): if isinstance(data, np.ndarray): dsOpts['maxshape'] = (None,) + data.shape[1:] root.create_dataset(name, data=data, **dsOpts) elif isinstance(data, list) or isinstance(data, tuple): gr = root.create_group(name) if isinstance(data, list): gr.attrs['_metaType_'] = 'list' else: gr.attrs['_metaType_'] = 'tuple' #n = int(np.log10(len(data))) + 1 for i in range(len(data)): self.writeHDF5Meta(gr, str(i), data[i], **dsOpts) elif isinstance(data, dict): gr = root.create_group(name) gr.attrs['_metaType_'] = 'dict' for k, v in data.items(): self.writeHDF5Meta(gr, k, v, **dsOpts) elif isinstance(data, int) or isinstance(data, float) or isinstance(data, np.integer) or isinstance(data, np.floating): root.attrs[name] = data else: try: ## strings, bools, None are stored as repr() strings root.attrs[name] = repr(data) except: print("Can not store meta data of type '%s' in HDF5. (key is '%s')" % (str(type(data)), str(name))) raise def writeMa(self, fileName, appendAxis=None, newFile=False): """Write an old-style .ma file""" meta = {'shape':self.shape, 'type':str(self.dtype), 'info':self.infoCopy(), 'version':MetaArray.version} axstrs = [] ## copy out axis values for dynamic axis if requested if appendAxis is not None: if MetaArray.isNameType(appendAxis): appendAxis = self._interpretAxis(appendAxis) ax = meta['info'][appendAxis] ax['values_len'] = 'dynamic' if 'values' in ax: ax['values_type'] = str(ax['values'].dtype) dynXVals = ax['values'] del ax['values'] else: dynXVals = None ## Generate axis data string, modify axis info so we know how to read it back in later for ax in meta['info']: if 'values' in ax: axstrs.append(ax['values'].tostring()) ax['values_len'] = len(axstrs[-1]) ax['values_type'] = str(ax['values'].dtype) del ax['values'] ## Decide whether to output the meta block for a new file if not newFile: ## If the file does not exist or its size is 0, then we must write the header newFile = (not os.path.exists(fileName)) or (os.stat(fileName).st_size == 0) ## write data to file if appendAxis is None or newFile: fd = open(fileName, 'wb') fd.write(str(meta) + '\n\n') for ax in axstrs: fd.write(ax) else: fd = open(fileName, 'ab') if self.dtype != object: dataStr = self.view(np.ndarray).tostring() else: dataStr = pickle.dumps(self.view(np.ndarray)) #print self.size, len(dataStr), self.dtype if appendAxis is not None: frameInfo = {'len':len(dataStr), 'numFrames':self.shape[appendAxis]} if dynXVals is not None: frameInfo['xVals'] = list(dynXVals) fd.write('\n'+str(frameInfo)+'\n') fd.write(dataStr) fd.close() def writeCsv(self, fileName=None): """Write 2D array to CSV file or return the string if no filename is given""" if self.ndim > 2: raise Exception("CSV Export is only for 2D arrays") if fileName is not None: file = open(fileName, 'w') ret = '' if 'cols' in self._info[0]: s = ','.join([x['name'] for x in self._info[0]['cols']]) + '\n' if fileName is not None: file.write(s) else: ret += s for row in range(0, self.shape[1]): s = ','.join(["%g" % x for x in self[:, row]]) + '\n' if fileName is not None: file.write(s) else: ret += s if fileName is not None: file.close() else: return ret #class H5MetaList(): #def rewriteContiguous(fileName, newName): #"""Rewrite a dynamic array file as contiguous""" #def _readData2(fd, meta, subtype, mmap): ### read in axis values #dynAxis = None #frameSize = 1 ### read in axis values for any axis that specifies a length #for i in range(len(meta['info'])): #ax = meta['info'][i] #if ax.has_key('values_len'): #if ax['values_len'] == 'dynamic': #if dynAxis is not None: #raise Exception("MetaArray has more than one dynamic axis! (this is not allowed)") #dynAxis = i #else: #ax['values'] = fromstring(fd.read(ax['values_len']), dtype=ax['values_type']) #frameSize *= ax['values_len'] #del ax['values_len'] #del ax['values_type'] ### No axes are dynamic, just read the entire array in at once #if dynAxis is None: #raise Exception('Array has no dynamic axes.') ### One axis is dynamic, read in a frame at a time #else: #if mmap: #raise Exception('memmap not supported for non-contiguous arrays. Use rewriteContiguous() to convert.') #ax = meta['info'][dynAxis] #xVals = [] #frames = [] #frameShape = list(meta['shape']) #frameShape[dynAxis] = 1 #frameSize = np.prod(frameShape) #n = 0 #while True: ### Extract one non-blank line #while True: #line = fd.readline() #if line != '\n': #break #if line == '': #break ### evaluate line #inf = eval(line) ### read data block ##print "read %d bytes as %s" % (inf['len'], meta['type']) #if meta['type'] == 'object': #data = pickle.loads(fd.read(inf['len'])) #else: #data = fromstring(fd.read(inf['len']), dtype=meta['type']) #if data.size != frameSize * inf['numFrames']: ##print data.size, frameSize, inf['numFrames'] #raise Exception("Wrong frame size in MetaArray file! (frame %d)" % n) ### read in data block #shape = list(frameShape) #shape[dynAxis] = inf['numFrames'] #data.shape = shape #frames.append(data) #n += inf['numFrames'] #if 'xVals' in inf: #xVals.extend(inf['xVals']) #subarr = np.concatenate(frames, axis=dynAxis) #if len(xVals)> 0: #ax['values'] = array(xVals, dtype=ax['values_type']) #del ax['values_len'] #del ax['values_type'] #subarr = subarr.view(subtype) #subarr._info = meta['info'] #return subarr if __name__ == '__main__': ## Create an array with every option possible arr = np.zeros((2, 5, 3, 5), dtype=int) for i in range(arr.shape[0]): for j in range(arr.shape[1]): for k in range(arr.shape[2]): for l in range(arr.shape[3]): arr[i,j,k,l] = (i+1)*1000 + (j+1)*100 + (k+1)*10 + (l+1) info = [ axis('Axis1'), axis('Axis2', values=[1,2,3,4,5]), axis('Axis3', cols=[ ('Ax3Col1'), ('Ax3Col2', 'mV', 'Axis3 Column2'), (('Ax3','Col3'), 'A', 'Axis3 Column3')]), {'name': 'Axis4', 'values': np.array([1.1, 1.2, 1.3, 1.4, 1.5]), 'units': 's'}, {'extra': 'info'} ] ma = MetaArray(arr, info=info) print("==== Original Array =======") print(ma) print("\n\n") #### Tests follow: #### Index/slice tests: check that all values and meta info are correct after slice print("\n -- normal integer indexing\n") print("\n ma[1]") print(ma[1]) print("\n ma[1, 2:4]") print(ma[1, 2:4]) print("\n ma[1, 1:5:2]") print(ma[1, 1:5:2]) print("\n -- named axis indexing\n") print("\n ma['Axis2':3]") print(ma['Axis2':3]) print("\n ma['Axis2':3:5]") print(ma['Axis2':3:5]) print("\n ma[1, 'Axis2':3]") print(ma[1, 'Axis2':3]) print("\n ma[:, 'Axis2':3]") print(ma[:, 'Axis2':3]) print("\n ma['Axis2':3, 'Axis4':0:2]") print(ma['Axis2':3, 'Axis4':0:2]) print("\n -- column name indexing\n") print("\n ma['Axis3':'Ax3Col1']") print(ma['Axis3':'Ax3Col1']) print("\n ma['Axis3':('Ax3','Col3')]") print(ma['Axis3':('Ax3','Col3')]) print("\n ma[:, :, 'Ax3Col2']") print(ma[:, :, 'Ax3Col2']) print("\n ma[:, :, ('Ax3','Col3')]") print(ma[:, :, ('Ax3','Col3')]) print("\n -- axis value range indexing\n") print("\n ma['Axis2':1.5:4.5]") print(ma['Axis2':1.5:4.5]) print("\n ma['Axis4':1.15:1.45]") print(ma['Axis4':1.15:1.45]) print("\n ma['Axis4':1.15:1.25]") print(ma['Axis4':1.15:1.25]) print("\n -- list indexing\n") print("\n ma[:, [0,2,4]]") print(ma[:, [0,2,4]]) print("\n ma['Axis4':[0,2,4]]") print(ma['Axis4':[0,2,4]]) print("\n ma['Axis3':[0, ('Ax3','Col3')]]") print(ma['Axis3':[0, ('Ax3','Col3')]]) print("\n -- boolean indexing\n") print("\n ma[:, array([True, True, False, True, False])]") print(ma[:, np.array([True, True, False, True, False])]) print("\n ma['Axis4':array([True, False, False, False])]") print(ma['Axis4':np.array([True, False, False, False])]) #### Array operations # - Concatenate # - Append # - Extend # - Rowsort #### File I/O tests print("\n================ File I/O Tests ===================\n") import tempfile tf = tempfile.mktemp() tf = 'test.ma' # write whole array print("\n -- write/read test") ma.write(tf) ma2 = MetaArray(file=tf) #print ma2 print("\nArrays are equivalent:", (ma == ma2).all()) #print "Meta info is equivalent:", ma.infoCopy() == ma2.infoCopy() os.remove(tf) # CSV write # append mode print("\n================append test (%s)===============" % tf) ma['Axis2':0:2].write(tf, appendAxis='Axis2') for i in range(2,ma.shape[1]): ma['Axis2':[i]].write(tf, appendAxis='Axis2') ma2 = MetaArray(file=tf) #print ma2 print("\nArrays are equivalent:", (ma == ma2).all()) #print "Meta info is equivalent:", ma.infoCopy() == ma2.infoCopy() os.remove(tf) ## memmap test print("\n==========Memmap test============") ma.write(tf, mappable=True) ma2 = MetaArray(file=tf, mmap=True) print("\nArrays are equivalent:", (ma == ma2).all()) os.remove(tf)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/metaarray/readMeta.m
.m
1,752
87
function f = readMeta(file) info = hdf5info(file); f = readMetaRecursive(info.GroupHierarchy.Groups(1)); end function f = readMetaRecursive(root) typ = 0; for i = 1:length(root.Attributes) if strcmp(root.Attributes(i).Shortname, '_metaType_') typ = root.Attributes(i).Value.Data; break end end if typ == 0 printf('group has no _metaType_') typ = 'dict'; end list = 0; if strcmp(typ, 'list') || strcmp(typ, 'tuple') data = {}; list = 1; elseif strcmp(typ, 'dict') data = struct(); else printf('Unrecognized meta type %s', typ); data = struct(); end for i = 1:length(root.Attributes) name = root.Attributes(i).Shortname; if strcmp(name, '_metaType_') continue end val = root.Attributes(i).Value; if isa(val, 'hdf5.h5string') val = val.Data; end if list ind = str2num(name)+1; data{ind} = val; else data.(name) = val; end end for i = 1:length(root.Datasets) fullName = root.Datasets(i).Name; name = stripName(fullName); file = root.Datasets(i).Filename; data2 = hdf5read(file, fullName); if list ind = str2num(name)+1; data{ind} = data2; else data.(name) = data2; end end for i = 1:length(root.Groups) name = stripName(root.Groups(i).Name); data2 = readMetaRecursive(root.Groups(i)); if list ind = str2num(name)+1; data{ind} = data2; else data.(name) = data2; end end f = data; return; end function f = stripName(str) inds = strfind(str, '/'); if isempty(inds) f = str; else f = str(inds(length(inds))+1:length(str)); end end
MATLAB
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/canvas/TransformGuiTemplate_pyside.py
.py
2,827
56
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyqtgraph/canvas/TransformGuiTemplate.ui' # # Created: Wed Nov 9 17:57:16 2016 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(224, 117) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth()) Form.setSizePolicy(sizePolicy) self.verticalLayout = QtGui.QVBoxLayout(Form) self.verticalLayout.setSpacing(1) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.translateLabel = QtGui.QLabel(Form) self.translateLabel.setObjectName("translateLabel") self.verticalLayout.addWidget(self.translateLabel) self.rotateLabel = QtGui.QLabel(Form) self.rotateLabel.setObjectName("rotateLabel") self.verticalLayout.addWidget(self.rotateLabel) self.scaleLabel = QtGui.QLabel(Form) self.scaleLabel.setObjectName("scaleLabel") self.verticalLayout.addWidget(self.scaleLabel) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.mirrorImageBtn = QtGui.QPushButton(Form) self.mirrorImageBtn.setToolTip("") self.mirrorImageBtn.setObjectName("mirrorImageBtn") self.horizontalLayout.addWidget(self.mirrorImageBtn) self.reflectImageBtn = QtGui.QPushButton(Form) self.reflectImageBtn.setObjectName("reflectImageBtn") self.horizontalLayout.addWidget(self.reflectImageBtn) self.verticalLayout.addLayout(self.horizontalLayout) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8)) self.translateLabel.setText(QtGui.QApplication.translate("Form", "Translate:", None, QtGui.QApplication.UnicodeUTF8)) self.rotateLabel.setText(QtGui.QApplication.translate("Form", "Rotate:", None, QtGui.QApplication.UnicodeUTF8)) self.scaleLabel.setText(QtGui.QApplication.translate("Form", "Scale:", None, QtGui.QApplication.UnicodeUTF8)) self.mirrorImageBtn.setText(QtGui.QApplication.translate("Form", "Mirror", None, QtGui.QApplication.UnicodeUTF8)) self.reflectImageBtn.setText(QtGui.QApplication.translate("Form", "Reflect", None, QtGui.QApplication.UnicodeUTF8))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/canvas/TransformGuiTemplate_pyqt.py
.py
2,986
69
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyqtgraph/canvas/TransformGuiTemplate.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(224, 117) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth()) Form.setSizePolicy(sizePolicy) self.verticalLayout = QtGui.QVBoxLayout(Form) self.verticalLayout.setMargin(0) self.verticalLayout.setSpacing(1) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.translateLabel = QtGui.QLabel(Form) self.translateLabel.setObjectName(_fromUtf8("translateLabel")) self.verticalLayout.addWidget(self.translateLabel) self.rotateLabel = QtGui.QLabel(Form) self.rotateLabel.setObjectName(_fromUtf8("rotateLabel")) self.verticalLayout.addWidget(self.rotateLabel) self.scaleLabel = QtGui.QLabel(Form) self.scaleLabel.setObjectName(_fromUtf8("scaleLabel")) self.verticalLayout.addWidget(self.scaleLabel) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.mirrorImageBtn = QtGui.QPushButton(Form) self.mirrorImageBtn.setToolTip(_fromUtf8("")) self.mirrorImageBtn.setObjectName(_fromUtf8("mirrorImageBtn")) self.horizontalLayout.addWidget(self.mirrorImageBtn) self.reflectImageBtn = QtGui.QPushButton(Form) self.reflectImageBtn.setObjectName(_fromUtf8("reflectImageBtn")) self.horizontalLayout.addWidget(self.reflectImageBtn) self.verticalLayout.addLayout(self.horizontalLayout) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Form", None)) self.translateLabel.setText(_translate("Form", "Translate:", None)) self.rotateLabel.setText(_translate("Form", "Rotate:", None)) self.scaleLabel.setText(_translate("Form", "Scale:", None)) self.mirrorImageBtn.setText(_translate("Form", "Mirror", None)) self.reflectImageBtn.setText(_translate("Form", "Reflect", None))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/canvas/__init__.py
.py
71
3
# -*- coding: utf-8 -*- from .Canvas import * from .CanvasItem import *
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_plot/pyqtgraph/canvas/CanvasTemplate_pyqt.py
.py
5,347
105
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'CanvasTemplate.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(821, 578) self.gridLayout_2 = QtGui.QGridLayout(Form) self.gridLayout_2.setMargin(0) self.gridLayout_2.setSpacing(0) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.splitter = QtGui.QSplitter(Form) self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setObjectName(_fromUtf8("splitter")) self.view = GraphicsView(self.splitter) self.view.setObjectName(_fromUtf8("view")) self.vsplitter = QtGui.QSplitter(self.splitter) self.vsplitter.setOrientation(QtCore.Qt.Vertical) self.vsplitter.setObjectName(_fromUtf8("vsplitter")) self.canvasCtrlWidget = QtGui.QWidget(self.vsplitter) self.canvasCtrlWidget.setObjectName(_fromUtf8("canvasCtrlWidget")) self.gridLayout = QtGui.QGridLayout(self.canvasCtrlWidget) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.autoRangeBtn = QtGui.QPushButton(self.canvasCtrlWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.autoRangeBtn.sizePolicy().hasHeightForWidth()) self.autoRangeBtn.setSizePolicy(sizePolicy) self.autoRangeBtn.setObjectName(_fromUtf8("autoRangeBtn")) self.gridLayout.addWidget(self.autoRangeBtn, 0, 0, 1, 2) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setSpacing(0) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.redirectCheck = QtGui.QCheckBox(self.canvasCtrlWidget) self.redirectCheck.setObjectName(_fromUtf8("redirectCheck")) self.horizontalLayout.addWidget(self.redirectCheck) self.redirectCombo = CanvasCombo(self.canvasCtrlWidget) self.redirectCombo.setObjectName(_fromUtf8("redirectCombo")) self.horizontalLayout.addWidget(self.redirectCombo) self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 2) self.itemList = TreeWidget(self.canvasCtrlWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(100) sizePolicy.setHeightForWidth(self.itemList.sizePolicy().hasHeightForWidth()) self.itemList.setSizePolicy(sizePolicy) self.itemList.setHeaderHidden(True) self.itemList.setObjectName(_fromUtf8("itemList")) self.itemList.headerItem().setText(0, _fromUtf8("1")) self.gridLayout.addWidget(self.itemList, 2, 0, 1, 2) self.resetTransformsBtn = QtGui.QPushButton(self.canvasCtrlWidget) self.resetTransformsBtn.setObjectName(_fromUtf8("resetTransformsBtn")) self.gridLayout.addWidget(self.resetTransformsBtn, 3, 0, 1, 2) self.mirrorSelectionBtn = QtGui.QPushButton(self.canvasCtrlWidget) self.mirrorSelectionBtn.setObjectName(_fromUtf8("mirrorSelectionBtn")) self.gridLayout.addWidget(self.mirrorSelectionBtn, 4, 0, 1, 1) self.reflectSelectionBtn = QtGui.QPushButton(self.canvasCtrlWidget) self.reflectSelectionBtn.setObjectName(_fromUtf8("reflectSelectionBtn")) self.gridLayout.addWidget(self.reflectSelectionBtn, 4, 1, 1, 1) self.canvasItemCtrl = QtGui.QWidget(self.vsplitter) self.canvasItemCtrl.setObjectName(_fromUtf8("canvasItemCtrl")) self.ctrlLayout = QtGui.QGridLayout(self.canvasItemCtrl) self.ctrlLayout.setMargin(0) self.ctrlLayout.setSpacing(0) self.ctrlLayout.setObjectName(_fromUtf8("ctrlLayout")) self.gridLayout_2.addWidget(self.splitter, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Form", None)) self.autoRangeBtn.setText(_translate("Form", "Auto Range", None)) self.redirectCheck.setToolTip(_translate("Form", "Check to display all local items in a remote canvas.", None)) self.redirectCheck.setText(_translate("Form", "Redirect", None)) self.resetTransformsBtn.setText(_translate("Form", "Reset Transforms", None)) self.mirrorSelectionBtn.setText(_translate("Form", "Mirror Selection", None)) self.reflectSelectionBtn.setText(_translate("Form", "MirrorXY", None)) from ..widgets.GraphicsView import GraphicsView from ..widgets.TreeWidget import TreeWidget from .CanvasManager import CanvasCombo
Python