code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return any(isinstance(model, i) for i in [xmeans, clarans, rock, optics])
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)
32.28265
38.403763
0.840612
if self.is_pyclustering_instance(self.model): if isinstance(self.model, xmeans): data = self.input_preprocess(data) self.model._xmeans__pointer_data = data elif isinstance(self.model, clarans): data = self.input_preprocess(data) ...
def fit(self, data=None)
Performs clustering.rst :param data: Data to be fit :return: the clustering.rst object
4.442993
4.504725
0.986296
clusters = self.model.get_clusters() labels = [] for i in range(0, len(clusters)): for j in clusters[i]: labels.insert(int(j), i) return labels
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
3.228828
3.849221
0.838826
if self.is_pyclustering_instance(self.model): clusters = self.model.get_clusters() mask = [] for i in range(0, df.shape[0]): mask.append(i in clusters[cluster_no]) else: mask = self.model.labels_ == cluster_no # a boolean mask ...
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
3.99722
4.429604
0.902388
if Clustering.is_pyclustering_instance(obj.model): return obj._labels_from_pyclusters else: return obj.model.labels_
def get_labels(obj)
Retrieve the labels of a clustering.rst object :param obj: the clustering.rst object :return: the resulting labels
12.64328
13.752204
0.919364
k_range = range(k_min, k_max) k_means_var = [Clustering.kmeans(k).fit(data) for k in k_range] silhouette_scores = [obj.silhouette_score(data=data, metric=distance) for obj in k_means_var] fig = plt.figure() ax = fig.add_subplot(111) ax.plot(k_range, silhouette...
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: upperbound of the cluster range :param distance: the distance metric, 'euclidean'...
2.390892
2.476898
0.965277
# Determine your k range k_range = range(k_min, k_max) # Fit the kmeans model for each n_clusters = k k_means_var = [Clustering.kmeans(k).fit(data) for k in k_range] # Pull out the cluster centers for each model centroids = [X.model.cluster_centers_ for X in k_...
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 range :param k_max: upperbound of the cluster range :param dista...
3.01482
3.113633
0.968264
return adjusted_mutual_info_score(self.get_labels(self), self.get_labels(reference_clusters))
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 score
3.832889
4.647389
0.82474
return adjusted_rand_score(self.get_labels(self), self.get_labels(reference_clusters))
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
4.122894
5.556422
0.742005
return completeness_score(self.get_labels(self), self.get_labels(reference_clusters))
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
5.754635
7.135458
0.806484
return fowlkes_mallows_score(self.get_labels(self), self.get_labels(reference_clusters))
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.
3.709936
5.109219
0.726126
return homogeneity_score(self.get_labels(self), self.get_labels(reference_clusters))
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.
4.68666
6.000218
0.781082
return mutual_info_score(self.get_labels(self), self.get_labels(reference_clusters))
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.
4.154232
5.631239
0.737712
return normalized_mutual_info_score(self.get_labels(self), self.get_labels(reference_clusters))
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 score.
3.824697
4.923616
0.776807
return silhouette_score(data, self.get_labels(self), metric, sample_size, random_state, **kwds)
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 :param sample_size: the size of the sample to use computing the Silhouette Coefficient :param random_state...
3.023455
4.461812
0.677629
from .. import GMQLDataset if isinstance(datasets, dict): result = dict() for output_path in datasets.keys(): dataset = datasets[output_path] if not isinstance(dataset, GMQLDataset.GMQLDataset): raise TypeError("The values of the dictionary must be GM...
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. :param datasets: it can be a li...
2.294201
1.946841
1.178422
res = df[self.model.biclusters_[0][row_no]] bicluster = res[res.columns[self.model.biclusters_[1][column_no]]] return bicluster
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 :param column_no: the number of the column bicluster :return: th...
3.999896
4.384074
0.91237
similarity_score = consensus_score(self.model.biclusters_, reference_model.biclusters_) return similarity_score
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 similarity of two sets of biclusters.
6.513543
6.450827
1.009722
if not full_load: warnings.warn("\n\n You are using the optimized loading technique. " "All-zero rows are not going to be loaded into memory. " "To load all the data please set the full_load parameter equal to True.") p = Parser(p...
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 separate the data by the number of references :param regs: The region data that are to be analyzed :param meta: The met...
5.302601
4.783527
1.108513
all_meta_data = pd.DataFrame() for dm in self.data_model: all_meta_data = pd.concat([all_meta_data, dm.meta], axis=0) group = all_meta_data.groupby([samples_uuid])['sample'] sample_sets = group.apply(list).values merged_df = pd.DataFrame() multi_in...
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
3.193433
3.049753
1.047112
meta_names = list(selected_meta) meta_index = [] for x in meta_names: meta_index.append(self.all_meta_data.ix[merged_data.index.get_level_values(reference_no)][x].values) meta_index = np.asarray(meta_index) multi_meta_index = pd.MultiIndex.from_arrays(meta_i...
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 create the compact view :param selected_meta: The selected metadata to create ...
2.79171
2.499883
1.116737
mask = (df.isnull().sum() / df.shape[0]).map(lambda x: True if x < percentage else False) pruned_df = df[df.columns[mask.values]] return pruned_df
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: the pruned dataframe
3.150549
3.267929
0.964081
sf = SimpleFill(method) imputed_matrix = sf.complete(df.values) imputed_df = pd.DataFrame(imputed_matrix, df.index, df.columns) return imputed_df
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 with zeros "mean": fill with column means "me...
3.845175
4.0985
0.938191
imputed_matrix = KNN(k=k).complete(df.values) imputed_df = pd.DataFrame(imputed_matrix, df.index, df.columns) return imputed_df
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 imputed dataframe
3.113822
4.399631
0.707746
imputed_matrix = IterativeSVD(rank,convergence_threshold, max_iters).complete(df.values) imputed_df = pd.DataFrame(imputed_matrix, df.index, df.columns) return imputed_df
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 contains missing values :param rank: Rank value of the truncated SVD :param converge...
3.14452
4.386265
0.716901
fs_obj = None if method == 'chi2': fs_obj = chi2 elif method == 'ANOVA': fs_obj = f_classif elif method == 'mi': fs_obj = mutual_info_classif else: raise ValueError('The method is not recognized') fs = SelectKB...
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 input dataframe :param labels: Labels for each row in the df. Type: Pandas.Ser...
2.370144
2.349236
1.0089
if isinstance(d, dict): self._properties.update(d) elif isinstance(key, str) and isinstance(value, str): self._properties[key] = value else: raise TypeError("key, value must be strings")
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
2.53248
2.670483
0.948323
if isinstance(d, dict): self._system.update(d) elif isinstance(key, str) and isinstance(value, str): self._system[key] = value else: raise TypeError("key, value must be strings")
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
2.54745
2.871264
0.887222
if not isinstance(values, list): raise TypeError("Input should be a string. {} was provided".format(type(values))) if not (self.name.startswith("(") and self.name.endswith(")")): first = True new_condition = None for v in values: i...
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
3.394771
3.110946
1.091234
bits = token.split_contents() syntax_message = ("%(tag_name)s expects a syntax of %(tag_name)s " "['url_starts_with'] [for user] as context_name" % dict(tag_name=bits[0])) # Must have at 3-6 bits in the tag if 3 <= len(bits) <= 8: containing = No...
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 optional ``for`` clause can be used to control the user...
3.556372
2.800076
1.270098
self._double_fork() # Write pidfile. self.pid = os.getpid() LOG.info( "Succesfully daemonized process {0}.".format(self.pid) )
def daemonize(self)
Double fork and set the pid.
7.396419
5.756822
1.284809
try: pid = os.fork() if pid > 0: # Exit first parent. sys.exit(0) return None except OSError as err: LOG.exception( "Fork #1 failed: {0} ({1})".format( err.errno, ...
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
1.715097
1.751566
0.979179
obj = cls() obj.data = data obj.meta = meta return obj
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 GenometricSpace object
4.145197
5.278349
0.785321
if not full_load: warnings.warn("\n\nYou are using the optimized loading technique. " "All-zero rows are not going to be loaded into memory. " "To load all the data please set the full_load parameter equal to True.") p = Parser(_pa...
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 filesystem :param regs: the regions that are to be analyzed :param meta: the meta-data that are to be analyzed :param v...
5.353869
4.819004
1.110991
meta_names = list(selected_meta) meta_names.append('sample') meta_index = [] # To set the index for existing samples in the region dataframe. # The index size of the region dataframe does not necessarily be equal to that of metadata df. warnings.warn("\n\nThis me...
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.
5.179847
5.180206
0.999931
if isinstance(values, list): for v in values: try: self.data[v] = self.data[v].map(float) except: print(self.data[v]) else: self.data[values] = self.data[values].map(float) print("started piv...
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 matrix. :param selected_regions: The index to one axis of the ...
2.86162
3.190268
0.896984
warnings.warn("\n\nThis method assumes that the last level of the index is the sample_id.\n" "In case of single index, the index itself should be the sample_id") sample_ids = set.index.get_level_values(-1) corresponding_meta = self.meta.loc[sample_ids] valu...
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
5.179864
5.333492
0.971196
values = self.get_values(group, selected_meta) if stat_code == 'mean': res = statistics.mean(values) elif stat_code == 'variance': res = statistics.variance(values) elif stat_code == 'std': res = statistics.stdev(values) return res
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 :param stat_code: 'mean' for mean or 'variance' for variance or 'std' for standard...
1.991314
2.07296
0.960613
meta_files = Parser._get_files('meta', self._path) meta_dict = {} for f in meta_files: meta_dict[Parser.get_sample_id(f)] = f clusters = [] if isinstance(clustering_object, Clustering): if Clustering.is_pyclustering_instance(clustering_object.mo...
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/ directory :param clustering_object: The clustering.rst objec...
3.063012
2.91659
1.050203
token_dict = {} def BoG_tokenizer(_text): return _text.split('\n') print("creating the term-document matrix...") for file in tqdm(Parser._get_files('.bag_of_genome', path_to_bag_of_genomes)): f = open(file, 'r') text = f.read() t...
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_to_bag_of_genomes: Path to the documents (genomes) :param max_df: To prune the terms that are existing i...
3.585011
3.567769
1.004833
counts = dict() words = cluster.split(' ') for word in words: counts[word] = counts.get(word, 0) + 1 return counts
def tf(cluster)
Computes the term frequency and stores it as a dictionary :param cluster: the cluster that contains the metadata :return: tf dictionary
3.581629
3.353508
1.068025
from nltk.corpus import stopwords clusters = [] for file in Parser._get_files('.bag_of_genome', path_to_bag_of_genomes): f = open(file, 'r') text = f.read() # process the text word_list = [] for line in text.split('\n'): ...
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 preprocess: to remove the redundant information from the metadata :return: return...
3.779386
3.703118
1.020596
from PIL import Image if image_path is not None: mask = np.array(Image.open(image_path)) wc = WordCloud(mask=mask, background_color='white', width=1600, height=1200, prefer_horizontal=0.8) wc = wc.generate_from_frequencies(dictionary) else: ...
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 needed
1.859301
1.868701
0.99497
dictionary = GenometricSpace.best_descriptive_meta_dict(path_to_bog, cluster_no) GenometricSpace.visualize_cloud_of_words(dictionary, image_path)
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 masking is needed
9.015745
9.972979
0.904017
# retrieves the files sharing the same extension files = [] for file in os.listdir(path): if file.endswith(extension): files.append(os.path.join(path, file)) return sorted(files)
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
3.293624
3.171588
1.038478
for file in os.listdir(path): if file.endswith(extension): return os.path.join(path, file)
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
2.589705
2.677095
0.967357
e = xml.etree.ElementTree.parse(schema_file) root = e.getroot() cols = [] for elem in root.findall(".//{http://genomic.elet.polimi.it/entities}field"): # XPATH cols.append(elem.text) return cols
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
5.21391
4.774407
1.092054
# reads a meta data file into a dataframe columns = [] data = [] with open(fname) as f: for line in f: splitted = line.split('\t') columns.append(splitted[0]) data.append(splitted[1].split('\n')[0]) # to remove the \n ...
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
3.175648
3.149623
1.008263
# reads all meta data files files = self._get_files("meta", self.path) df = pd.DataFrame() print("Parsing the metadata files...") for f in tqdm(files): data = self.parse_single_meta(f, selected_meta_data) if data is not None: df = ...
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:
4.20188
4.021258
1.044917
# reads a sample file df = pd.read_table(path, engine='c', sep="\t", lineterminator="\n", header=None) df.columns = cols # column names from schema df = df[selected_region_data] if not full_load: if type(selected_values) is list: df_2 = pd.D...
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 be parsed In most cases the analyst only needs a small subset of the region data :param selecte...
2.725887
2.830742
0.962959
regions = list(selected_region_data) if type(selected_values) is list: regions.extend(selected_values) else: regions.append(selected_values) files = self._get_files(extension, self.path) df = pd.DataFrame(dtype=float) cols = self.parse_s...
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 :param full_load: Specifies the method of parsing the data. If False then parser omits the parsing of zero(0) ...
3.409491
3.471308
0.982192
regs = check_regs(regs, chr_name, start_name, stop_name, strand_name, sample_name) regs = to_gmql_regions(regs) if meta is not None: if not check_meta(meta, regs): raise ValueError("Error. Meta dataframe is not GMQL standard") else: meta = empty_meta(regs) return GDa...
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 model :param meta: (optional) a pandas Dataframe of metadata that is coherent with the regions :param chr_name: (optional) which column of...
4.324279
4.057749
1.065684
if sample_name is None: region_df.index = np.repeat(default_id_sample, len(region_df)) else: region_df = search_column(region_df, id_sample_aliases, id_sample_types, 'id_sample', sample_name) region_df = region_df.set_index("id_sample", drop=True) ...
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: (optional) which column of :attr:`~.region_df` is the chromosome :param start_name: (optional) which column of :attr:`~.region_df` i...
2.154581
2.214789
0.972816
return FrameToGMQL.to_dataset_files(self, path_local=local_path, path_remote=remote_path)
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
8.905411
11.235869
0.792588
local = None remote = None if (local_path is None) and (remote_path is None): # get a temporary path local = TempFileManager.get_new_dataset_tmp_folder() if local_path is not None: local = local_path if remote_path is not 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
3.553681
3.848273
0.923448
if not isinstance(attributes, list): raise TypeError('attributes must be a list') meta_to_project = self.meta[attributes].applymap(lambda l: ", ".join(l)) new_regs = self.regs.merge(meta_to_project, left_index=True, right_index=True) return GDataframe(regs=new_regs, ...
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
4.267834
3.533177
1.207931
index_regs = index_regs if index_regs is not None else [] index_meta = index_meta if index_meta is not None else [] columns_regs = columns_regs if columns_regs is not None else [] columns_meta = columns_meta if columns_meta is not None else [] values_regs = values_regs ...
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 the pivot_table function of Pandas. :param index_regs: list of region fields to use as index :param index_meta: list of metadata attributes to use as index :para...
1.921036
1.910975
1.005265
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.charts_get_with_http_info(**kwargs) else: (data) = self.charts_get_with_http_info(**kwargs) return data
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 analysis on Questions instead. Charts are derived data; Pol...
1.509785
1.682815
0.897178
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.charts_slug_get_with_http_info(slug, **kwargs) else: (data) = self.charts_slug_get_with_http_info(slug, **kwargs) return data
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 editors publish them and change them as editorial priorities ch...
1.399545
1.552245
0.901627
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.charts_slug_pollster_chart_poll_questions_tsv_get_with_http_info(slug, **kwargs) else: (data) = self.charts_slug_pollster_chart_poll_questions_tsv_get_with_http_info(slug, **kwargs) ...
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 in the past: * We've omitted \"Registered Voters\" from a chart when \"Likely Voters\" respond...
1.287992
1.407763
0.914921
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.charts_slug_pollster_trendlines_tsv_get_with_http_info(slug, **kwargs) else: (data) = self.charts_slug_pollster_trendlines_tsv_get_with_http_info(slug, **kwargs) return dat...
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}` response's `chart.pollster_estimates[0].algorithm` to find the algorithm Pollster used to...
1.313022
1.442819
0.910039
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.polls_get_with_http_info(**kwargs) else: (data) = self.polls_get_with_http_info(**kwargs) return data
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 when they enter Polls, and they don't necessarily ...
1.495248
1.624093
0.920667
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.polls_slug_get_with_http_info(slug, **kwargs) else: (data) = self.polls_slug_get_with_http_info(slug, **kwargs) return data
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 every question when they enter Polls, and they don't necessarily e...
1.397215
1.49508
0.934542
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.questions_get_with_http_info(**kwargs) else: (data) = self.questions_get_with_http_info(**kwargs) return data
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 readers with varying responses (one poll might have \"...
1.540143
1.691089
0.91074
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.questions_slug_get_with_http_info(slug, **kwargs) else: (data) = self.questions_slug_get_with_http_info(slug, **kwargs) return data
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 varying responses (one poll might have \"Approve\" and \"Disapprove\"; a...
1.441445
1.524096
0.945771
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.questions_slug_poll_responses_clean_tsv_get_with_http_info(slug, **kwargs) else: (data) = self.questions_slug_poll_responses_clean_tsv_get_with_http_info(slug, **kwargs) re...
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 Pollster editors. Each row represents a single PollQuestion+Subpopulation. The value for ea...
1.305741
1.440891
0.906204
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.questions_slug_poll_responses_raw_tsv_get_with_http_info(slug, **kwargs) else: (data) = self.questions_slug_poll_responses_raw_tsv_get_with_http_info(slug, **kwargs) return...
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 Poll API for a description of these terms. Group results by `(poll_slug, subpopulation, que...
1.323658
1.443367
0.917063
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.tags_get_with_http_info(**kwargs) else: (data) = self.tags_get_with_http_info(**kwargs) return data
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 request by default. To make an asynchronou...
1.50561
1.696137
0.88767
types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,) if isinstance(obj, type(None)): return None elif isinstance(obj, types): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) ...
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, sanitize each element in the list. If obj is dict, return t...
2.290809
2.298929
0.996468
if not content_types: return 'application/json' content_types = list(map(lambda x: x.lower(), content_types)) if 'application/json' in content_types or '*/*' in content_types: return 'application/json' else: return content_types[0]
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).
2.066853
2.15055
0.961081
instance = klass() if not instance.swagger_types: return data for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ and instance.attribute_map[attr] in data\ and isinstance(data, (list, dict)): ...
def __deserialize_model(self, data, klass)
Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object.
2.746165
2.985869
0.91972
if not url.startswith('/'): url = '/' + url language = request.LANGUAGE_CODE language_prefix = '/%s' % language language_db_field = language.replace('-', '_') if url.startswith(language_prefix): url = url[len(language_prefix):] kwargs = { '{0}__{1}'.format('url_%...
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` object
2.37532
2.406244
0.987148
# 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.auth.views import redirect_to_login return redirect_to_login(request.path) if f....
def render_flatpage(request, f)
Internal interface to the flat page view.
3.313113
3.350436
0.98886
return os.path.abspath( os.path.expandvars( os.path.expanduser( self._pidfile, ), ), )
def pidfile(self)
Get the absolute path of the pidfile.
3.720483
2.887188
1.288618
if isinstance(argument, MetaField): return argument._unary_expression("SQRT") elif isinstance(argument, RegField): return argument._unary_expression("SQRT") else: raise TypeError("You have to give as input a RegField (dataset.field)" "or a MetaField (data...
def SQRT(argument)
Computes the square matrix of the argument :param argument: a dataset region field (dataset.field) or metadata (dataset['field'])
6.341845
4.465618
1.420149
from .RemoteConnection.RemoteManager import RemoteManager global __remote_manager, __session_manager logger = logging.getLogger() remote_address = get_remote_address() res = __session_manager.get_session(remote_address) if res is None: # there is no session for this address, let's ...
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.
4.587703
4.504129
1.018555
while True: LOG.debug("Sleeping for {0} seconds.".format(idle)) time.sleep(idle)
def main(idle)
Any normal python logic which runs a loop. Can take arguments.
4.732095
4.861442
0.973393
if self.path_or_name is None: raise ValueError("You cannot explore the metadata of an intermediate query." "You can get metadata only after a load_from_local or load_from_remote") if self.location == 'local': return self.__get_metadata_local(...
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 returned in the form of a Pandas Dataf...
6.099466
6.066307
1.005466
return MetaField(name=name, index=self.__index, t=t)
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 MetaField is used in a region projection (:meth:`~.reg_proj...
6.815312
14.581871
0.467383
semiJoinDataset_exists = False if isinstance(meta_predicate, MetaField): meta_condition = Some(meta_predicate.getMetaCondition()) elif meta_predicate is None: meta_condition = none() else: raise TypeError("meta_predicate must be a MetaField o...
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 selection based on the existence of certain metadata :attr:`~.semiJoinMeta` attributes and the matching of their values with t...
2.585952
2.455978
1.052921
return self.select(meta_predicate=predicate, semiJoinDataset=semiJoinDataset, semiJoinMeta=semiJoinMeta)
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: an other GMQLDataset :param semiJoinMeta: a list of metadata :return: a new GMQLData...
2.980375
4.255588
0.700344
return self.select(region_predicate=predicate, semiJoinMeta=semiJoinMeta, semiJoinDataset=semiJoinDataset)
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 semiJoinDataset: an other GMQLDataset :param semiJoinMeta: a list of metadata :return: a ...
4.277401
5.296692
0.807561
return self.project(projected_meta=attr_list, new_attr_dict=new_attr_dict, all_but_meta=all_but)
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 from the projection. :param new_attr_dict: an optional dictionary of the form {'new_fi...
4.260733
5.450749
0.781678
return self.project(projected_regs=field_list, all_but_regs=all_but, new_field_dict=new_field_dict)
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 specified :param new_field_dict: an optional dictionary of the form {'new_f...
3.978479
6.09334
0.652923
if isinstance(new_attr_dict, dict): expBuild = self.pmg.getNewExpressionBuilder(self.__index) aggregates = [] for k in new_attr_dict.keys(): if isinstance(k, str): item = new_attr_dict[k] if isinstance(item, Agg...
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 them to the existing metadata attribute-value pairs of ...
4.547488
4.231819
1.074594
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="normal")
def normal_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None)
*Wrapper of* ``COVER`` The normal cover operation as described in :meth:`~.cover`. Equivalent to calling:: dataset.cover("normal", ...)
3.192764
4.922324
0.648629
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="flat")
def flat_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None)
*Wrapper of* ``COVER`` Variant of the function :meth:`~.cover` that returns the union of all the regions which contribute to the COVER. More precisely, it returns the contiguous regions that start from the first end and stop at the last end of the regions which would contribute to ea...
3.423505
4.677682
0.731881
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="summit")
def summit_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None)
*Wrapper of* ``COVER`` Variant of the function :meth:`~.cover` that returns only those portions of the COVER result where the maximum number of regions overlap (this is done by returning only regions that start from a position after which the number of overlaps does not increase, and s...
3.274887
4.231748
0.773885
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="histogram")
def histogram_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None)
*Wrapper of* ``COVER`` Variant of the function :meth:`~.cover` that returns all regions contributing to the COVER divided in different (contiguous) parts according to their accumulation index value (one part for each different accumulation value), which is assigned to the AccIndex re...
3.456413
4.682357
0.738178
if isinstance(other, GMQLDataset): other_idx = other.__index else: raise TypeError("other must be a GMQLDataset. " "{} was provided".format(type(other))) if isinstance(joinBy, list) and \ all([isinstance(x, str) for x in ...
def difference(self, other, joinBy=None, exact=False)
*Wrapper of* ``DIFFERENCE`` DIFFERENCE is a binary, non-symmetric operator that produces one sample in the result for each sample of the first operand, by keeping the same metadata of the first operand sample and only those regions (with their schema and values) of the first operand sam...
3.031679
2.83326
1.070032
if not isinstance(left_name, str) or \ not isinstance(right_name, str): raise TypeError("left_name and right_name must be strings. " "{} - {} was provided".format(type(left_name), type(right_name))) if isinstance(other, GMQLDataset): ...
def union(self, other, left_name="LEFT", right_name="RIGHT")
*Wrapper of* ``UNION`` The UNION operation is used to integrate homogeneous or heterogeneous samples of two datasets within a single dataset; for each sample of either one of the input datasets, a sample is created in the result as follows: * its metadata are the same as in...
2.708977
2.651482
1.021684
if isinstance(groupBy, list) and \ all([isinstance(x, str) for x in groupBy]): groupBy = Some(groupBy) elif groupBy is None: groupBy = none() else: raise TypeError("groupBy must be a list of strings. " "{} was ...
def merge(self, groupBy=None)
*Wrapper of* ``MERGE`` The MERGE operator builds a new dataset consisting of a single sample having * as regions all the regions of all the input samples, with the same attributes and values * as metadata the union of all the metadata attribute-values ...
4.837443
4.334348
1.116072
return self.group(meta=meta, meta_aggregates=meta_aggregates)
def meta_group(self, meta, meta_aggregates=None)
*Wrapper of* ``GROUP`` Group operation only for metadata. For further information check :meth:`~.group`
4.050588
4.059461
0.997814
return self.group(regs=regs, regs_aggregates=regs_aggregates)
def regs_group(self, regs, regs_aggregates=None)
*Wrapper of* ``GROUP`` Group operation only for region data. For further information check :meth:`~.group`
4.388731
4.728702
0.928105
current_mode = get_mode() new_index = self.__modify_dag(current_mode) if current_mode == 'local': return Materializations.materialize_local(new_index, output_path, all_load) elif current_mode == 'remote': return Materializations.materialize_remote(new_ind...
def materialize(self, output_path=None, output_name=None, all_load=True)
*Wrapper of* ``MATERIALIZE`` Starts the execution of the operations for the GMQLDataset. PyGMQL implements lazy execution and no operation is performed until the materialization of the results is requestd. This operation can happen both locally or remotely. * Local mode: if the GMQLDat...
3.842306
3.630692
1.058285
message = self.get_message() if message is None: self.sleep(self.idle_time) return None self.dispatch(message) # In non-greenthread environments this does nothing. In green-thread # environments this yields the context so messages can be acted u...
def step(self)
Grab a new message and dispatch it to the handler. This method should not be extended or overwritten. Instead, implementations of this daemon should implement the 'get_message()' and 'handle_message()' methods.
9.736974
7.867857
1.237564
config = getattr(app, 'config', app) self.team_id = config.get('TEAM_ID')
def init_app(self, app=None)
Initialize application configuration
6.510932
6.864803
0.948451
if team_id is None: team_id = self.team_id if team_id is None: raise RuntimeError('TEAM_ID is not found in your configuration!') def deco(func): self._commands[(team_id, command)] = (func, token, methods, kwargs) return func retur...
def command(self, command, token, team_id=None, methods=['GET'], **kwargs)
A decorator used to register a command. Example:: @slack.command('your_command', token='your_token', team_id='your_team_id', methods=['POST']) def your_method(**kwargs): text = kwargs.get('text') return slack.response(text) ...
3.030859
3.809374
0.795632
from flask import request method = request.method data = request.args if method == 'POST': data = request.form token = data.get('token') team_id = data.get('team_id') command = data.get('command') or data.get('trigger_word') if isi...
def dispatch(self)
Dispatch http request to registerd commands. Example:: slack = Slack(app) app.add_url_rule('/', view_func=slack.dispatch)
3.629155
3.242562
1.119224
if (team_id, command) not in self._commands: raise SlackError('Command {0} is not found in team {1}'.format( command, team_id)) func, _token, methods, kwargs = self._commands[(team_id, command)] if method not in methods: raise Slack...
def validate(self, command, token, team_id, method)
Validate request queries with registerd commands :param command: command parameter from request :param token: token parameter from request :param team_id: team_id parameter from request :param method: the request method
3.937952
4.081566
0.964814