text
stringlengths
18
773k
def set_mode(how): """ Sets the behavior of the API :param how: if 'remote' all the execution is performed on the remote server; if 'local' all it is executed locally. Default = 'local' :return: None """ global __mode if how == "local": __mode = how elif how == "remote": ...
def set_progress(how): """ Enables or disables the progress bars for the loading, writing and downloading of datasets :param how: True if you want the progress bar, False otherwise :return: None Example:: import gmql as gl gl.set_progress(True) # abilitates progress bars ...
def set_meta_profiling(how): """ Enables or disables the profiling of metadata at the loading of a GMQLDataset :param how: True if you want to analyze the metadata when a GMQLDataset is created by a load_from_*. False otherwise. (Default=True) :return: None """ global __metadata_pro...
def parse_regions(self, path): """ Given a file path, it loads it into memory as a Pandas dataframe :param path: file path :return: a Pandas Dataframe """ if self.schema_format.lower() == GTF.lower(): res = self._parse_gtf_regions(path) else: res ...
def get_attributes(self): """ Returns the unordered list of attributes :return: list of strings """ attr = ['chr', 'start', 'stop'] if self.strandPos is not None: attr.append('strand') if self.otherPos: for i, o in enumerate(self.otherPos): ...
def get_ordered_attributes(self): """ Returns the ordered list of attributes :return: list of strings """ attrs = self.get_attributes() attr_arr = np.array(attrs) poss = [self.chrPos, self.startPos, self.stopPos] if self.strandPos is not None: poss.ap...
def get_types(self): """ Returns the unordered list of data types :return: list of data types """ types = [str, int, int] if self.strandPos is not None: types.append(str) if self.otherPos: for o in self.otherPos: types.append(o[2])...
def get_name_type_dict(self): """ Returns a dictionary of the type {'column_name': data_type, ...} :return: dict """ attrs = self.get_attributes() types = self.get_types() d = dict() for i,a in enumerate(attrs): d[a] = types[i] return...
def get_ordered_types(self): """ Returns the ordered list of data types :return: list of data types """ types = self.get_types() types_arr = np.array(types) poss = [self.chrPos, self.startPos, self.stopPos] if self.strandPos is not None: poss.append(s...
def xmeans(cls, initial_centers=None, kmax=20, tolerance=0.025, criterion=splitting_type.BAYESIAN_INFORMATION_CRITERION, ccore=False): """ Constructor of the x-means clustering.rst algorithm :param initial_centers: Initial coordinates of centers of clusters that are represented by list: [center...
def clarans(cls, number_clusters, num_local, max_neighbour): """ Constructor of the CLARANS clustering.rst algorithm :param number_clusters: the number of clusters to be allocated :param num_local: the number of local minima obtained (amount of iterations for solving the problem). ...
def rock(cls, data, eps, number_clusters, threshold=0.5, ccore=False): """ Constructor of the ROCK cluster analysis algorithm :param eps: Connectivity radius (similarity threshold), points are neighbors if distance between them is less than connectivity radius :param number_clusters: De...
def optics(cls, data, eps, minpts, ccore=False): """ Constructor of OPTICS clustering.rst algorithm :param data: Input data that is presented as a list of points (objects), where each point is represented by list or tuple :param eps: Connectivity radius between points, points may be con...
def is_pyclustering_instance(model): """ Checks if the clustering.rst algorithm belongs to pyclustering :param model: the clustering.rst algorithm model :return: the truth value (Boolean) """ return any(isinstance(model, i) for i in [xmeans, clarans, rock, optics])
def fit(self, data=None): """ Performs clustering.rst :param data: Data to be fit :return: the clustering.rst object """ if self.is_pyclustering_instance(self.model): if isinstance(self.model, xmeans): data = self.input_preprocess(data) ...
def _labels_from_pyclusters(self): """ Computes and returns the list of labels indicating the data points and the corresponding cluster ids. :return: The list of labels """ clusters = self.model.get_clusters() labels = [] for i in range(0, len(clusters)): ...
def retrieve_cluster(self, df, cluster_no): """ Extracts the cluster at the given index from the input dataframe :param df: the dataframe that contains the clusters :param cluster_no: the cluster number :return: returns the extracted cluster """ if self.is_pyclus...
def get_labels(obj): """ Retrieve the labels of a clustering.rst object :param obj: the clustering.rst object :return: the resulting labels """ if Clustering.is_pyclustering_instance(obj.model): return obj._labels_from_pyclusters else: ret...
def silhouette_n_clusters(data, k_min, k_max, distance='euclidean'): """ Computes and plot the silhouette score vs number of clusters graph to help selecting the number of clusters visually :param data: The data object :param k_min: lowerbound of the cluster range :param k_max: ...
def elbow_method(data, k_min, k_max, distance='euclidean'): """ Calculates and plots the plot of variance explained - number of clusters Implementation reference: https://github.com/sarguido/k-means-clustering.rst :param data: The dataset :param k_min: lowerbound of the cluster ...
def adjusted_mutual_info(self, reference_clusters): """ Calculates the adjusted mutual information score w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: returns the value of the adjusted mutual information...
def adjusted_rand_score(self, reference_clusters): """ Calculates the adjusted rand score w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: returns the value of the adjusted rand score """ re...
def completeness_score(self, reference_clusters): """ Calculates the completeness score w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: the resulting completeness score """ return completen...
def fowlkes_mallows(self, reference_clusters): """ Calculates the Fowlkes-Mallows index (FMI) w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: The resulting Fowlkes-Mallows score. """ return...
def homogeneity_score(self, reference_clusters): """ Calculates the homogeneity score w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: The resulting homogeneity score. """ return homogeneity...
def mutual_info_score(self, reference_clusters): """ Calculates the MI (mutual information) w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: The resulting MI score. """ return mutual_info_sc...
def normalized_mutual_info_score(self, reference_clusters): """ Calculates the normalized mutual information w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: The resulting normalized mutual information scor...
def silhouette_score(self, data, metric='euclidean', sample_size=None, random_state=None, **kwds): """ Computes the mean Silhouette Coefficient of all samples (implicit evaluation) :param data: The data that the clusters are generated from :param metric: the pairwise distance metric ...
def materialize(datasets): """ Multiple materializations. Enables the user to specify a set of GMQLDataset to be materialized. The engine will perform all the materializations at the same time, if an output path is provided, while will perform each operation separately if the output_path is not specified. ...
def retrieve_bicluster(self, df, row_no, column_no): """ Extracts the bicluster at the given row bicluster number and the column bicluster number from the input dataframe. :param df: the input dataframe whose values were biclustered :param row_no: the number of the row bicluster ...
def bicluster_similarity(self, reference_model): """ Calculates the similarity between the current model of biclusters and the reference model of biclusters :param reference_model: The reference model of biclusters :return: Returns the consensus score(Hochreiter et. al., 2010), i.e. the...
def load(self, path, genes_uuid, regs=['chr', 'left', 'right', 'strand'], meta=[], values=[], full_load=False): """ Loads the multi referenced mapped data from the file system :param path: The path to the files :param genes_uuid: The unique identifier metadata column name to sep...
def merge(self, samples_uuid): """ The method to merge the datamodels belonging to different references :param samples_uuid: The unique identifier metadata column name to identify the identical samples having different references :return: Returns the merged dataframe """ ...
def compact_view(self, merged_data, selected_meta, reference_no): """ Creates and returns the compact view where the index of the dataframe is a multi index of the selected metadata. Side effect: Alters the merged_data parameter :param merged_data: The merged data that is to be used to ...
def prune_by_missing_percent(df, percentage=0.4): """ The method to remove the attributes (genes) with more than a percentage of missing values :param df: the dataframe containing the attributes to be pruned :param percentage: the percentage threshold (0.4 by default) :return: t...
def impute_using_statistics(df, method='min'): """ Imputes the missing values by the selected statistical property of each column :param df: The input dataframe that contains missing values :param method: The imputation method (min by default) "zero": fill missing entries wi...
def impute_knn(df, k=3): """ Nearest neighbour imputations which weights samples using the mean squared difference on features for which two rows both have observed data. :param df: The input dataframe that contains missing values :param k: The number of neighbours :return: the ...
def impute_svd(df, rank=10, convergence_threshold=0.00001, max_iters=200): """ Imputes the missing values by using SVD decomposition Based on the following publication: 'Missing value estimation methods for DNA microarrays' by Troyanskaya et. al. :param df:The input dataframe that conta...
def feature_selection(df, labels, n_features, method='chi2'): """ Reduces the number of features in the imput dataframe. Ex: labels = gs.meta['biospecimen_sample__sample_type_id'].apply(int).apply(lambda x: 0 if x < 10 else 1) chi2_fs(gs.data, labels, 50) :param df: The inpu...
def set_spark_conf(self, key=None, value=None, d=None): """ Sets a spark property as a ('key', 'value') pair of using a dictionary {'key': 'value', ...} :param key: string :param value: string :param d: dictionary :return: None """ if isinstance(d, dict):...
def set_system_conf(self, key=None, value=None, d=None): """ Sets a java system property as a ('key', 'value') pair of using a dictionary {'key': 'value', ...} :param key: string :param value: string :param d: dictionary :return: None """ if isinstance(d,...
def isin(self, values): """ Selects the samples having the metadata attribute between the values provided as input :param values: a list of elements :return a new complex condition """ if not isinstance(values, list): raise TypeError("Input should be a string...
def get_flatpages_i18n(parser, token): """ Retrieves all flatpage objects available for the current site and visible to the specific user (or visible to all users if no user is specified). Populates the template context with them in a variable whose name is defined by the ``as`` clause. An opti...
def daemonize(self): """Double fork and set the pid.""" self._double_fork() # Write pidfile. self.pid = os.getpid() LOG.info( "Succesfully daemonized process {0}.".format(self.pid) )
def _double_fork(self): """Do the UNIX double-fork magic. See Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ try: pid = os.fork() if pid > 0: ...
def from_memory(cls, data, meta): """ Overloaded constructor to create the GenometricSpace object from memory data and meta variables. The indexes of the data and meta dataframes should be the same. :param data: The data model :param meta: The metadata :return: A Genome...
def load(self, _path, regs=['chr', 'left', 'right', 'strand'], meta=[], values=[], full_load=False, file_extension="gdm"): """Parses and loads the data into instance attributes. The indexes of the data and meta dataframes should be the same. :param path: The path to the dataset on the filesyste...
def set_meta(self, selected_meta): """Sets one axis of the 2D multi-indexed dataframe index to the selected meta data. :param selected_meta: The list of the metadata users want to index with. """ meta_names = list(selected_meta) meta_names.append('sample') m...
def to_matrix(self, values, selected_regions, default_value=0): """Creates a 2D multi-indexed matrix representation of the data. This representation allows the data to be sent to the machine learning algorithms. Args: :param values: The value or values that are going to fill the...
def get_values(self, set, selected_meta): """ Retrieves the selected metadata values of the given set :param set: cluster that contains the data :param selected_meta: the values of the selected_meta :return: the values of the selected meta of the cluster """ warn...
def group_statistics(self, group, selected_meta, stat_code='mean'): """ Provides statistics of a group based on the meta data selected. :param group:The result of a classification or clustering.rst or biclustering algorithm :param selected_meta: The metadata that we are interested in ...
def to_bag_of_genomes(self, clustering_object): """ Creates a bag of genomes representation for data mining purposes Each document (genome) in the representation is a set of metadata key and value pairs belonging to the same cluster. The bag of genomes are saved under ./bag_of_genomes/ d...
def to_term_document_matrix(path_to_bag_of_genomes, max_df=0.99, min_df=1, use_idf=False): """ Creates a term-document matrix which is a mathematical matrix that describes the frequency of terms that occur in a collection of documents (in our case a collection of genomes). :param path_t...
def tf(cluster): """ Computes the term frequency and stores it as a dictionary :param cluster: the cluster that contains the metadata :return: tf dictionary """ counts = dict() words = cluster.split(' ') for word in words: counts[word] = count...
def best_descriptive_meta_dict(path_to_bag_of_genomes, cluster_no): """ Computes the importance of each metadata by using tf * coverage (the percentage of the term occuring in a cluster) :param path_to_bag_of_genomes: The directory path :param cluster_no: cluster number :param p...
def visualize_cloud_of_words(dictionary, image_path=None): """ Renders the cloud of words representation for a given dictionary of frequencies :param dictionary: the dictionary object that contains key-frequency pairs :param image_path: the path to the image mask, None if no masking is ...
def cloud_of_words(path_to_bog, cluster_no, image_path=None): """ Draws the cloud of words representation :param path_to_bog: path to bag of words :param cluster_no: the number of document to be visualized :param image_path: path to the image file for the masking, None if no mas...
def _get_files(extension, path): """ Returns a sorted list of all of the files having the same extension under the same directory :param extension: the extension of the data files such as 'gdm' :param path: path to the folder containing the files :return: sorted list of files ...
def _get_schema_file(extension, path): """ Returns the schema file :param extension: extension of the schema file usually .schema :param path: path to the folder containing the schema file :return: the path to the schema file """ for file in os.listdir(path): ...
def parse_schema(schema_file): """ parses the schema file and returns the columns that are later going to represent the columns of the genometric space dataframe :param schema_file: the path to the schema file :return: the columns of the schema file """ e = xml.etree.Elem...
def parse_single_meta(self, fname, selected_meta_data): """ Parses a single meta data file :param fname: name of the file :param selected_meta_data: If not none then only the specified columns of metadata are parsed :return: the resulting pandas series """ # reads...
def parse_meta(self, selected_meta_data): """ Parses all of the metadata files :param selected_meta_data: if specified then only the columns that are contained here are going to be parsed :return: """ # reads all meta data files files = self._get_files("meta", sel...
def parse_single_data(self, path, cols, selected_region_data, selected_values, full_load): """ Parses a single region data file :param path: path to the file :param cols: the column names coming from the schema file :param selected_region_data: the selected of the region data to ...
def parse_data(self, selected_region_data, selected_values, full_load=False, extension="gdm"): """ Parses all of the region data :param selected_region_data: the columns of region data that are needed :param selected_values: the selected values to be put in the matrix cells :para...
def from_pandas(regs, meta=None, chr_name=None, start_name=None, stop_name=None, strand_name=None, sample_name=None): """ Creates a GDataframe from a pandas dataframe of region and a pandas dataframe of metadata :param regs: a pandas Dataframe of regions that is coherent with the GMQL data mode...
def check_regs(region_df, chr_name=None, start_name=None, stop_name=None, strand_name=None, sample_name=None): """ Modifies a region dataframe to be coherent with the GMQL data model :param region_df: a pandas Dataframe of regions that is coherent with the GMQL data model :param chr_name: (o...
def to_dataset_files(self, local_path=None, remote_path=None): """ Save the GDataframe to a local or remote location :param local_path: a local path to the folder in which the data must be saved :param remote_path: a remote dataset name that wants to be used for these data :return: None...
def to_GMQLDataset(self, local_path=None, remote_path=None): """ Converts the GDataframe in a GMQLDataset for later local or remote computation :return: a GMQLDataset """ local = None remote = None if (local_path is None) and (remote_path is None): # get a te...
def project_meta(self, attributes): """ Projects the specified metadata attributes to new region fields :param attributes: a list of metadata attributes :return: a new GDataframe with additional region fields """ if not isinstance(attributes, list): raise TypeError('...
def to_matrix(self, index_regs=None, index_meta=None, columns_regs=None, columns_meta=None, values_regs=None, values_meta=None, **kwargs): """ Transforms the GDataframe to a pivot matrix having as index and columns the ones specified. This function is a wrapper around...
def charts_get(self, **kwargs): """ Charts Returns a list of Charts, ordered by creation date (newest first). A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysi...
def charts_slug_get(self, slug, **kwargs): """ Chart A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster ...
def charts_slug_pollster_chart_poll_questions_tsv_get(self, slug, **kwargs): """ One row per poll plotted on a Chart Derived data presented on a Pollster Chart. Rules for which polls and responses are plotted on a chart can shift over time. Here are some examples of behaviors Pollster has used ...
def charts_slug_pollster_trendlines_tsv_get(self, slug, **kwargs): """ Estimates of what the polls suggest about trends Derived data presented on a Pollster Chart. The trendlines on a Pollster chart don't add up to 100: we calculate each label's trendline separately. Use the `charts/{slug}` re...
def polls_get(self, **kwargs): """ Polls A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include every question...
def polls_slug_get(self, slug, **kwargs): """ Poll A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include ever...
def questions_get(self, **kwargs): """ Questions Returns a list of Questions. A Question is chosen by Pollster editors. One example is \"Obama job approval\". Different survey houses may publish varying phrasings (\"Do you approve or disapprove\" vs \"What do you think of the job\") and prompt...
def questions_slug_get(self, slug, **kwargs): """ Question A Question is chosen by Pollster editors. One example is \"Obama job approval\". Different survey houses may publish varying phrasings (\"Do you approve or disapprove\" vs \"What do you think of the job\") and prompt readers with varyin...
def questions_slug_poll_responses_clean_tsv_get(self, slug, **kwargs): """ One row of response values per PollQuestion+Subpopulation concerning the given Question We include one TSV column per response label. See `questions/{slug}` for the Question's list of response labels, which are chosen by ...
def questions_slug_poll_responses_raw_tsv_get(self, slug, **kwargs): """ One row per PollQuestion+Subpopulation+Response concerning the given Question (Large) Raw data from which we derived `poll-responses-clean.tsv`. Each row represents a single PollQuestion+Subpopulation+Response. See the Pol...
def tags_get(self, **kwargs): """ Tags Returns the list of Tags. A Tag can apply to any number of Charts and Questions; Charts and Questions, in turn, can have any number of Tags. Tags all look `like-this`: lowercase letters, numbers and hyphens. This method makes a synchronous HTTP ...
def sanitize_for_serialization(self, obj): """ Builds a JSON POST object. If obj is None, return None. If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sani...
def select_header_content_type(self, content_types): """ Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. :return: Content-Type (e.g. application/json). """ if not content_types: return 'applicat...
def __deserialize_model(self, data, klass): """ Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ instance = klass() if not instance.swagger_types: return data for at...
def flatpage(request, url): """ Public interface to the flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or `flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages`...
def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.au...
def pidfile(self): """Get the absolute path of the pidfile.""" return os.path.abspath( os.path.expandvars( os.path.expanduser( self._pidfile, ), ), )
def SQRT(argument): """ Computes the square matrix of the argument :param argument: a dataset region field (dataset.field) or metadata (dataset['field']) """ if isinstance(argument, MetaField): return argument._unary_expression("SQRT") elif isinstance(argument, RegField): return arg...
def login(): """ Enables the user to login to the remote GMQL service. If both username and password are None, the user will be connected as guest. """ from .RemoteConnection.RemoteManager import RemoteManager global __remote_manager, __session_manager logger = logging.getLogger() remote_ad...
def main(idle): """Any normal python logic which runs a loop. Can take arguments.""" while True: LOG.debug("Sleeping for {0} seconds.".format(idle)) time.sleep(idle)
def get_metadata(self): """ Returns the metadata related to the current GMQLDataset. This function can be used only when a local dataset is loaded using the :meth:`~gmql.dataset.loaders.Loader.load_from_path` and no other operation has been called on the GMQLDataset. The metadata are re...
def MetaField(self, name, t=None): """ Creates an instance of a metadata field of the dataset. It can be used in building expressions or conditions for projection or selection. Notice that this function is equivalent to call:: dataset["name"] If the Meta...
def select(self, meta_predicate=None, region_predicate=None, semiJoinDataset=None, semiJoinMeta=None): """ *Wrapper of* ``SELECT`` Selection operation. Enables to filter datasets on the basis of region features or metadata attributes. In addition it is possibile to perform a sel...
def meta_select(self, predicate=None, semiJoinDataset=None, semiJoinMeta=None): """ *Wrapper of* ``SELECT`` Wrapper of the :meth:`~.select` function filtering samples only based on metadata. :param predicate: logical predicate on the values of the rows :param semiJoinDataset: a...
def reg_select(self, predicate=None, semiJoinDataset=None, semiJoinMeta=None): """ *Wrapper of* ``SELECT`` Wrapper of the :meth:`~.select` function filtering regions only based on region attributes. :param predicate: logical predicate on the values of the regions :param semiJoi...
def project(self, projected_meta=None, new_attr_dict=None, all_but_meta=None, projected_regs=None, new_field_dict=None, all_but_regs=None): """ *Wrapper of* ``PROJECT`` The PROJECT operator creates, from an existing dataset, a new dataset with all the samples (with their...
def meta_project(self, attr_list=None, all_but=None, new_attr_dict=None): """ *Wrapper of* ``PROJECT`` Project the metadata based on a list of attribute names :param attr_list: list of the metadata fields to select :param all_but: list of metadata that must be excluded ...
def reg_project(self, field_list=None, all_but=None, new_field_dict=None): """ *Wrapper of* ``PROJECT`` Project the region data based on a list of field names :param field_list: list of the fields to select :param all_but: keep only the region fields different from the ones ...
def extend(self, new_attr_dict): """ *Wrapper of* ``EXTEND`` For each sample in an input dataset, the EXTEND operator builds new metadata attributes, assigns their values as the result of arithmetic and/or aggregate functions calculated on sample region attributes, and adds the...
def cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None, cover_type="normal"): """ *Wrapper of* ``COVER`` COVER is a GMQL operator that takes as input a dataset (of usually, but not necessarily, multiple samples) and returns another dataset (with a single sample, if ...