logo Netzschleuder network catalog, repository, and centrifuge

History of sister_cities

The changes to the source code of this entry in the repository, newest first, each with the differences it made to the entry's files. They are also listed on GitLab.

[entries] Add the date when each entry was added, and remove icon_hash by Tiago de Paula Peixoto beff7c9
The dates are those of the commits that first added the entries' files
(2020-08-11 for the entries of the initial commit); renamed entries keep
the date of their first name.

Changed: none
diff --git a/entries/sister_cities/__init__.py b/entries/sister_cities/__init__.py
index 7ce5c0d..8c2e211 100644
--- a/entries/sister_cities/__init__.py
+++ b/entries/sister_cities/__init__.py
@@ -52,7 +52,7 @@ url = ['https://www.wikidata.org/wiki/Property:P190',
        'https://archive.org/details/wikibase-wikidatawiki-20171116',
        'https://query.wikidata.org/']
 citation = [('D. Vrandečić, M. Krötzsch, "Wikidata: a free collaborative knowledgebase." Communications of the ACM 57, 78-85 (2014).', 'https://doi.org/10.1145/2629489')]
-icon_hash = None
+date_added = '2026-10-27'
 upstream_license = ('CC0 1.0 (Wikidata)', 'https://www.wikidata.org/wiki/Wikidata:Licensing')
 
 archive_prefix = 'https://archive.org/download/wikibase-wikidatawiki-20171116'
[entries] Prefix the properties in the descriptions with (Node), (Edge) or (Graph) by Tiago de Paula Peixoto bc3dbbd
The lists of properties at the end of the descriptions marked edge
properties with "Edge" but left node properties unmarked, or grouped
them in "Nodes: `a`, ...; `b`, ..." items, so the kind of a property
was often unclear. Every item now starts with (Node), (Edge) or (Graph),
followed by the property names, a colon and the explanation, one item
per property or group of properties; qualifications (kinds of nodes,
networks) follow the names in parentheses. Properties that were only
named got a short explanation, and a few items that named the wrong
kind of property were corrected.
diff --git a/entries/sister_cities/__init__.py b/entries/sister_cities/__init__.py
index 43b13a4..7ce5c0d 100644
--- a/entries/sister_cities/__init__.py
+++ b/entries/sister_cities/__init__.py
@@ -42,11 +42,11 @@ There are two networks:
 
 The networks have the following properties:
 
