desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns the \'top img\' as specified by the website'
| def get_meta_img_url(self, article_url, doc):
| (top_meta_image, try_one, try_two, try_three, try_four) = ([None] * 5)
try_one = self.get_meta_content(doc, 'meta[property="og:image"]')
if (try_one is None):
link_icon_kwargs = {'tag': 'link', 'attr': 'rel', 'value': 'icon'}
elems = self.parser.getElementsByTag(doc, **link_icon_kwargs)
... |
'Returns meta type of article, open graph protocol'
| def get_meta_type(self, doc):
| return self.get_meta_content(doc, 'meta[property="og:type"]')
|
'If the article has meta description set in the source, use that'
| def get_meta_description(self, doc):
| return self.get_meta_content(doc, 'meta[name=description]')
|
'If the article has meta keywords set in the source, use that'
| def get_meta_keywords(self, doc):
| return self.get_meta_content(doc, 'meta[name=keywords]')
|
'Return the article\'s canonical URL
Gets the first available value of:
1. The rel=canonical tag
2. The og:url tag'
| def get_canonical_link(self, article_url, doc):
| links = self.parser.getElementsByTag(doc, tag='link', attr='rel', value='canonical')
canonical = (self.parser.getAttribute(links[0], 'href') if links else '')
og_url = self.get_meta_content(doc, 'meta[property="og:url"]')
meta_url = (canonical or og_url or '')
if meta_url:
meta_url = meta_ur... |
'Return all of the images on an html page, lxml root'
| def get_img_urls(self, article_url, doc):
| img_kwargs = {'tag': 'img'}
img_tags = self.parser.getElementsByTag(doc, **img_kwargs)
urls = [img_tag.get('src') for img_tag in img_tags if img_tag.get('src')]
img_links = set([urljoin(article_url, url) for url in urls])
return img_links
|
'Retrieves the first image in the \'top_node\'
The top node is essentially the HTML markdown where the main
article lies and the first image in that area is probably signifigcant.'
| def get_first_img_url(self, article_url, top_node):
| node_images = self.get_img_urls(article_url, top_node)
node_images = list(node_images)
if node_images:
return urljoin(article_url, node_images[0])
return ''
|
'Return a list of urls or a list of (url, title_text) tuples
if specified.'
| def _get_urls(self, doc, titles):
| if (doc is None):
return []
a_kwargs = {'tag': 'a'}
a_tags = self.parser.getElementsByTag(doc, **a_kwargs)
if titles:
return [(a.get('href'), a.text) for a in a_tags if a.get('href')]
return [a.get('href') for a in a_tags if a.get('href')]
|
'`doc_or_html`s html page or doc and returns list of urls, the regex
flag indicates we don\'t parse via lxml and just search the html.'
| def get_urls(self, doc_or_html, titles=False, regex=False):
| if (doc_or_html is None):
log.critical('Must extract urls from either html, text or doc!')
return []
if regex:
doc_or_html = re.sub('<[^<]+?>', ' ', str(doc_or_html))
doc_or_html = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a... |
'Inputs source lxml root and source url, extracts domain and
finds all of the top level urls, we are assuming that these are
the category urls.
cnn.com --> [cnn.com/latest, world.cnn.com, cnn.com/asia]'
| def get_category_urls(self, source_url, doc):
| page_urls = self.get_urls(doc)
valid_categories = []
for p_url in page_urls:
scheme = urls.get_scheme(p_url, allow_fragments=False)
domain = urls.get_domain(p_url, allow_fragments=False)
path = urls.get_path(p_url, allow_fragments=False)
if ((not domain) and (not path)):
... |
'Alot of times the first paragraph might be the caption under an image
so we\'ll want to make sure if we\'re going to boost a parent node that
it should be connected to other paragraphs, at least for the first n
paragraphs so we\'ll want to make sure that the next sibling is a
paragraph and has at least some substantia... | def is_boostable(self, node):
| para = 'p'
steps_away = 0
minimum_stopword_count = 5
max_stepsaway_from_node = 3
nodes = self.walk_siblings(node)
for current_node in nodes:
current_node_tag = self.parser.getTag(current_node)
if (current_node_tag == para):
if (steps_away >= max_stepsaway_from_node):
... |
'Adds any siblings that may have a decent score to this node'
| def get_siblings_content(self, current_sibling, baseline_score_siblings_para):
| if ((current_sibling.tag == 'p') and (len(self.parser.getText(current_sibling)) > 0)):
e0 = current_sibling
if e0.tail:
e0 = copy.deepcopy(e0)
e0.tail = ''
return [e0]
else:
potential_paragraphs = self.parser.getElementsByTag(current_sibling, tag='p')
... |
'We could have long articles that have tons of paragraphs
so if we tried to calculate the base score against
the total text score of those paragraphs it would be unfair.
So we need to normalize the score based on the average scoring
of the paragraphs within the top node.
For example if our total score of 10 paragraphs ... | def get_siblings_score(self, top_node):
| base = 100000
paragraphs_number = 0
paragraphs_score = 0
nodes_to_check = self.parser.getElementsByTag(top_node, tag='p')
for node in nodes_to_check:
text_node = self.parser.getText(node)
word_stats = self.stopwords_class(language=self.language).get_stopword_count(text_node)
... |
'Adds a score to the gravityScore Attribute we put on divs
we\'ll get the current score then add the score we\'re passing
in to the current.'
| def update_score(self, node, add_to_score):
| current_score = 0
score_string = self.parser.getAttribute(node, 'gravityScore')
if score_string:
current_score = float(score_string)
new_score = (current_score + add_to_score)
self.parser.setAttribute(node, 'gravityScore', str(new_score))
|
'Stores how many decent nodes are under a parent node'
| def update_node_count(self, node, add_to_count):
| current_score = 0
count_string = self.parser.getAttribute(node, 'gravityNodes')
if count_string:
current_score = int(count_string)
new_score = (current_score + add_to_count)
self.parser.setAttribute(node, 'gravityNodes', str(new_score))
|
'Checks the density of links within a node, if there is a high
link to text ratio, then the text is less likely to be relevant'
| def is_highlink_density(self, e):
| links = self.parser.getElementsByTag(e, tag='a')
if (not links):
return False
text = self.parser.getText(e)
words = [word for word in text.split() if word.isalnum()]
if (not words):
return True
words_number = float(len(words))
sb = []
for link in links:
sb.append(... |
'Returns the gravityScore as an integer from this node'
| def get_score(self, node):
| return (self.get_node_gravity_score(node) or 0)
|
'Returns a list of nodes we want to search
on like paragraphs and tables'
| def nodes_to_check(self, doc):
| nodes_to_check = []
for tag in ['p', 'pre', 'td']:
items = self.parser.getElementsByTag(doc, tag=tag)
nodes_to_check += items
return nodes_to_check
|
'Remove any divs that looks like non-content, clusters of links,
or paras with no gusto; add adjacent nodes which look contenty'
| def post_cleanup(self, top_node):
| node = self.add_siblings(top_node)
for e in self.parser.getChildren(node):
e_tag = self.parser.getTag(e)
if (e_tag != 'p'):
if self.is_highlink_density(e):
self.parser.remove(e)
return node
|
'The **kwargs argument may be filled with config values, which
is added into the config object'
| def __init__(self, url, title='', source_url='', config=None, **kwargs):
| self.config = (config or Configuration())
self.config = extend_config(self.config, kwargs)
self.extractor = ContentExtractor(self.config)
if (source_url == ''):
scheme = urls.get_scheme(url)
if (scheme is None):
scheme = 'http'
source_url = ((scheme + '://') + urls.ge... |
'Build a lone article from a URL independent of the source (newspaper).
Don\'t normally call this method b/c it\'s good to multithread articles
on a source (newspaper) level.'
| def build(self):
| self.download()
self.parse()
self.nlp()
|
'Downloads the link\'s HTML content, don\'t use if you are batch async
downloading articles
recursion_counter (currently 1) stops refreshes that are potentially
infinite'
| def download(self, input_html=None, title=None, recursion_counter=0):
| if (input_html is None):
try:
html = network.get_html_2XX_only(self.url, self.config)
except requests.exceptions.RequestException as e:
self.download_state = ArticleDownloadState.FAILED_RESPONSE
self.download_exception_msg = str(e)
log.debug(('Download... |
'Performs a check on the url of this link to determine if article
is a real news article or not'
| def is_valid_url(self):
| return urls.valid_url(self.url)
|
'If the article\'s body text is long enough to meet
standard article requirements, keep the article'
| def is_valid_body(self):
| if (not self.is_parsed):
raise ArticleException("must parse article before checking if it's body is valid!")
meta_type = self.extract... |
'If the article is related heavily to media:
gallery, video, big pictures, etc'
| def is_media_news(self):
| safe_urls = ['/video', '/slide', '/gallery', '/powerpoint', '/fashion', '/glamour', '/cloth']
for s in safe_urls:
if (s in self.url):
return True
return False
|
'Keyword extraction wrapper'
| def nlp(self):
| self.throw_if_not_downloaded_verbose()
self.throw_if_not_parsed_verbose()
text_keyws = list(nlp.keywords(self.text).keys())
title_keyws = list(nlp.keywords(self.title).keys())
keyws = list(set((title_keyws + text_keyws)))
self.set_keywords(keyws)
max_sents = self.config.MAX_SUMMARY_SENT
... |
'A parse candidate is a wrapper object holding a link hash of this
article and a final_url of the article'
| def get_parse_candidate(self):
| if self.html:
return RawHelper.get_parsing_candidate(self.url, self.html)
return URLHelper.get_parsing_candidate(self.url)
|
'Must be called after computing HTML/final URL'
| def build_resource_path(self):
| res_path = self.get_resource_path()
if (not os.path.exists(res_path)):
os.mkdir(res_path)
|
'Every article object has a special directory to store data in from
initialization to garbage collection'
| def get_resource_path(self):
| res_dir_fn = 'article_resources'
resource_directory = os.path.join(settings.TOP_DIRECTORY, res_dir_fn)
if (not os.path.exists(resource_directory)):
os.mkdir(resource_directory)
dir_path = os.path.join(resource_directory, ('%s_' % self.link_hash))
return dir_path
|
'Wrapper for setting images. Queries known image attributes
first, then uses Reddit\'s image algorithm as a fallback.'
| def set_reddit_top_img(self):
| try:
s = images.Scraper(self)
self.set_top_img(s.largest_image_url())
except TypeError as e:
if ("Can't convert 'NoneType' object to str implicitly" in e.args[0]):
log.debug(('No pictures found. Top image not set, %s' % e))
elif ... |
'Encode HTML before setting it'
| def set_html(self, html):
| if html:
if isinstance(html, bytes):
html = self.config.get_parser().get_unicode_html(html)
self.html = html
self.download_state = ArticleDownloadState.SUCCESS
|
'Sets the HTML of just the article\'s `top_node`'
| def set_article_html(self, article_html):
| if article_html:
self.article_html = article_html
|
'Provide 2 APIs for images. One at "top_img", "imgs"
and one at "top_image", "images"'
| def set_top_img_no_check(self, src_url):
| self.top_img = src_url
self.top_image = src_url
|
'The motive for this method is the same as above, provide APIs
for both `article.imgs` and `article.images`'
| def set_imgs(self, imgs):
| self.images = imgs
self.imgs = imgs
|
'Keys are stored in list format'
| def set_keywords(self, keywords):
| if (not isinstance(keywords, list)):
raise Exception('Keyword input must be list!')
if keywords:
self.keywords = keywords[:self.config.MAX_KEYWORDS]
|
'Authors are in ["firstName lastName", "firstName lastName"] format'
| def set_authors(self, authors):
| if (not isinstance(authors, list)):
raise Exception('authors input must be list!')
if authors:
self.authors = authors[:self.config.MAX_AUTHORS]
|
'Summary here refers to a paragraph of text from the
title text and body text'
| def set_summary(self, summary):
| self.summary = summary[:self.config.MAX_SUMMARY]
|
'Save langauges in their ISO 2-character form'
| def set_meta_language(self, meta_lang):
| if (meta_lang and (len(meta_lang) >= 2) and (meta_lang in get_available_languages())):
self.meta_lang = meta_lang[:2]
|
'Store the keys in list form'
| def set_meta_keywords(self, meta_keywords):
| self.meta_keywords = [k.strip() for k in meta_keywords.split(',')]
|
'Trim video objects into just urls'
| def set_movies(self, movie_objects):
| movie_urls = [o.src for o in movie_objects if (o and o.src)]
self.movies = movie_urls
|
'Parse ArticleDownloadState -> log readable status
-> maybe throw ArticleException'
| def throw_if_not_downloaded_verbose(self):
| if (self.download_state == ArticleDownloadState.NOT_STARTED):
print 'You must `download()` an article first!'
raise ArticleException()
elif (self.download_state == ArticleDownloadState.FAILED_RESPONSE):
print ('Article `download()` failed with %s on URL ... |
'Parse `is_parsed` status -> log readable status
-> maybe throw ArticleException'
| def throw_if_not_parsed_verbose(self):
| if (not self.is_parsed):
print 'You must `parse()` an article first!'
raise ArticleException()
|
'Test that data and keys of edges are preserved on consequent
write and reads'
| def test_preserve_multi_edge_data(self):
| G = nx.MultiGraph()
G.add_node(1)
G.add_node(2)
G.add_edges_from([(1, 2), (1, 2, dict(key='data_key1')), (1, 2, dict(id='data_id2')), (1, 2, dict(key='data_key3', id='data_id3')), (1, 2, 103, dict(key='data_key4')), (1, 2, 104, dict(id='data_id5')), (1, 2, 105, dict(key='data_key6', id='data_id7'))])
... |
'Writing keys as edge id attributes means keys become strings.
The original keys are stored as data, so read them back in
if `make_str(key) == edge_id`
This allows the adjacency to remain the same.'
| def test_more_multigraph_keys(self):
| G = nx.MultiGraph()
G.add_edges_from([('a', 'b', 2), ('a', 'b', 3)])
(fd, fname) = tempfile.mkstemp()
self.writer(G, fname)
H = nx.read_graphml(fname)
assert_true(H.is_multigraph())
assert_edges_equal(G.edges(keys=True), H.edges(keys=True))
assert_equal(G._adj, H._adj)
os.close(fd)
... |
'Infer the attribute type of data named name. Currently this only
supports inference of numeric types.
If self.infer_numeric_types is false, type is used. Otherwise, pick the
most general of types found across all values with name and scope. This
means edges with data named \'weight\' are treated separately from nodes
... | def attr_type(self, name, scope, value):
| if self.infer_numeric_types:
types = self.attribute_types[(name, scope)]
try:
chr(12345)
local_long = int
local_unicode = str
except ValueError:
local_long = long
local_unicode = unicode
if (len(types) > 1):
if (... |
'Make a data element for an edge or a node. Keep a log of the
type in the keys table.'
| def add_data(self, name, element_type, value, scope='all', default=None):
| if (element_type not in self.xml_type):
msg = 'GraphML writer does not support %s as data values.'
raise nx.NetworkXError((msg % element_type))
keyid = self.get_key(name, self.xml_type[element_type], scope, default)
data_element = self.myElement('data', key=keyid)
... |
'Appends attribute data to edges or nodes, and stores type information
to be added later. See add_graph_element.'
| def add_attributes(self, scope, xml_obj, data, default):
| for (k, v) in data.items():
self.attribute_types[(make_str(k), scope)].add(type(v))
self.attributes[xml_obj].append([k, v, scope, default.get(k)])
|
'Serialize graph G in GraphML to the stream.'
| def add_graph_element(self, G):
| if G.is_directed():
default_edge_type = 'directed'
else:
default_edge_type = 'undirected'
graphid = G.graph.pop('id', None)
if (graphid is None):
graph_element = self.myElement('graph', edgedefault=default_edge_type)
else:
graph_element = self.myElement('graph', edged... |
'Add many graphs to this GraphML document.'
| def add_graphs(self, graph_list):
| for G in graph_list:
self.add_graph_element(G)
|
'Serialize graph G in GraphML to the stream.'
| def add_graph_element(self, G):
| if G.is_directed():
default_edge_type = 'directed'
else:
default_edge_type = 'undirected'
graphid = G.graph.pop('id', None)
if (graphid is None):
graph_element = self._xml.element('graph', edgedefault=default_edge_type)
else:
graph_element = self._xml.element('graph',... |
'Appends attribute data.'
| def add_attributes(self, scope, xml_obj, data, default):
| for (k, v) in data.items():
data_element = self.add_data(make_str(k), self.attr_type(make_str(k), scope, v), make_str(v), scope, default.get(k))
xml_obj.append(data_element)
|
'Add a node to the graph.'
| def add_node(self, G, node_xml, graphml_keys):
| ports = node_xml.find(('{%s}port' % self.NS_GRAPHML))
if (ports is not None):
warnings.warn('GraphML port tag not supported.')
node_id = self.node_type(node_xml.get('id'))
data = self.decode_data_elements(graphml_keys, node_xml)
G.add_node(node_id, **data)
|
'Add an edge to the graph.'
| def add_edge(self, G, edge_element, graphml_keys):
| ports = edge_element.find(('{%s}port' % self.NS_GRAPHML))
if (ports is not None):
warnings.warn('GraphML port tag not supported.')
directed = edge_element.get('directed')
if (G.is_directed() and (directed == 'false')):
msg = 'directed=false edge found in directed ... |
'Use the key information to decode the data XML if present.'
| def decode_data_elements(self, graphml_keys, obj_xml):
| data = {}
for data_element in obj_xml.findall(('{%s}data' % self.NS_GRAPHML)):
key = data_element.get('key')
try:
data_name = graphml_keys[key]['name']
data_type = graphml_keys[key]['type']
except KeyError:
raise nx.NetworkXError(('Bad GraphML da... |
'Extracts all the keys and key defaults from the xml.'
| def find_graphml_keys(self, graph_element):
| graphml_keys = {}
graphml_key_defaults = {}
for k in graph_element.findall(('{%s}key' % self.NS_GRAPHML)):
attr_id = k.get('id')
attr_type = k.get('attr.type')
attr_name = k.get('attr.name')
yfiles_type = k.get('yfiles.type')
if (yfiles_type is not None):
... |
'Returns True if and only if an arbitrary remaining node can
potentially be joined with some other remaining node.'
| def suitable_edge(self):
| nodes = iter(self.remaining_degree)
u = next(nodes)
return any(((v not in self.graph[u]) for v in nodes))
|
'Tests that the balanced tree with branching factor one is the
path graph.'
| def test_balanced_tree_path(self):
| T = balanced_tree(1, 4)
P = path_graph(5)
assert_true(is_isomorphic(T, P))
|
'Tests that the complete 0-partite graph is the null graph.'
| def test_complete_0_partite_graph(self):
| G = nx.complete_multipartite_graph()
H = nx.null_graph()
assert_nodes_equal(G, H)
assert_edges_equal(G.edges(), H.edges())
|
'Tests that the complete 1-partite graph is the empty graph.'
| def test_complete_1_partite_graph(self):
| G = nx.complete_multipartite_graph(3)
H = nx.empty_graph(3)
assert_nodes_equal(G, H)
assert_edges_equal(G.edges(), H.edges())
|
'Tests that the complete 2-partite graph is the complete bipartite
graph.'
| def test_complete_2_partite_graph(self):
| G = nx.complete_multipartite_graph(2, 3)
H = nx.complete_bipartite_graph(2, 3)
assert_nodes_equal(G, H)
assert_edges_equal(G.edges(), H.edges())
|
'Tests for generating the complete multipartite graph.'
| def test_complete_multipartite_graph(self):
| G = nx.complete_multipartite_graph(2, 3, 4)
blocks = [(0, 1), (2, 3, 4), (5, 6, 7, 8)]
for block in blocks:
for (u, v) in itertools.combinations_with_replacement(block, 2):
assert_true((v not in G[u]))
assert_equal(G.node[u], G.node[v])
for (block1, block2) in itertools.c... |
'Tests that the extended BA random graph generated behaves consistenly.
Tests the exceptions are raised as expected.
The graphs generation are repeated several times to prevent lucky-shots'
| def test_extended_barabasi_albert(self, m=2):
| seed = 42
repeats = 2
BA_model = barabasi_albert_graph(100, m, seed)
BA_model_edges = BA_model.number_of_edges()
while repeats:
repeats -= 1
G1 = extended_barabasi_albert_graph(100, m, 0, 0, seed)
assert_equal(G1.size(), BA_model_edges)
G1 = extended_barabasi_albert_g... |
'Tests that a 0-regular graph has the correct number of nodes and
edges.'
| def test_random_zero_regular_graph(self):
| seed = 42
G = random_regular_graph(0, 10)
assert_equal(len(G), 10)
assert_equal(sum((1 for _ in G.edges())), 0)
|
'Tests that pairs of vertices adjacent if and only if they are
within the prescribed radius.'
| def test_distances(self):
| dist = euclidean
G = nx.random_geometric_graph(50, 0.25)
for (u, v) in combinations(G, 2):
if (v in G[u]):
assert_true((dist(G.node[u]['pos'], G.node[v]['pos']) <= 0.25))
else:
assert_false((dist(G.node[u]['pos'], G.node[v]['pos']) <= 0.25))
|
'Tests for providing an alternate distance metric to the
generator.'
| def test_p(self):
| dist = l1dist
G = nx.random_geometric_graph(50, 0.25, p=1)
for (u, v) in combinations(G, 2):
if (v in G[u]):
assert_true((dist(G.node[u]['pos'], G.node[v]['pos']) <= 0.25))
else:
assert_false((dist(G.node[u]['pos'], G.node[v]['pos']) <= 0.25))
|
'Tests using values other than sequential numbers as node IDs.'
| def test_node_names(self):
| import string
nodes = list(string.ascii_lowercase)
G = nx.random_geometric_graph(nodes, 0.25)
assert_equal(len(G), len(nodes))
dist = euclidean
for (u, v) in combinations(G, 2):
if (v in G[u]):
assert_true((dist(G.node[u]['pos'], G.node[v]['pos']) <= 0.25))
else:
... |
'Tests that pairs of vertices adjacent if and only if their
distances meet the given threshold.'
| def test_distances(self):
| dist = euclidean
G = nx.geographical_threshold_graph(50, 100)
for (u, v) in combinations(G, 2):
if (v in G[u]):
assert_true(join(G, u, v, 100, 2, dist))
else:
assert_false(join(G, u, v, 100, 2, dist))
|
'Tests for providing an alternate distance metric to the
generator.'
| def test_metric(self):
| dist = l1dist
G = nx.geographical_threshold_graph(50, 100, metric=dist)
for (u, v) in combinations(G, 2):
if (v in G[u]):
assert_true(join(G, u, v, 100, 2, dist))
else:
assert_false(join(G, u, v, 100, 2, dist))
|
'Tests for providing an alternate distance metric to the
generator.'
| def test_metric(self):
| dist = l1dist
G = nx.waxman_graph(50, 0.5, 0.1, metric=dist)
assert_equal(len(G), 50)
|
'Tests for an in-place reweighting of the edges of the graph.'
| def test_in_place(self):
| G = nx.DiGraph()
G.add_edge(0, 1, weight=1)
G.add_edge(0, 2, weight=1)
nx.stochastic_graph(G, copy=False)
assert_equal(sorted(G.edges(data=True)), [(0, 1, {'weight': 0.5}), (0, 2, {'weight': 0.5})])
|
'Tests that an empty degree sequence yields the null graph.'
| def test_empty_degree_sequence(self):
| G = nx.configuration_model([])
assert_equal(len(G), 0)
|
'Tests that a degree sequence of all zeros yields the empty
graph.'
| def test_degree_zero(self):
| G = nx.configuration_model([0, 0, 0])
assert_equal(len(G), 3)
assert_equal(G.number_of_edges(), 0)
|
'Tests that the degree sequence of the generated graph matches
the input degree sequence.'
| def test_degree_sequence(self):
| deg_seq = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
G = nx.configuration_model(deg_seq, seed=12345678)
assert_equal(sorted((d for (n, d) in G.degree()), reverse=True), [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1])
assert_equal(sorted((d for (n, d) in G.degree(range(len(deg_seq)))), reverse=True), [5, 3, 3, 3, 3, 2, 2, 2, ... |
'Tests that each call with the same random seed generates the
same graph.'
| def test_random_seed(self):
| deg_seq = ([3] * 12)
G1 = nx.configuration_model(deg_seq, seed=1000)
G2 = nx.configuration_model(deg_seq, seed=1000)
assert_true(nx.is_isomorphic(G1, G2))
G1 = nx.configuration_model(deg_seq, seed=10)
G2 = nx.configuration_model(deg_seq, seed=10)
assert_true(nx.is_isomorphic(G1, G2))
|
'Tests that attempting to create a configuration model graph
using a directed graph yields an exception.'
| @raises(nx.NetworkXNotImplemented)
def test_directed_disallowed(self):
| nx.configuration_model([], create_using=nx.DiGraph())
|
'Tests that a degree sequence whose sum is odd yields an
exception.'
| @raises(nx.NetworkXError)
def test_odd_degree_sum(self):
| nx.configuration_model([1, 2])
|
'grid_graph([n,m]) is a connected simple graph with the
following properties:
number_of_nodes = n*m
degree_histogram = [0,0,4,2*(n+m)-8,(n-2)*(m-2)]'
| def test_grid_graph(self):
| for (n, m) in [(3, 5), (5, 3), (4, 5), (5, 4)]:
dim = [n, m]
g = nx.grid_graph(dim)
assert_equal(len(g), (n * m))
assert_equal(nx.degree_histogram(g), [0, 0, 4, ((2 * (n + m)) - 8), ((n - 2) * (m - 2))])
for (n, m) in [(1, 5), (5, 1)]:
dim = [n, m]
g = nx.grid_gra... |
'Tests that the graph is really a triangular lattice.'
| def test_lattice_points(self):
| for (m, n) in [(2, 3), (2, 2), (2, 1), (3, 3), (3, 2), (3, 4)]:
G = nx.triangular_lattice_graph(m, n)
N = ((n + 1) // 2)
assert_equal(len(G), (((m + 1) * (1 + N)) - ((n % 2) * ((m + 1) // 2))))
for (i, j) in G.nodes():
nbrs = G[(i, j)]
if (i < N):
assert_true(... |
'Tests for creating a directed triangular lattice.'
| def test_directed(self):
| G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
H = nx.triangular_lattice_graph(3, 4, create_using=nx.DiGraph())
assert_true(H.is_directed())
for (u, v) in H.edges():
assert_true((v[1] >= u[1]))
if (v[1] == u[1]):
assert_true((v[0] > u[0]))
|
'Tests for creating a triangular lattice multigraph.'
| def test_multigraph(self):
| G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
H = nx.triangular_lattice_graph(3, 4, create_using=nx.MultiGraph())
assert_equal(list(H.edges()), list(G.edges()))
|
'Tests that the graph is really a hexagonal lattice.'
| def test_lattice_points(self):
| for (m, n) in [(4, 5), (4, 4), (4, 3), (3, 2), (3, 3), (3, 5)]:
G = nx.hexagonal_lattice_graph(m, n)
assert_equal(len(G), (((2 * (m + 1)) * (n + 1)) - 2))
C_6 = nx.cycle_graph(6)
hexagons = [[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)], [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)], [... |
'Tests for creating a directed hexagonal lattice.'
| def test_directed(self):
| G = nx.hexagonal_lattice_graph(3, 5, create_using=nx.Graph())
H = nx.hexagonal_lattice_graph(3, 5, create_using=nx.DiGraph())
assert_true(H.is_directed())
pos = nx.get_node_attributes(H, 'pos')
for (u, v) in H.edges():
assert_true((pos[v][1] >= pos[u][1]))
if (pos[v][1] == pos[u][1])... |
'Tests for creating a hexagonal lattice multigraph.'
| def test_multigraph(self):
| G = nx.hexagonal_lattice_graph(3, 5, create_using=nx.Graph())
H = nx.hexagonal_lattice_graph(3, 5, create_using=nx.MultiGraph())
assert_equal(list(H.edges()), list(G.edges()))
|
'Tests that the generated graph is `k`-out-regular.'
| def test_regularity(self):
| n = 10
k = 3
alpha = 1
G = random_k_out_graph(n, k, alpha)
assert_true(all(((d == k) for (v, d) in G.out_degree())))
|
'Tests for forbidding self-loops.'
| def test_no_self_loops(self):
| n = 10
k = 3
alpha = 1
G = random_k_out_graph(n, k, alpha, self_loops=False)
assert_equal(G.number_of_selfloops(), 0)
|
'Tests that the generated graph is `k`-out-regular.'
| def test_regularity(self):
| n = 10
k = 3
G = random_uniform_k_out_graph(n, k)
assert_true(all(((d == k) for (v, d) in G.out_degree())))
|
'Tests for forbidding self-loops.'
| def test_no_self_loops(self):
| n = 10
k = 3
G = random_uniform_k_out_graph(n, k, self_loops=False)
assert_equal(G.number_of_selfloops(), 0)
assert_true(all(((d == k) for (v, d) in G.out_degree())))
|
'Conversion from non-square array.'
| def test_shape(self):
| A = np.array([[1, 2, 3], [4, 5, 6]])
assert_raises(nx.NetworkXError, nx.from_numpy_matrix, A)
|
'Conversion from graph to matrix to graph.'
| def test_identity_graph_matrix(self):
| A = nx.to_numpy_matrix(self.G1)
self.identity_conversion(self.G1, A, nx.Graph())
|
'Conversion from graph to array to graph.'
| def test_identity_graph_array(self):
| A = nx.to_numpy_matrix(self.G1)
A = np.asarray(A)
self.identity_conversion(self.G1, A, nx.Graph())
|
'Conversion from digraph to matrix to digraph.'
| def test_identity_digraph_matrix(self):
| A = nx.to_numpy_matrix(self.G2)
self.identity_conversion(self.G2, A, nx.DiGraph())
|
'Conversion from digraph to array to digraph.'
| def test_identity_digraph_array(self):
| A = nx.to_numpy_matrix(self.G2)
A = np.asarray(A)
self.identity_conversion(self.G2, A, nx.DiGraph())
|
'Conversion from weighted graph to matrix to weighted graph.'
| def test_identity_weighted_graph_matrix(self):
| A = nx.to_numpy_matrix(self.G3)
self.identity_conversion(self.G3, A, nx.Graph())
|
'Conversion from weighted graph to array to weighted graph.'
| def test_identity_weighted_graph_array(self):
| A = nx.to_numpy_matrix(self.G3)
A = np.asarray(A)
self.identity_conversion(self.G3, A, nx.Graph())
|
'Conversion from weighted digraph to matrix to weighted digraph.'
| def test_identity_weighted_digraph_matrix(self):
| A = nx.to_numpy_matrix(self.G4)
self.identity_conversion(self.G4, A, nx.DiGraph())
|
'Conversion from weighted digraph to array to weighted digraph.'
| def test_identity_weighted_digraph_array(self):
| A = nx.to_numpy_matrix(self.G4)
A = np.asarray(A)
self.identity_conversion(self.G4, A, nx.DiGraph())
|
'Conversion from graph to matrix to graph with nodelist.'
| def test_nodelist(self):
| P4 = path_graph(4)
P3 = path_graph(3)
nodelist = list(P3)
A = nx.to_numpy_matrix(P4, nodelist=nodelist)
GA = nx.Graph(A)
self.assert_equal(GA, P3)
nodelist += [nodelist[0]]
assert_raises(nx.NetworkXError, nx.to_numpy_matrix, P3, nodelist=nodelist)
|
'Tests that the :func:`networkx.from_numpy_matrix` function
interprets integer weights as the number of parallel edges when
creating a multigraph.'
| def test_from_numpy_matrix_parallel_edges(self):
| A = np.matrix([[1, 1], [1, 2]])
expected = nx.DiGraph()
edges = [(0, 0), (0, 1), (1, 0)]
expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
expected.add_edge(1, 1, weight=2)
actual = nx.from_numpy_matrix(A, parallel_edges=True, create_using=nx.DiGraph())
assert_graphs_equal(ac... |
'Tests that a symmetric matrix has edges added only once to an
undirected multigraph when using :func:`networkx.from_numpy_matrix`.'
| def test_symmetric(self):
| A = np.matrix([[0, 1], [1, 0]])
G = nx.from_numpy_matrix(A, create_using=nx.MultiGraph())
expected = nx.MultiGraph()
expected.add_edge(0, 1, weight=1)
assert_graphs_equal(G, expected)
|
'Test that setting dtype int actually gives an integer matrix.
For more information, see GitHub pull request #1363.'
| def test_dtype_int_graph(self):
| G = nx.complete_graph(3)
A = nx.to_numpy_matrix(G, dtype=int)
assert_equal(A.dtype, int)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.