Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def slice(self, window_size=1, step_size=1, cumulative=False, count_only=False, subcorpus=True, feature_name=None): if 'date' not in self.indices: self.index('date') start = min(self.indices['date'].keys()) end = m...
[ "\n Returns a generator that yields ``(key, subcorpus)`` tuples for\n sequential time windows.\n\n Two common slicing patterns are the \"sliding time-window\" and the\n \"time-period\" patterns. Whereas time-period slicing divides the corpus\n into subcorpora by sequential non-ove...
Please provide a description of the function:def distribution(self, **slice_kwargs): values = [] keys = [] for key, size in self.slice(count_only=True, **slice_kwargs): values.append(size) keys.append(key) return keys, values
[ "\n Calculates the number of papers in each slice, as defined by\n ``slice_kwargs``.\n\n Examples\n --------\n .. code-block:: python\n\n >>> corpus.distribution(step_size=1, window_size=1)\n [5, 5]\n\n Parameters\n ----------\n slice_kwarg...
Please provide a description of the function:def feature_distribution(self, featureset_name, feature, mode='counts', **slice_kwargs): values = [] keys = [] fset = self.features[featureset_name] for key, papers in self.slice(subcorpus=False, **slice...
[ "\n Calculates the distribution of a feature across slices of the corpus.\n\n Examples\n --------\n .. code-block:: python\n\n >>> corpus.feature_distribution(featureset_name='citations', \\\n ... feature='DOLE RJ 1965 CELL', \\\n ...
Please provide a description of the function:def top_features(self, featureset_name, topn=20, by='counts', perslice=False, slice_kwargs={}): if perslice: return [(k, subcorpus.features[featureset_name].top(topn, by=by)) for k, subcorpus in self.slic...
[ "\n Retrieves the top ``topn`` most numerous features in the corpus.\n\n Parameters\n ----------\n featureset_name : str\n Name of a :class:`.FeatureSet` in the :class:`.Corpus`\\.\n topn : int\n (default: ``20``) Number of features to return.\n by : s...
Please provide a description of the function:def subcorpus(self, selector): subcorpus = self.__class__(self[selector], index_by=self.index_by, index_fields=self.indices.keys(), index_features=self.features.keys()) ...
[ "\n Generates a new :class:`.Corpus` using the criteria in ``selector``.\n\n Accepts selector arguments just like :meth:`.Corpus.select`\\.\n\n .. code-block:: python\n\n >>> corpus = Corpus(papers)\n >>> subcorpus = corpus.subcorpus(('date', 1995))\n >>> subcorpu...
Please provide a description of the function:def merge(corpus_1, corpus_2, match_by=['ayjid'], match_threshold=1., index_by='ayjid'): def norm(value): if type(value) in [str, unicode]: return value.strip().lower() return value combined = [] exclude_1 = [] ex...
[ "\n Combines two :class:`.Corpus` instances.\n\n The default behavior is to match :class:`.Paper`\\s using the fields in\n ``match_by``\\. If several fields are specified, ``match_threshold`` can be\n used to control how well two :class:`.Paper`\\s must match to be combined.\n\n Alternatively, ``matc...
Please provide a description of the function:def ayjid(self): try: # TODO: make this less terrible. return self._ayjid except: pass if hasattr(self, 'authors_init') and len(self.authors_init) > 0: al, ai = self.authors_init[0] elif hasatt...
[ "\n Fuzzy WoS-style identifier, comprised of first author's name (LAST I),\n pubdate, and journal.\n\n Returns\n -------\n ayjid : str\n " ]
Please provide a description of the function:def authors(self): if hasattr(self, 'authors_full'): return self.authors_full elif hasattr(self, 'authors_init'): return self.authors_init else: return []
[ "\n Get the authors of the current :class:`.Paper` instance.\n\n Uses ``authors_full`` if it is available. Otherwise, uses\n ``authors_init``.\n\n Returns\n -------\n authors : :class:`.Feature`\n Author names are in the format ``LAST F``.\n " ]
Please provide a description of the function:def citations(self): if hasattr(self, 'citedReferences'): return [cr.ayjid for cr in self.citedReferences if cr is not None] return []
[ "\n Cited references as a :class:`.Feature`\\.\n\n Returns\n -------\n citations : :class:`.Feature`\n " ]
Please provide a description of the function:def _forward(X, s=1.1, gamma=1., k=5): X = list(X) def alpha(i): return (n/T)*(s**i) def tau(i, j): if j > i: return (j-i)*gamma*log(n) return 0. def f(j, x): return alpha(j) * exp(-1. * alpha(j) * x) d...
[ "\n Forward dynamic algorithm for burstness automaton HMM, from `Kleinberg\n (2002) <http://www.cs.cornell.edu/home/kleinber/bhs.pdf>`_.\n\n Parameters\n ----------\n X : list\n A series of time-gaps between events.\n s : float\n (default: 1.1) Scaling parameter ( > 1.)that controls ...
Please provide a description of the function:def burstness(corpus, featureset_name, features=[], k=5, topn=20, perslice=False, normalize=True, **kwargs): # If `features` of interest are not specified, calculate burstness for the # top `topn` features. if len(features) == 0: T = ...
[ "\n Estimate burstness profile for the ``topn`` features (or ``flist``) in\n ``feature``.\n\n Uses the popular burstness automaton model inroduced by `Kleinberg (2002)\n <http://www.cs.cornell.edu/home/kleinber/bhs.pdf>`_.\n\n Parameters\n ----------\n corpus : :class:`.Corpus`\n feature : s...
Please provide a description of the function:def feature_burstness(corpus, featureset_name, feature, k=5, normalize=True, s=1.1, gamma=1., **slice_kwargs): if featureset_name not in corpus.features: corpus.index_feature(featureset_name) if 'date' not in corpus.indices: ...
[ "\n Estimate burstness profile for a feature over the ``'date'`` axis.\n\n Parameters\n ----------\n corpus : :class:`.Corpus`\n feature : str\n Name of featureset in ``corpus``. E.g. ``'citations'``.\n findex : int\n Index of ``feature`` in ``corpus``.\n k : int\n (default...
Please provide a description of the function:def sigma(G, corpus, featureset_name, B=None, **kwargs): if 'date' not in corpus.indices: corpus.index('date') # Calculate burstness if not provided. if not B: B = burstness(corpus, featureset_name, features=G.nodes(), **kwargs) Sigma =...
[ "\n Calculate sigma (from `Chen 2009 <http://arxiv.org/pdf/0904.1439.pdf>`_)\n for all of the nodes in a :class:`.GraphCollection`\\.\n\n You can set parameters for burstness estimation using ``kwargs``:\n\n ========= ===============================================================\n Parameter Des...
Please provide a description of the function:def cocitation(corpus, min_weight=1, edge_attrs=['ayjid', 'date'], **kwargs): return cooccurrence(corpus, 'citations', min_weight=min_weight, edge_attrs=edge_attrs, **kwargs)
[ "\n Generate a cocitation network.\n\n A **cocitation network** is a network in which vertices are papers, and\n edges indicate that two papers were cited by the same third paper.\n `CiteSpace\n <http://cluster.cis.drexel.edu/~cchen/citespace/doc/jasist2006.pdf>`_\n is a popular desktop applicatio...
Please provide a description of the function:def context_chunks(self, context): N_chunks = len(self.contexts[context]) chunks = [] for j in xrange(N_chunks): chunks.append(self.context_chunk(context, j)) return chunks
[ "\n Retrieves all tokens, divided into the chunks in context ``context``.\n\n Parameters\n ----------\n context : str\n Context name.\n\n Returns\n -------\n chunks : list\n Each item in ``chunks`` is a list of tokens.\n " ]
Please provide a description of the function:def context_chunk(self, context, j): N_chunks = len(self.contexts[context]) start = self.contexts[context][j] if j == N_chunks - 1: end = len(self) else: end = self.contexts[context][j+1] return [self[...
[ "\n Retrieve the tokens in the ``j``th chunk of context ``context``.\n\n Parameters\n ----------\n context : str\n Context name.\n j : int\n Index of a context chunk.\n\n Returns\n -------\n chunk : list\n List of tokens in the...
Please provide a description of the function:def add_context(self, name, indices, level=None): self._validate_context((name, indices)) if level is None: level = len(self.contexts_ranked) self.contexts_ranked.insert(level, name) self.contexts[name] = indices
[ "\n Add a new context level to the hierarchy.\n\n By default, new contexts are added to the lowest level of the hierarchy.\n To insert the context elsewhere in the hierarchy, use the ``level``\n argument. For example, ``level=0`` would insert the context at the\n highest level of ...
Please provide a description of the function:def top(self, topn=10): return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]
[ "\n Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n Examples\n --------\n\n .. code-block:: python\n\n >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n >>> myFeature.top(1)\n [('trapezoid', 5)]\n\n Parameters\n ...
Please provide a description of the function:def top(self, topn, by='counts'): if by not in ['counts', 'documentCounts']: raise NameError('kwarg `by` must be "counts" or "documentCounts"') cvalues = getattr(self, by) order = argsort(list(cvalues.values()))[::-1][:topn] ...
[ "\n Get the top ``topn`` features in the :class:`.FeatureSet`\\.\n\n Parameters\n ----------\n topn : int\n Number of features to return.\n by : str\n (default: 'counts') How features should be sorted. Must be 'counts'\n or 'documentcounts'.\n\n ...
Please provide a description of the function:def context_chunks(self, context): chunks = [] papers = [] for paper, feature in self.features.iteritems(): if context in feature.contexts: new_chunks = feature.context_chunks(context) else: ...
[ "\n Retrieves all tokens, divided into the chunks in context ``context``.\n\n If ``context`` is not found in a feature, then the feature will be\n treated as a single chunk.\n\n Parameters\n ----------\n context : str\n Context name.\n\n Returns\n -...
Please provide a description of the function:def transform(self, func): features = {} for i, feature in self.features.iteritems(): feature_ = [] for f, v in feature: t = self.lookup[f] v_ = func(f, v, self.counts[t], self.documentCounts[t]...
[ "\n Apply a transformation to tokens in this :class:`.FeatureSet`\\.\n\n Parameters\n ----------\n func : callable\n Should take four parameters: token, value in document (e.g. count),\n value in :class:`.FeatureSet` (e.g. overall count), and document\n c...
Please provide a description of the function:def build(self, corpus, method, slice_kwargs={}, method_kwargs={}): if not hasattr(method, '__call__'): if not hasattr(networks, method): raise NameError('No such method') method = getattr(networks, method) for...
[ "\n Generate a set of :ref:`networkx.Graph <networkx:graph>`\\s using\n ``method`` on the slices in ``corpus``\\.\n\n Parameters\n ----------\n corpus : :class:`.Corpus`\n method : str or func\n If str, looks for ``method`` in the ``tethne`` namespace.\n s...
Please provide a description of the function:def add(self, name, graph): if name in self: raise ValueError("{0} exists in this GraphCollection".format(name)) elif hasattr(self, unicode(name)): raise ValueError("Name conflicts with an existing attribute") indexed...
[ "\n Index and add a :ref:`networkx.Graph <networkx:graph>` to the\n :class:`.GraphCollection`.\n\n Parameters\n ----------\n name : hashable\n Unique name used to identify the `graph`.\n graph : :ref:`networkx.Graph <networkx:graph>`\n\n Raises\n --...
Please provide a description of the function:def index(self, name, graph): nodes = graph.nodes() # Index new nodes. new_nodes = list(set(nodes) - set(self.node_index.values())) start = max(len(self.node_index) - 1, max(self.node_index.keys())) for i in xrange(start, sta...
[ "\n Index any new nodes in `graph`, and relabel the nodes in `graph` using\n the index.\n\n Parameters\n ----------\n name : hashable\n Unique name used to identify the `graph`.\n graph : networkx.Graph\n\n Returns\n -------\n indexed_graph :...
Please provide a description of the function:def nodes(self, data=False, native=True): nodes = self.master_graph.nodes(data=data) if native: if data: nodes = [(self.node_index[n], attrs) for n, attrs in nodes] else: nodes = [self.node_ind...
[ "\n Returns a list of all nodes in the :class:`.GraphCollection`\\.\n\n Parameters\n ----------\n data : bool\n (default: False) If True, returns a list of 2-tuples containing\n node labels and attributes.\n\n Returns\n -------\n nodes : list\n ...
Please provide a description of the function:def edges(self, data=False, native=True): edges = self.master_graph.edges(data=data) if native: if data: edges = [(self.node_index[s], self.node_index[t], attrs) for s, t, attrs in edges] ...
[ "\n Returns a list of all edges in the :class:`.GraphCollection`\\.\n\n Parameters\n ----------\n data : bool\n (default: False) If True, returns a list of 3-tuples containing\n source and target node labels, and attributes.\n\n Returns\n -------\n ...
Please provide a description of the function:def order(self, piecewise=False): if piecewise: return {k: v.order() for k, v in self.items()} return self.master_graph.order()
[ "\n Returns the total number of nodes in the :class:`.GraphCollection`\\.\n " ]
Please provide a description of the function:def size(self, piecewise=False): if piecewise: return {k: v.size() for k, v in self.items()} return self.master_graph.size()
[ "\n Returns the total number of edges in the :class:`.GraphCollection`\\.\n " ]
Please provide a description of the function:def collapse(self, weight_attr='weight'): if self.directed: graph = nx.DiGraph() else: graph = nx.Graph() # Transfer all nodes and attributes. for n, attrs in self.master_graph.nodes(data=True): g...
[ "\n Returns a :ref:`networkx.Graph <networkx:graph>` or :class:`networkx.DiGraph` in which\n the edges between each pair of nodes are collapsed into a single\n weighted edge.\n " ]
Please provide a description of the function:def analyze(self, method_name, mapper=map, invert=False, **kwargs): # Find the analysis method, if possible. if hasattr(method_name, '__iter__'): mpath = method_name if type(mpath) in [str, unicode]: mpath = [...
[ "\n Apply a method from NetworkX to each of the graphs in the\n :class:`.GraphCollection`\\.\n\n Examples\n --------\n .. code-block:: python\n\n >>> G.analyze('betweenness_centrality')\n {'test': {0: 1.0, 1: 0.0, 2: 0.0},\n 'test2': {0: 0.0, 1: 0.0,...
Please provide a description of the function:def edge_history(self, source, target, attribute): return {attr['graph']: attr[attribute] for i, attr in self.master_graph.edge[source][target].items()}
[ "\n Returns a dictionary of attribute vales for each Graph in the\n :class:`.GraphCollection` for a single edge.\n\n Parameters\n ----------\n source : str\n Identifier for source node.\n target : str\n Identifier for target node.\n attribute : ...
Please provide a description of the function:def union(self, weight_attr='_weight'): if type(self.master_graph) is nx.MultiDiGraph: graph = nx.DiGraph() else: graph = nx.Graph() edge_attrs = defaultdict(list) for u, v, a in self.master_graph.edges(data...
[ "\n Returns the union of all graphs in this :class:`.GraphCollection`\\.\n\n The number of graphs in which an edge exists between each node pair `u` and `v`\n is stored in the edge attribute given be `weight_attr` (default: `_weight`).\n\n Parameters\n ----------\n weight_a...
Please provide a description of the function:def terms(model, threshold=0.01, **kwargs): select = lambda f, v, c, dc: v > threshold graph = cooccurrence(model.phi, filter=select, **kwargs) # Only include labels for terms that are actually in the graph. label_map = {k: v for k, v in model.vocabula...
[ "\n Two terms are coupled if the posterior probability for both terms is\n greather than ``threshold`` for the same topic.\n\n Parameters\n ----------\n model : :class:`.LDAModel`\n threshold : float\n Default: 0.01\n kwargs : kwargs\n Passed on to :func:`.cooccurrence`\\.\n\n ...
Please provide a description of the function:def topic_coupling(model, threshold=None, **kwargs): if not threshold: threshold = 3./model.Z select = lambda f, v, c, dc: v > threshold graph = coupling(model.corpus, 'topics', filter=select, **kwargs) graph.name = '' return graph
[ "\n Two papers are coupled if they both contain a shared topic above a\n ``threshold``.\n\n Parameters\n ----------\n model : :class:`.LDAModel`\n threshold : float\n Default: ``3./model.Z``\n kwargs : kwargs\n Passed on to :func:`.coupling`\\.\n\n Returns\n -------\n :re...
Please provide a description of the function:def cotopics(model, threshold=None, **kwargs): if not threshold: threshold = 2./model.Z select = lambda f, v, c, dc: v > threshold return cooccurrence(model.corpus, 'topics', filter=select, **kwargs)
[ "\n Two topics are coupled if they occur (above some ``threshold``) in the same\n document (s).\n\n Parameters\n ----------\n model : :class:`.LDAModel`\n threshold : float\n Default: ``2./model.Z``\n kwargs : kwargs\n Passed on to :func:`.cooccurrence`\\.\n\n Returns\n ----...
Please provide a description of the function:def distance(model, method='cosine', percentile=90, bidirectional=False, normalize=True, smooth=False, transform='log', **kwargs): if method in ['hamming','jaccard']: raise RuntimeError( 'There is no sensicle interpretation of {0} f...
[ "\n Generate a network of :class:`.Paper`\\s based on a distance metric from\n `scipy.spatial.distance\n <http://docs.scipy.org/doc/scipy/reference/spatial.distance.html>`_\n using :ref:`sparse-feature-vector`\\s over the dimensions in ``model``.\n\n The only two methods that will not work in this co...
Please provide a description of the function:def kl_divergence(V_a, V_b): # Find shared features. Ndiff = _shared_features(V_a, V_b) # aprob and bprob should each sum to 1.0 aprob = map(lambda v: float(v)/sum(V_a), V_a) bprob = map(lambda v: float(v)/sum(V_b), V_b) # Smooth according to ...
[ "\n Calculate Kullback-Leibler distance.\n\n Uses the smoothing method described in `Bigi 2003\n <http://lvk.cs.msu.su/~bruzz/articles/classification/Using%20Kullback-Leibler%20Distance%20for%20Text%20Categorization.pdf>`_\n to facilitate better comparisons between vectors describing wordcounts.\n\n ...
Please provide a description of the function:def cosine_similarity(F_a, F_b): shared = list(F_a.unique & F_b.unique) A = [dict(F_a.norm)[i] for i in shared] B = [dict(F_b.norm)[i] for i in shared] dot = sum(map(lambda a, b: a*b, A, B)) mag_A = sqrt(sum(map(lambda a: a**2, A))) mag_B = sqrt...
[ "\n Calculate `cosine similarity\n <http://en.wikipedia.org/wiki/Cosine_similarity>`_ for sparse feature\n vectors.\n\n Parameters\n ----------\n F_a : :class:`.Feature`\n F_b : :class:`.Feature`\n\n Returns\n -------\n similarity : float\n Cosine similarity.\n " ]
Please provide a description of the function:def _shared_features(adense, bdense): a_indices = set(nonzero(adense)) b_indices = set(nonzero(bdense)) shared = list(a_indices & b_indices) diff = list(a_indices - b_indices) Ndiff = len(diff) return Ndiff
[ "\n Number of features in ``adense`` that are also in ``bdense``.\n " ]
Please provide a description of the function:def _smooth(aprob, bprob, Ndiff): gamma, epsilon = _smoothing_parameters(aprob, bprob, Ndiff) # Remove zeros. in_a = [i for i,v in enumerate(aprob) if abs(v) > 0.0] aprob = list([list(aprob)[i] for i in in_a]) bprob = list([list(bprob)[i]*gamma for ...
[ "\n Smooth distributions for KL-divergence according to `Bigi 2003\n <http://link.springer.com/chapter/10.1007%2F3-540-36618-0_22?LI=true>`_.\n " ]
Please provide a description of the function:def cooccurrence(corpus_or_featureset, featureset_name=None, min_weight=1, edge_attrs=['ayjid', 'date'], filter=None): if not filter: filter = lambda f, v, c, dc: dc >= min_weight featureset = _get_featureset(corpus_or...
[ "\n A network of feature elements linked by their joint occurrence in papers.\n " ]
Please provide a description of the function:def coupling(corpus_or_featureset, featureset_name=None, min_weight=1, filter=lambda f, v, c, dc: True, node_attrs=[]): featureset = _get_featureset(corpus_or_featureset, featureset_name) c = lambda f: featureset.count(f) # ...
[ "\n A network of papers linked by their joint posession of features.\n " ]
Please provide a description of the function:def multipartite(corpus, featureset_names, min_weight=1, filters={}): pairs = Counter() node_type = {corpus._generate_index(p): {'type': 'paper'} for p in corpus.papers} for featureset_name in featureset_names: ftypes = {} ...
[ "\n A network of papers and one or more featuresets.\n " ]
Please provide a description of the function:def mutual_information(corpus, featureset_name, min_weight=0.9, filter=lambda f, v, c, dc: True): graph = feature_cooccurrence(corpus, featureset_name, min_weight=1, filter=filter) mgraph = type(graph)() ...
[ "\n Generates a graph of features in ``featureset`` based on normalized\n `pointwise mutual information (nPMI)\n <http://en.wikipedia.org/wiki/Pointwise_mutual_information>`_.\n\n .. math::\n\n nPMI(i,j)=\\\\frac{log(\\\\frac{p_{ij}}{p_i*p_j})}{-1*log(p_{ij})}\n\n ...where :math:`p_i` and :math...
Please provide a description of the function:def _strip_punctuation(s): if type(s) is str and not PYTHON_3: # Bytestring (default in Python 2.x). return s.translate(string.maketrans("",""), string.punctuation) else: # Unicode string (default in Python 3.x). translate_tabl...
[ "\n Removes all punctuation characters from a string.\n " ]
Please provide a description of the function:def overlap(listA, listB): if (listA is None) or (listB is None): return [] else: return list(set(listA) & set(listB))
[ "\n Return list of objects shared by listA, listB.\n " ]
Please provide a description of the function:def subdict(super_dict, keys): sub_dict = {} valid_keys = super_dict.keys() for key in keys: if key in valid_keys: sub_dict[key] = super_dict[key] return sub_dict
[ "\n Returns a subset of the super_dict with the specified keys.\n " ]
Please provide a description of the function:def attribs_to_string(attrib_dict, keys): for key, value in attrib_dict.iteritems(): if (isinstance(value, list) or isinstance(value, dict) or isinstance(value, tuple)): attrib_dict[key] = value return attrib_dict
[ "\n A more specific version of the subdict utility aimed at handling\n node and edge attribute dictionaries for NetworkX file formats such as\n gexf (which does not allow attributes to have a list type) by making\n them writable in those formats\n " ]
Please provide a description of the function:def concat_list(listA, listB, delim=' '): # Lists must be of equal length. if len(listA) != len(listB): raise IndexError('Input lists are not parallel.') # Concatenate lists. listC = [] for i in xrange(len(listA)): app = listA[i] + ...
[ "\n Concatenate list elements pair-wise with the delim character\n Returns the concatenated list\n Raises index error if lists are not parallel\n " ]
Please provide a description of the function:def strip_non_ascii(s): stripped = (c for c in s if 0 < ord(c) < 127) clean_string = u''.join(stripped) return clean_string
[ "\n Returns the string without non-ASCII characters.\n\n Parameters\n ----------\n string : string\n A string that may contain non-ASCII characters.\n\n Returns\n -------\n clean_string : string\n A string that does not contain non-ASCII characters.\n\n " ]
Please provide a description of the function:def dict_from_node(node, recursive=False): dict = {} for snode in node: if len(snode) > 0: if recursive: # Will drill down until len(snode) <= 0. value = dict_from_node(snode, True) else: ...
[ "\n Converts ElementTree node to a dictionary.\n\n Parameters\n ----------\n node : ElementTree node\n recursive : boolean\n If recursive=False, the value of any field with children will be the\n number of children.\n\n Returns\n -------\n dict : nested dictionary.\n Tag...
Please provide a description of the function:def feed(self, data): try: self.rawdata = self.rawdata + data except TypeError: data = unicode(data) self.rawdata = self.rawdata + data self.goahead(0)
[ "\n added this check as sometimes we are getting the data in integer format instead of string\n " ]
Please provide a description of the function:def write_csv(graph, prefix): node_headers = list(set([a for n, attrs in graph.nodes(data=True) for a in attrs.keys()])) edge_headers = list(set([a for s, t, attrs in graph.edges(data=True) for a in attrs...
[ "\n Write ``graph`` as tables of nodes (``prefix-nodes.csv``) and edges\n (``prefix-edges.csv``).\n\n Parameters\n ----------\n graph : :ref:`networkx.Graph <networkx:graph>`\n prefix : str\n " ]
Please provide a description of the function:def to_sif(graph, output_path): warnings.warn("Removed in 0.8. Use write_csv instead.", DeprecationWarning) graph = _strip_list_attributes(graph) if output_path[-4:] == ".sif": output_path = output_path[:-4] if nx.number_of_nodes(graph) == 0:...
[ "\n Generates Simple Interaction Format output file from provided graph.\n\n The SIF specification is described\n `here <http://wiki.cytoscape.org/Cytoscape_User_Manual/Network_Formats>`_.\n\n :func:`.to_sif` will generate a .sif file describing the network, and a few\n .eda and .noa files containing...
Please provide a description of the function:def to_gexf(graph, output_path): warnings.warn("Removed in 0.8.", DeprecationWarning) graph = _strip_list_attributes(graph) nx.write_gexf(graph, output_path + ".gexf")
[ "Writes graph to `GEXF <http://gexf.net>`_.\n\n Uses the NetworkX method\n `write_gexf <http://networkx.lanl.gov/reference/generated/networkx.readwrite.gexf.write_gexf.html>`_.\n\n Parameters\n ----------\n graph : networkx.Graph\n The Graph to be exported to GEXF.\n output_path : str\n ...
Please provide a description of the function:def write_graphml(graph, path, encoding='utf-8', prettyprint=True): graph = _strip_list_attributes(graph) writer = TethneGraphMLWriter(encoding=encoding, prettyprint=prettyprint) writer.add_graph_element(graph) writer.dump(open(path, 'wb'))
[ "Writes graph to `GraphML <http://graphml.graphdrawing.org/>`_.\n\n Uses the NetworkX method\n `write_graphml <http://networkx.lanl.gov/reference/generated/networkx.readwrite.graphml.write_graphml.html>`_.\n\n Parameters\n ----------\n graph : networkx.Graph\n The Graph to be exported to Graph...
Please provide a description of the function:def serializeCorpus(self): corpus_details = [{ "model": "django-tethne.corpus", "pk": self.corpus_id, "fields": { "source": self.source, "date_created":strftime("%Y-%m-%d...
[ "\n This method creates a fixture for the \"django-tethne_corpus\" model.\n Returns\n -------\n corpus_details in JSON format which can written to a file.\n\n " ]
Please provide a description of the function:def serializePaper(self): pid = tethnedao.getMaxPaperID(); papers_details = [] for paper in self.corpus: pid = pid + 1 paper_key = getattr(paper, Serialize.paper_source_map[self.source]) self.paperIdMap[pa...
[ "\n This method creates a fixture for the \"django-tethne_paper\" model.\n\n Returns\n -------\n paper_details in JSON format, which can written to a file.\n\n " ]
Please provide a description of the function:def serializeAuthors(self): author_details = [] auid = tethnedao.getMaxAuthorID() for val in self.corpus.features['authors'].index.values(): auid = auid + 1 self.authorIdMap[val[1]+val[0]] = auid instanceDa...
[ "\n This method creates a fixture for the \"django-tethne_author\" model.\n\n Returns\n -------\n\n Author details in JSON format, which can be written to a file.\n\n " ]
Please provide a description of the function:def serializeAuthorInstances(self): author_instance_details = [] au_instanceid = tethnedao.getMaxAuthorInstanceID() for paper in self.corpus: paper_key = getattr(paper, Serialize.paper_source_map[self.source]) for aut...
[ "\n This method creates a fixture for the \"django-tethne_author\" model.\n\n Returns\n -------\n Author Instance details which can be written to a file\n\n ", "\n identity_data = {\n \"model\": \"django-tethne.author_identity\",\n ...
Please provide a description of the function:def serializeCitation(self): citation_details = [] citation_id = tethnedao.getMaxCitationID() for citation in self.corpus.features['citations'].index.values(): date_match = re.search(r'(\d+)', citation) if date_match ...
[ "\n This method creates a fixture for the \"django-tethne_citation\" model.\n\n Returns\n -------\n citation details which can be written to a file\n\n " ]
Please provide a description of the function:def serializeInstitution(self): institution_data = [] institution_instance_data = [] affiliation_data = [] affiliation_id = tethnedao.getMaxAffiliationID() institution_id = tethnedao.getMaxInstitutionID() institution_i...
[ "\n This method creates a fixture for the \"django-tethne_citation_institution\" model.\n\n Returns\n -------\n institution details which can be written to a file\n\n " ]
Please provide a description of the function:def get_details_from_inst_literal(self, institute_literal, institution_id, institution_instance_id, paper_key): institute_details = institute_literal.split(',') institute_name = institute_details[0] country = institute_details[len(institute_d...
[ "\n This method parses the institute literal to get the following\n 1. Department naame\n 2. Country\n 3. University name\n 4. ZIP, STATE AND CITY (Only if the country is USA. For other countries the standard may vary. So parsing these\n values becomes very difficult. Howev...
Please provide a description of the function:def get_affiliation_details(self, value, affiliation_id, institute_literal): tokens = tuple([t.upper().strip() for t in value.split(',')]) if len(tokens) == 1: tokens = value.split() if len(tokens) > 0: if len(tokens) ...
[ "\n This method is used to map the Affiliation between an author and Institution.\n\n Parameters\n ----------\n value - The author name\n affiliation_id - Primary key of the affiliation table\n institute_literal\n\n Returns\n -------\n Affiliation detai...
Please provide a description of the function:def start(self): while not self.is_start(self.current_tag): self.next() self.new_entry()
[ "\n Find the first data entry and prepare to parse.\n " ]
Please provide a description of the function:def handle(self, tag, data): if self.is_end(tag): self.postprocess_entry() if self.is_start(tag): self.new_entry() if not data or not tag: return if getattr(self, 'parse_only', None) and tag not...
[ "\n Process a single line of data, and store the result.\n\n Parameters\n ----------\n tag : str\n data :\n " ]
Please provide a description of the function:def open(self): if not os.path.exists(self.path): raise IOError("No such path: {0}".format(self.path)) with open(self.path, "rb") as f: msg = f.read() result = chardet.detect(msg) self.buffer = codecs.open(...
[ "\n Open the data file.\n " ]
Please provide a description of the function:def next(self): line = self.buffer.readline() while line == '\n': # Skip forward to the next line with content. line = self.buffer.readline() if line == '': # End of file. self.at_eof = True ...
[ "\n Get the next line of data.\n\n Returns\n -------\n tag : str\n data :\n " ]
Please provide a description of the function:def coauthors(corpus, min_weight=1, edge_attrs=['ayjid', 'date'], **kwargs): return cooccurrence(corpus, 'authors', min_weight=min_weight, edge_attrs=edge_attrs, **kwargs)
[ "\n A graph describing joint authorship in ``corpus``.\n " ]
Please provide a description of the function:def _infer_spaces(s): s = s.lower() # Find the best match for the i first characters, assuming cost has # been built for the i-1 first characters. # Returns a pair (match_cost, match_length). def best_match(i): candidates = enumerate(reverse...
[ "\n Uses dynamic programming to infer the location of spaces in a string\n without spaces.\n " ]
Please provide a description of the function:def extract_text(fpath): with codecs.open(fpath, 'r') as f: # Determine the encoding of the file. document = f.read() encoding = chardet.detect(document)['encoding'] document = document.decode(encoding) tokens = [] sentences = [] i = 0...
[ "\n Extracts structured text content from a plain-text file at ``fpath``.\n\n Parameters\n ----------\n fpath : str\n Path to the text file..\n\n Returns\n -------\n :class:`.StructuredFeature`\n A :class:`.StructuredFeature` that contains sentence context.\n " ]
Please provide a description of the function:def extract_pdf(fpath): with codecs.open(fpath, 'r') as f: # Determine the encoding of the file. document = slate.PDF(f) encoding = chardet.detect(document[0]) tokens = [] pages = [] sentences = [] tokenizer = nltk.tokenize.TextTiling...
[ "\n Extracts structured text content from a PDF at ``fpath``.\n\n Parameters\n ----------\n fpath : str\n Path to the PDF.\n\n Returns\n -------\n :class:`.StructuredFeature`\n A :class:`.StructuredFeature` that contains page and sentence contexts.\n " ]
Please provide a description of the function:def read(path, corpus=True, index_by='uri', follow_links=False, **kwargs): # TODO: is there a case where `from_dir` would make sense? parser = ZoteroParser(path, index_by=index_by, follow_links=follow_links) papers = parser.parse() if corpus: c...
[ "\n Read bibliographic data from Zotero RDF.\n\n Examples\n --------\n Assuming that the Zotero collection was exported to the directory\n ``/my/working/dir`` with the name ``myCollection``, a subdirectory should\n have been created at ``/my/working/dir/myCollection``, and an RDF file\n should ...
Please provide a description of the function:def open(self): with open(self.path, 'r') as f: corrected = f.read().replace('rdf:resource rdf:resource', 'link:link rdf:resource') with open(self.path, 'w') as f: f.write(corrected) ...
[ "\n Fixes RDF validation issues. Zotero incorrectly uses ``rdf:resource`` as\n a child element for Attribute; ``rdf:resource`` should instead be used\n as an attribute of ``link:link``.\n " ]
Please provide a description of the function:def handle_link(self, value): for s, p, o in self.graph.triples((value, None, None)): if p == LINK_ELEM: return unicode(o).replace('file://', '')
[ "\n rdf:link rdf:resource points to the resource described by a record.\n " ]
Please provide a description of the function:def handle_date(self, value): try: return iso8601.parse_date(unicode(value)).year except iso8601.ParseError: for datefmt in ("%B %d, %Y", "%Y-%m", "%Y-%m-%d", "%m/%d/%Y"): try: # TODO: remov...
[ "\n Attempt to coerced date to ISO8601.\n " ]
Please provide a description of the function:def postprocess_link(self, entry): if not self.follow_links: return if type(entry.link) is not list: entry.link = [entry.link] for link in list(entry.link): if not os.path.exists(link): c...
[ "\n Attempt to load full-text content from resource.\n " ]
Please provide a description of the function:def main(): try: args = get_config() result = webpush( args.sub_info, data=args.data, vapid_private_key=args.key, vapid_claims=args.claims, curl=args.curl, content_encoding=args...
[ " Send data " ]
Please provide a description of the function:def webpush(subscription_info, data=None, vapid_private_key=None, vapid_claims=None, content_encoding="aes128gcm", curl=False, timeout=None, ttl=0): vapid_headers = None if vapid...
[ "\n One call solution to endcode and send `data` to the endpoint\n contained in `subscription_info` using optional VAPID auth headers.\n\n in example:\n\n .. code-block:: python\n\n from pywebpush import python\n\n webpush(\n subscription_info={\n ...
Please provide a description of the function:def encode(self, data, content_encoding="aes128gcm"): # Salt is a random 16 byte array. if not data: return if not self.auth_key or not self.receiver_key: raise WebPushException("No keys specified in subscription info"...
[ "Encrypt the data.\n\n :param data: A serialized block of byte data (String, JSON, bit array,\n etc.) Make sure that whatever you send, your client knows how\n to understand it.\n :type data: str\n :param content_encoding: The content_encoding type to use to encrypt\n ...
Please provide a description of the function:def as_curl(self, endpoint, encoded_data, headers): header_list = [ '-H "{}: {}" \\ \n'.format( key.lower(), val) for key, val in headers.items() ] data = "" if encoded_data: with open("encrypte...
[ "Return the send as a curl command.\n\n Useful for debugging. This will write out the encoded data to a local\n file named `encrypted.data`\n\n :param endpoint: Push service endpoint URL\n :type endpoint: basestring\n :param encoded_data: byte array of encoded data\n :type ...
Please provide a description of the function:def send(self, data=None, headers=None, ttl=0, gcm_key=None, reg_id=None, content_encoding="aes128gcm", curl=False, timeout=None): # Encode the data. if headers is None: headers = dict() encoded = {} headers =...
[ "Encode and send the data to the Push Service.\n\n :param data: A serialized block of data (see encode() ).\n :type data: str\n :param headers: A dictionary containing any additional HTTP headers.\n :type headers: dict\n :param ttl: The Time To Live in seconds for this message if ...
Please provide a description of the function:def yearplot(data, year=None, how='sum', vmin=None, vmax=None, cmap='Reds', fillcolor='whitesmoke', linewidth=1, linecolor=None, daylabels=calendar.day_abbr[:], dayticks=True, monthlabels=calendar.month_abbr[1:], monthticks=True, ax=Non...
[ "\n Plot one year from a timeseries as a calendar heatmap.\n\n Parameters\n ----------\n data : Series\n Data for the plot. Must be indexed by a DatetimeIndex.\n year : integer\n Only data indexed by this year will be plotted. If `None`, the first\n year for which there is data w...
Please provide a description of the function:def calendarplot(data, how='sum', yearlabels=True, yearascending=True, yearlabel_kws=None, subplot_kws=None, gridspec_kws=None, fig_kws=None, **kwargs): yearlabel_kws = yearlabel_kws or {} subplot_kws = subplot_kws or {} gridspec_kws = grids...
[ "\n Plot a timeseries as a calendar heatmap.\n\n Parameters\n ----------\n data : Series\n Data for the plot. Must be indexed by a DatetimeIndex.\n how : string\n Method for resampling data by day. If `None`, assume data is already\n sampled by day and don't resample. Otherwise, ...
Please provide a description of the function:def geosgeometry_str_to_struct(value): ''' Parses a geosgeometry string into struct. Example: SRID=5432;POINT(12.0 13.0) Returns: >> [5432, 12.0, 13.0] ''' result = geos_ptrn.match(value) if not result: return None ...
[]
Please provide a description of the function:def get_env(name, default=None): if name in os.environ: return os.environ[name] if default is not None: return default error_msg = "Set the {} env variable".format(name) raise ImproperlyConfigured(error_msg)
[ "Get the environment variable or return exception" ]
Please provide a description of the function:def remove_nodehandler(self, node): out = None if node in self.node_handlers: out = self.node_handlers.pop(node) return out
[ "remove support for a node\n returns current node handler, so that it\n might be re-added with add_nodehandler()\n " ]
Please provide a description of the function:def user_defined_symbols(self): sym_in_current = set(self.symtable.keys()) sym_from_construction = set(self.no_deepcopy) unique_symbols = sym_in_current.difference(sym_from_construction) return unique_symbols
[ "Return a set of symbols that have been added to symtable after\n construction.\n\n I.e., the symbols from self.symtable that are not in\n self.no_deepcopy.\n\n Returns\n -------\n unique_symbols : set\n symbols in symtable that are not in self.no_deepcopy\n\n ...
Please provide a description of the function:def unimplemented(self, node): self.raise_exception(node, exc=NotImplementedError, msg="'%s' not supported" % (node.__class__.__name__))
[ "Unimplemented nodes." ]
Please provide a description of the function:def raise_exception(self, node, exc=None, msg='', expr=None, lineno=None): if self.error is None: self.error = [] if expr is None: expr = self.expr if len(self.error) > 0 and not isinstance(node...
[ "Add an exception." ]
Please provide a description of the function:def parse(self, text): self.expr = text try: out = ast.parse(text) except SyntaxError: self.raise_exception(None, msg='Syntax Error', expr=text) except: self.raise_exception(None, msg='Runtime Error...
[ "Parse statement/expression to Ast representation." ]
Please provide a description of the function:def run(self, node, expr=None, lineno=None, with_raise=True): # Note: keep the 'node is None' test: internal code here may run # run(None) and expect a None in return. if time.time() - self.start_time > self.max_time: raise Run...
[ "Execute parsed Ast representation for an expression." ]
Please provide a description of the function:def eval(self, expr, lineno=0, show_errors=True): self.lineno = lineno self.error = [] self.start_time = time.time() try: node = self.parse(expr) except: errmsg = exc_info()[1] if len(self.e...
[ "Evaluate a single statement." ]
Please provide a description of the function:def on_return(self, node): # ('value',) self.retval = self.run(node.value) if self.retval is None: self.retval = ReturnedNone return
[ "Return statement: look for None, return special sentinal." ]
Please provide a description of the function:def on_module(self, node): # ():('body',) out = None for tnode in node.body: out = self.run(tnode) return out
[ "Module def." ]
Please provide a description of the function:def on_assert(self, node): # ('test', 'msg') if not self.run(node.test): self.raise_exception(node, exc=AssertionError, msg=node.msg) return True
[ "Assert statement." ]
Please provide a description of the function:def on_dict(self, node): # ('keys', 'values') return dict([(self.run(k), self.run(v)) for k, v in zip(node.keys, node.values)])
[ "Dictionary." ]
Please provide a description of the function:def on_name(self, node): # ('id', 'ctx') ctx = node.ctx.__class__ if ctx in (ast.Param, ast.Del): return str(node.id) else: if node.id in self.symtable: return self.symtable[node.id] else...
[ "Name node." ]
Please provide a description of the function:def node_assign(self, node, val): if node.__class__ == ast.Name: if not valid_symbol_name(node.id) or node.id in self.readonly_symbols: errmsg = "invalid symbol name (reserved word?) %s" % node.id self.raise_except...
[ "Assign a value (not the node.value object) to a node.\n\n This is used by on_assign, but also by for, list comprehension,\n etc.\n\n " ]
Please provide a description of the function:def on_attribute(self, node): # ('value', 'attr', 'ctx') ctx = node.ctx.__class__ if ctx == ast.Store: msg = "attribute for storage: shouldn't be here!" self.raise_exception(node, exc=RuntimeError, msg=msg) sym = s...
[ "Extract attribute." ]