-- `wikidata_id`: the Wikidata identifier of the item (e.g. `Q64` for Berlin).
-- `name`: the English label of the item (empty if it has none).
-- `is_city`: whether the item is an instance of "human settlement" or of one of its subclasses.
-- `latitude`, `longitude`: the coordinates of the item (property P625; NaN if it has none, or only coordinates on another celestial body); if it has several, one of them.
-- `country`: the English labels of the countries the item belongs to (property P17), separated by semicolons (empty if none)."""
+- (Node) `wikidata_id`: the Wikidata identifier of the item (e.g. `Q64` for Berlin).
+- (Node) `name`: the English label of the item (empty if it has none).
+- (Node) `is_city`: whether the item is an instance of "human settlement" or of one of its subclasses.
+- (Node) `latitude`, `longitude`: the coordinates of the item (property P625; NaN if it has none, or only coordinates on another celestial body); if it has several, one of them.
+- (Node) `country`: the English labels of the countries the item belongs to (property P17), separated by semicolons (empty if none)."""
 tags = ['Social', 'Offline', 'Relationships', 'Unweighted', 'Metadata']
 url = ['https://www.wikidata.org/wiki/Property:P190',
        'https://archive.org/details/wikibase-wikidatawiki-20171116',
[entries] Move contact, convote_mentions, douban, email_company, epinions, flixster, football_league_results, hyves, lastfm, libimseti, livemocha, reuters, sa_companies, sister_cities, tripadvisor_ratings, wikilens_ratings and wikipedia_discussions_de to their original sources by Tiago de Paula Peixoto 8f097de
These entries downloaded KONECT's copies of the data. They now download
the original data (live, from pinned Wayback Machine snapshots, or by
re-extracting from public dumps), gaining the metadata KONECT dropped
(names, identifiers, timestamps, attributes), with descriptions and
citations rewritten from the original sources and factual errors fixed
(years and periods of contact, email_company, douban, flixster,
libimseti, sa_companies; the rated objects of epinions; the sign of
convote_mentions; songs merged by title alone in lastfm).

New networks: the trust network of epinions, the links of
wikilens_ratings, the JSON crawl of tripadvisor_ratings, and current
versions of sister_cities and wikipedia_discussions_de next to the ones
KONECT used. asu_social_networks only loses its mention of KONECT.

Changed: upstream contact convote_mentions douban email_company epinions flixster football_league_results hyves lastfm libimseti livemocha reuters sa_companies sister_cities tripadvisor_ratings wikilens_ratings wikipedia_discussions_de
diff --git a/entries/sister_cities/__init__.py b/entries/sister_cities/__init__.py
index 28a72c9..43b13a4 100644
--- a/entries/sister_cities/__init__.py
+++ b/entries/sister_cities/__init__.py
@@ -16,39 +16,311 @@
 # You should have received a copy of the GNU Affero General Public License along
 # with this program.  If not, see <http://www.gnu.org/licenses/>.
 
+import array
+import bz2
+import csv
+import io
+import os
+import re
+import tempfile
+import urllib.parse
 
+import numpy
 
 from .. import *
 
 
-title = 'Sister cities (Wikidata, 2017)'
-description = """An undirected network of cities and other administrative areas of the world connected by "sister city" (or "twin city") relationships, as extracted from Wikidata by KONECT in October 2017. Each node is a city (or another administrative body), and an edge connects two cities that are twinned. The data identify the cities only by indices; their names are not included."""
-tags = ['Social', 'Offline', 'Relationships', 'Unweighted']
-url = 'http://konect.cc/networks/twin'
-citation = [('J. Kunegis, "Sister cities network dataset." KONECT, the Koblenz Network Collection (2017)', 'http://konect.cc/networks/twin'),
-            ('J. Kunegis, "KONECT -- The Koblenz Network Collection." Proceedings of the 22nd International Conference on World Wide Web Companion, 1343-1350 (2013)', 'https://doi.org/10.1145/2487788.2488173')]
+title = 'Sister cities (Wikidata)'
+description = """Directed networks of cities and other places of the world connected by "sister city" (twin town) relationships, as recorded in Wikidata with the property "twinned administrative body" (P190). Each node is a Wikidata item, and a directed edge from A to B means that the item of A lists B as twinned with it. The relationship is symmetric in reality, but it is not always recorded on both items, so that a pair of twinned places can be connected by edges in one or both directions.
+
+Only the statements of items that are instances of "human settlement" (Q486972) or of any of its subclasses (property paths P31/P279*) are included, i.e. the edges whose source is such an item; their targets may be other kinds of places (e.g. regions or districts that have twin towns), which are marked by the property `is_city`. Only the preferred (or, if there is none, the normal) statements are used ("truthy" statements), and statements whose value is "unknown" are left out.
+
+There are two networks:
+
+- `2017`: from the Wikidata dump of "truthy" statements of 16 November 2017 (the class hierarchy of that time is used for the selection).
+- `2026`: from the Wikidata Query Service, reflecting the state of Wikidata at the time of download (October 2026).
+
+The networks have the following properties:
+
+- `wikidata_id`: the Wikidata identifier of the item (e.g. `Q64` for Berlin).
+- `name`: the English label of the item (empty if it has none).
+- `is_city`: whether the item is an instance of "human settlement" or of one of its subclasses.
+- `latitude`, `longitude`: the coordinates of the item (property P625; NaN if it has none, or only coordinates on another celestial body); if it has several, one of them.
+- `country`: the English labels of the countries the item belongs to (property P17), separated by semicolons (empty if none)."""
+tags = ['Social', 'Offline', 'Relationships', 'Unweighted', 'Metadata']
+url = ['https://www.wikidata.org/wiki/Property:P190',
+       'https://archive.org/details/wikibase-wikidatawiki-20171116',
+       'https://query.wikidata.org/']
+citation = [('D. Vrandečić, M. Krötzsch, "Wikidata: a free collaborative knowledgebase." Communications of the ACM 57, 78-85 (2014).', 'https://doi.org/10.1145/2629489')]
 icon_hash = None
 upstream_license = ('CC0 1.0 (Wikidata)', 'https://www.wikidata.org/wiki/Wikidata:Licensing')
-upstream_prefix = 'http://konect.cc/files'
-files = [('download.tsv.twin.tar.bz2', None, 'konect')]
 
-def postprocess(alt, g):
-    pass
+archive_prefix = 'https://archive.org/download/wikibase-wikidatawiki-20171116'
+files_2017 = [('wikidata-20171116-truthy-BETA.nt.bz2', '2017', None)]
+# Results of the queries to the Wikidata Query Service (see fetch_sparql())
+SPARQL_EDGES = 'sparql_edges.csv'
+SPARQL_NODES = 'sparql_nodes.csv'
+files_2026 = [((SPARQL_EDGES, SPARQL_NODES), '2026', None)]
+files = files_2017 + files_2026
+
+SPARQL_URL = 'https://query.wikidata.org/sparql'
+# The class of human settlements
+SETTLEMENT = 486972
+# Evaluated in the order written (optimizer off): the P190 statements first,
+# then the class of their subjects; the automatic order times out
+EDGE_QUERY = """SELECT DISTINCT ?city ?sister WHERE {
+  hint:Query hint:optimizer "None" .
+  ?city wdt:P190 ?sister .
+  ?city wdt:P31/wdt:P279* wd:Q486972 .
+}"""
+NODE_QUERY = """SELECT ?item ?label ?coord ?country ?countryLabel ?isCity WHERE {
+  VALUES ?item { %s }
+  OPTIONAL { ?item rdfs:label ?label FILTER(LANG(?label) = "en") }
+  OPTIONAL { ?item wdt:P625 ?coord }
+  OPTIONAL { ?item wdt:P17 ?country .
+             OPTIONAL { ?country rdfs:label ?countryLabel FILTER(LANG(?countryLabel) = "en") } }
+  BIND(EXISTS { ?item wdt:P31/wdt:P279* wd:Q486972 } AS ?isCity)
+}"""
+NODE_BATCH = 2000
+ENTITY = "http://www.wikidata.org/entity/"
+
+def sparql(query):
+    "The CSV result of a query to the Wikidata Query Service, as rows."
+    data = urllib.parse.urlencode({"query": query}).encode()
+    def run():
+        with open_url(SPARQL_URL, headers={"Accept": "text/csv"},
+                      data=data, timeout=300) as f:
+            return f.read()
+    text = retry_download(run, tries=4).decode("utf8")
+    # A query that times out while the results are sent ends with an error
+    # message instead of failing
+    if not text.endswith("\r\n") or "TimeoutException" in text[-2000:]:
+        raise RuntimeError("incomplete result of query to the Wikidata Query Service")
+    rows = list(csv.reader(io.StringIO(text)))
+    for r in rows[1:]:
+        if len(r) != len(rows[0]) or not r[0].startswith(ENTITY + "Q"):
+            raise RuntimeError(f"unexpected row in the result of a query: {r}")
+    return rows[0], rows[1:]
+
+def fetch_sparql(name, force=False):
+    import process_entry
+    if process_entry._check_health:
+        sparql("SELECT ?x WHERE { wd:Q64 wdt:P190 ?x } LIMIT 1")
+        return
+    if not force:
+        try:
+            with open_upstream_file(name, SPARQL_NODES, "rb"):
+                return
+        except (FileNotFoundError, IOError):
+            pass
+    header, edges = sparql(EDGE_QUERY)
+    if header != ["city", "sister"] or len(edges) == 0:
+        raise RuntimeError(f"unexpected result of the edge query: {header}")
+    items = sorted({x for e in edges for x in e},
+                   key=lambda x: int(x.removeprefix(ENTITY + "Q")))
+    nodes = []
+    for i in range(0, len(items), NODE_BATCH):
+        vals = " ".join("wd:" + x.removeprefix(ENTITY)
+                        for x in items[i:i + NODE_BATCH])
+        nheader, rows = sparql(NODE_QUERY % vals)
+        nodes.extend(rows)
+    got = {r[0] for r in nodes}
+    if got != set(items):
+        raise RuntimeError(f"node query incomplete: {len(set(items) - got)} items missing")
+    for fname, header, rows in [(SPARQL_EDGES, header, edges),
+                                (SPARQL_NODES, nheader, nodes)]:
+        with open_upstream_file(name, fname, "wb") as output:
+            with io.TextIOWrapper(output, "utf8", newline="") as f:
+                w = csv.writer(f)
+                w.writerow(header)
+                w.writerows(rows)
 
 def fetch_upstream(force=False):
-    return fetch_upstream_files(__name__.split(".")[-1], upstream_prefix, files,
-                                force)
+    name = __name__.split(".")[-1]
+    retry_download(fetch_upstream_files, name, archive_prefix, files_2017,
+                   force)
+    fetch_sparql(name, force)
+
+# For checks only: if set, only (about) this many P190 statements are read
+# per network
+_check_rows = None
+
+re_point = re.compile(r'^Point\(([-+0-9.eE]+) ([-+0-9.eE]+)\)$')
+
+def make_graph(edges, nodes):
+    """Graph from the directed edges (pairs of numeric Q-ids) and the node
+    attributes: a dict Q-id -> (name, is_city, (lon, lat) or None, list of
+    country names)."""
+    ids = sorted({x for e in edges for x in e})
+    idx = {x: i for i, x in enumerate(ids)}
+    g = Graph(directed=True)
+    g.add_vertex(len(ids))
+    g.add_edge_list([(idx[s], idx[t]) for s, t in edges])
+    g.vp.wikidata_id = g.new_vp("string", vals=[f"Q{x}" for x in ids])
+    g.vp.name = g.new_vp("string", vals=[nodes[x][0] for x in ids])
+    g.vp.is_city = g.new_vp("bool", vals=[nodes[x][1] for x in ids])
+    lon = [nodes[x][2][0] if nodes[x][2] else numpy.nan for x in ids]
+    lat = [nodes[x][2][1] if nodes[x][2] else numpy.nan for x in ids]
+    g.vp.latitude = g.new_vp("double", vals=lat)
+    g.vp.longitude = g.new_vp("double", vals=lon)
+    g.vp.country = g.new_vp("string", vals=["; ".join(nodes[x][3]) for x in ids])
+    return g
+
+def parse_sparql(fe, fn):
+    "Network from the results of the queries (text files)."
+    edges = []
+    for i, (s, t) in enumerate(csv.reader(fe)):
+        if i == 0:
+            continue
+        if _check_rows is not None and len(edges) >= _check_rows:
+            break
+        edges.append((int(s.removeprefix(ENTITY + "Q")),
+                      int(t.removeprefix(ENTITY + "Q"))))
+    nodes = {}
+    for i, (item, label, coord, country, clabel, is_city) in enumerate(csv.reader(fn)):
+        if i == 0:
+            continue
+        x = int(item.removeprefix(ENTITY + "Q"))
+        if x not in nodes:
+            nodes[x] = [label, is_city == "true", None, []]
+        m = re_point.match(coord)
+        if m is not None and nodes[x][2] is None:
+            nodes[x][2] = (float(m.group(1)), float(m.group(2)))
+        if country:
+            c = clabel or country.removeprefix(ENTITY)
+            if c not in nodes[x][3]:
+                nodes[x][3].append(c)
+    # nodes missing from the attributes (only when reading a part, for checks)
+    for e in edges:
+        for x in e:
+            nodes.setdefault(x, ["", False, None, []])
+    return make_graph(edges, nodes)
+
+# The 2017 dump (N-Triples, grouped by subject), read in chunks with regular
+# expressions
+_E = rb"<http://www\.wikidata\.org/entity/Q(\d+)>"
+re_claim = re.compile(_E + rb" <http://www\.wikidata\.org/prop/direct/(P31|P279|P190|P17|P625)> ([^\n]*) \.\n")
+re_label = re.compile(_E + rb' <http://www\.w3\.org/2000/01/rdf-schema#label> "([^\n]*)"@en \.\n')
+re_item = re.compile(rb"^<http://www\.wikidata\.org/entity/Q(\d+)>$")
+re_wkt = re.compile(rb'^"Point\(([-+0-9.eE]+) ([-+0-9.eE]+)\)"\^\^')
+re_escape = re.compile(r'\\(u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}|.)')
+_ESC = {"t": "\t", "b": "\b", "n": "\n", "r": "\r", "f": "\f"}
+
+def nt_unescape(s):
+    "Decode an N-Triples string literal (UTF-8 bytes, without quotes)."
+    s = s.decode("utf8", errors="replace")
+    if "\\" not in s:
+        return s
+    def sub(m):
+        c = m.group(1)
+        if c[0] in "uU" and len(c) > 1:
+            return chr(int(c[1:], 16))
+        return _ESC.get(c, c)
+    return re_escape.sub(sub, s)
+
+def parse_truthy(f):
+    """Network from the decompressed Wikidata truthy N-Triples dump `f`, read
+    once: the P31, P279, P190, P17 and P625 statements are kept in memory, and
+    the English labels written to a temporary file, read again at the end for
+    the nodes and their countries."""
+    claims = {p: (array.array("i"), array.array("i"))
+              for p in (b"P31", b"P279", b"P190", b"P17")}
+    c_id = array.array("i")
+    c_lon = array.array("d")
+    c_lat = array.array("d")
+    os.makedirs("cache/temp", exist_ok=True)
+    with tempfile.TemporaryFile(dir="cache/temp") as tmp:
+        rest = b""
+        while True:
+            buf = f.read(1 << 24)
+            if not buf:
+                break
+            buf = rest + buf
+            i = buf.rfind(b"\n") + 1
+            buf, rest = buf[:i], buf[i:]
+            for s, p, o in re_claim.findall(buf):
+                if p == b"P625":
+                    m = re_wkt.match(o)
+                    if m is not None:     # (only coordinates on Earth)
+                        c_id.append(int(s))
+                        c_lon.append(float(m.group(1)))
+                        c_lat.append(float(m.group(2)))
+                    continue
+                m = re_item.match(o)
+                if m is None:             # unknown value (blank node)
+                    continue
+                cs, co = claims[p]
+                cs.append(int(s))
+                co.append(int(m.group(1)))
+            tmp.write(b"".join(b"%s\t%s\n" % x for x in re_label.findall(buf)))
+            if (_check_rows is not None and
+                len(claims[b"P190"][0]) >= _check_rows):
+                break
+
+        def pairs(p):
+            return (numpy.frombuffer(claims[p][0], dtype="int32"),
+                    numpy.frombuffer(claims[p][1], dtype="int32"))
+
+        # the subclasses of human settlement
+        sub, sup = pairs(b"P279")
+        children = {}
+        for a, b in zip(sub.tolist(), sup.tolist()):
+            children.setdefault(b, []).append(a)
+        classes = {SETTLEMENT}
+        stack = [SETTLEMENT]
+        while stack:
+            for a in children.get(stack.pop(), []):
+                if a not in classes:
+                    classes.add(a)
+                    stack.append(a)
+        del children, sub, sup
+        classes = numpy.array(sorted(classes), dtype="int32")
+
+        s31, o31 = pairs(b"P31")
+        cities = set(s31[numpy.isin(o31, classes)].tolist())
+        del s31, o31, claims[b"P31"], claims[b"P279"]
+
+        s190, o190 = pairs(b"P190")
+        edges = sorted({(s, t) for s, t in zip(s190.tolist(), o190.tolist())
+                        if s in cities})
+        nodes = {x: ["", x in cities, None, []] for e in edges for x in e}
+
+        s17, o17 = pairs(b"P17")
+        sel = numpy.isin(s17, numpy.array(sorted(nodes), dtype="int32"))
+        countries = {}
+        for s, c in zip(s17[sel].tolist(), o17[sel].tolist()):
+            if c not in nodes[s][3]:
+                nodes[s][3].append(c)
+            countries[c] = f"Q{c}"
+        for x, lon, lat in zip(c_id, c_lon, c_lat):
+            if x in nodes and nodes[x][2] is None:
+                nodes[x][2] = (lon, lat)
+
+        tmp.seek(0)
+        for line in tmp:
+            q, label = line.rstrip(b"\n").split(b"\t", 1)
+            q = int(q)
+            if q in nodes:
+                nodes[q][0] = nt_unescape(label)
+            if q in countries:
+                countries[q] = nt_unescape(label)
+    for x in nodes.values():
+        x[3] = [countries[c] for c in x[3]]
+    return make_graph(edges, nodes)
 
 @cache_network()
 @coerce_props()
 @annotate()
 def parse(alts=None):
-    global files
     name = __name__.split(".")[-1]
-    for fname, alt, fmt in files:
+    for fnames, alt, fmt in files:
         if alts is not None and alt not in alts:
             continue
-        with open_upstream_file(name, fname, "rb") as f:
-            g = parse_graph([f], fmt, directed=None)
-        postprocess(alt, g)
+        if alt == "2017":
+            with open_upstream_file(name, fnames, "rb") as fs, bz2.open(fs) as f:
+                g = parse_truthy(f)
+        else:
+            with open_upstream_file(name, SPARQL_EDGES, "r") as fe, \
+                 open_upstream_file(name, SPARQL_NODES, "r") as fn:
+                g = parse_sparql(fe, fn)
         yield alt, g
[entries] New entry: sister_cities by Tiago de Paula Peixoto 9455885
diff --git a/entries/sister_cities/__init__.py b/entries/sister_cities/__init__.py
new file mode 100644
index 0000000..28a72c9
--- /dev/null
+++ b/entries/sister_cities/__init__.py
@@ -0,0 +1,54 @@
+#! /usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2026 Tiago de Paula Peixoto <tiago@skewed.de>
+#
+# This program is free software: you can redistribute it and/or modify it under
+# the terms of the GNU Affero General Public License as published by the Free
+# Software Foundation, either version 3 of the License, or (at your option) any
+# later version.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License along
+# with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+
+
+from .. import *
+
+
+title = 'Sister cities (Wikidata, 2017)'
+description = """An undirected network of cities and other administrative areas of the world connected by "sister city" (or "twin city") relationships, as extracted from Wikidata by KONECT in October 2017. Each node is a city (or another administrative body), and an edge connects two cities that are twinned. The data identify the cities only by indices; their names are not included."""
+tags = ['Social', 'Offline', 'Relationships', 'Unweighted']
+url = 'http://konect.cc/networks/twin'
+citation = [('J. Kunegis, "Sister cities network dataset." KONECT, the Koblenz Network Collection (2017)', 'http://konect.cc/networks/twin'),
+            ('J. Kunegis, "KONECT -- The Koblenz Network Collection." Proceedings of the 22nd International Conference on World Wide Web Companion, 1343-1350 (2013)', 'https://doi.org/10.1145/2487788.2488173')]
+icon_hash = None
+upstream_license = ('CC0 1.0 (Wikidata)', 'https://www.wikidata.org/wiki/Wikidata:Licensing')
+upstream_prefix = 'http://konect.cc/files'
+files = [('download.tsv.twin.tar.bz2', None, 'konect')]
+
+def postprocess(alt, g):
+    pass
+
+def fetch_upstream(force=False):
+    return fetch_upstream_files(__name__.split(".")[-1], upstream_prefix, files,
+                                force)
+
+@cache_network()
+@coerce_props()
+@annotate()
+def parse(alts=None):
+    global files
+    name = __name__.split(".")[-1]
+    for fname, alt, fmt in files:
+        if alts is not None and alt not in alts:
+            continue
+        with open_upstream_file(name, fname, "rb") as f:
+            g = parse_graph([f], fmt, directed=None)
+        postprocess(alt, g)
+        yield alt, g