Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Electronic sources for network analysis

Electronic sources for network analysis: what digital data (logs, APIs, web pages, sensors) can be turned into nodes and edges, how to collect and format them, and practical issues (rate limits, privacy, sampling).

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Engineers use electronic data sources to build social and interaction networks for tasks such as recommendation, anomaly detection, influence analysis and graph-based machine learning. Knowing how to convert raw digital traces (logs, API responses, scraped pages) into a correct network representation is essential for valid analysis and reproducible results.

Key ideas

Start from first principles. A graph is a pair G = (V, E) where V is a set of nodes (also called vertices) and E is a set of edges (also called links) connecting nodes. Define these before use: a node represents an actor or object (user, IP, file) and an edge represents a relation or interaction between two nodes.

  • Formal definitions universities expect:

    • A simple undirected graph is an ordered pair G = (V, E) where E ⊆ {{u, v} : u, v ∈ V, u ≠ v}. There are no loops or multiple edges.
    • A directed graph (digraph) is an ordered pair G = (V, E) where E ⊆ {(u, v) : u, v ∈ V, u ≠ v}. Edge (u, v) is not the same as (v, u).
    • A weighted graph attaches a numeric weight w(e) ∈ ℝ to each edge e ∈ E.
  • Electronic sources you will encounter (each defined):

    • Log: a time-ordered record produced by a system (web server, application, OS). Typical fields: timestamp, source, target, action, metadata.
    • API (Application Programming Interface): a structured machine endpoint returning data (often JSON or XML) on request. APIs commonly impose rate limits (maximum requests per time unit), require authentication (API keys/OAuth), and paginate results via cursors/pages; implement exponential backoff and honor 429/Retry-After when throttled.
    • Web scraping / crawling: automated download and parsing of web pages when APIs are not available. Respect robots.txt and legal constraints.
    • Mailboxes / email archives: stores of messages that can be mapped to sender→recipient edges.
    • Social platform exports: data directly provided by a social network (may be restricted) in formats such as JSON or CSV.
    • Sensor / mobile / IoT data: location, proximity or event streams producing temporal edges (e.g., Bluetooth encounters).
    • Public datasets: prepared network files (GraphML, GEXF, edge lists) used for experiments and baselines.
  • From events to networks: standard mapping (exam-style derivation universities ask for):

    1. Event record r contains at least: timestamp t(r), source s(r), target d(r), type type(r) (type may be message, follow, co-edit).
    2. Choose model: directed vs undirected; simple vs multigraph; static vs temporal.
    3. Define an aggregation function f over events that maps a set of events between a pair (u, v) to an edge weight w_{uv}:
      • Example choices: count events: w_{uv} = Σ_{r: s(r)=u, d(r)=v} 1; sum durations: w_{uv} = Σ_{r: s(r)=u, d(r)=v} duration(r); max or average of a value in events.
    4. Build adjacency matrix A where A_{ij} = w_{ij}. For an unweighted simple graph set A_{ij} = 1 if at least one event exists. Set A_{ii}=0 when using simple graphs (no self-loops).

    Exact mapping often written as: for node set V = { s(r) | r ranges over events } ∪ { d(r) | r ranges over events }, define E = { (u, v) | ∃ r with s(r)=u and d(r)=v }, with weight w(u,v)=Σ_{r: s(r)=u,d(r)=v} g(r) where g(r) is chosen (1 for count).

  • Temporal networks: two common approaches

    • Time-slice (snapshot): divide time into intervals Δt and build static G_{Δt} for each interval.
    • Event-based temporal graph: keep each event as a timestamped edge (u, v, t). Analysis uses timelines (e.g., cascade growth).
  • Data formats you must know (defined):

    • Edgelist: each row lists source,target[,weight] — simplest and universal.
    • Adjacency matrix: N×N matrix A where A_{ij} gives edge presence/weight.
    • GraphML / GEXF: XML-based formats carrying metadata and attributes.
    • JSON: hierarchical API responses; must be converted to rows for graphs.
  • Practical constraints and hygiene (short list):

    • Rate limits: APIs limit requests; design backoff and caching.
    • Sampling bias: when you cannot fetch full data, your sample method (snowball, random node, streaming) creates biases—state the assumption in answers.
    • Missing data and identity resolution: users may have multiple identifiers; develop matching rules (email normalization, handle lowercasing).
    • Privacy and consent: verify legal/ethical permission before collecting or publishing personal data.
  • What to draw for an exam diagram: draw a 4-column table (timestamp | source | target | action) with 5 rows of sample events; beside it draw nodes A, B, C and arrows for each event. Label arrow counts for aggregated weights and show adjacency matrix with rows=sources, columns=targets.

Formulas

G = (V, E) — G is a graph with node set V and edge set E. A_{ij} = w_{ij} — adjacency matrix entry for source i and target j equals edge weight w_{ij}. Units: determined by g(r) (e.g., counts, durations). Applies after aggregation. w_{uv} = Σ_{r: s(r)=u, d(r)=v} g(r) — weight between u and v equals sum over events r mapping to a chosen per-event value g(r) (g(r)=1 for counts). deg_out(u) = Σ_v A_{uv} — out-degree (weighted) of node u. Units: same as edge weights (determined by g(r)). Applies for directed graphs. deg_in(u) = Σ_v A_{vu} — in-degree (weighted). Units: same as edge weights. deg_undirected(u) = Σ_v A_{uv} for symmetric A (or after converting A←A+A^T for aggregation). This is the weighted 'strength'; for unweighted binary A it equals the number of neighbors. A (from edge list) construction: read each edge (u,v,w) and set A[u][v] += w. For undirected graphs also set A[v][u] += w (or store only one triangle).

Common code syntax to remember (Python / networkx): import networkx as nx G = nx.DiGraph() G.add_edge(u, v, weight=w) G.out_degree(u, weight='weight') nx.read_edgelist('file.txt', delimiter=',', create_using=nx.DiGraph(), data=[('weight', float)])

Worked examples

Example 1 — Convert a small message log into a directed weighted graph (numerical-style steps). Data (draw this 4-column table in your answer):

  1. 2026-01-01T10:00:00, Alice, Bob, message
  2. 2026-01-01T10:05:00, Bob, Alice, reply
  3. 2026-01-01T10:10:00, Alice, Carol, message
  4. 2026-01-01T10:15:00, Alice, Bob, message
  5. 2026-01-01T10:20:00, Carol, Alice, reply

Steps:

  1. Node set V = {Alice, Bob, Carol}.
  2. For directed weighted graph, choose g(r)=1 for count each event.
  3. Count events per ordered pair:
    • Alice→Bob: events 1 and 4 → w(Alice,Bob) = 2
    • Bob→Alice: event 2 → w(Bob,Alice) = 1
    • Alice→Carol: event 3 → w(Alice,Carol) = 1
    • Carol→Alice: event 5 → w(Carol,Alice) = 1
  4. Adjacency matrix A (rows = source, cols = target): Alice Bob Carol Alice 0 2 1 Bob 1 0 0 Carol 1 0 0
  5. Compute weighted degrees:
    • Out-degree(Alice) = 2 + 1 = 3
    • In-degree(Alice) = 1 + 1 = 2
    • Out-degree(Bob) = 1; In-degree(Bob) = 2
    • Out-degree(Carol) = 1; In-degree(Carol) = 1 Answer (final): Alice out=3 in=2; Bob out=1 in=2; Carol out=1 in=1.

If you convert to an undirected graph by summing A + A^T, then undirected edge weights are: Alice–Bob = 3, Alice–Carol = 2. Undirected degrees: Alice=5, Bob=3, Carol=2.

Example 2 — Python program: parse a CSV of messages and show weighted in/out degrees (complete, runnable). Code:

import csv
import networkx as nx

G = nx.DiGraph()
with open('messages.csv', newline='') as f:
    reader = csv.DictReader(f)
    for row in reader:
        u = row['src'].strip()
        v = row['dst'].strip()
        if G.has_edge(u, v):
            G[u][v]['weight'] += 1
        else:
            G.add_edge(u, v, weight=1)

for n in sorted(G.nodes()):
    out = G.out_degree(n, weight='weight')
    inn = G.in_degree(n, weight='weight')
    print(f"{n} out={out} in={inn}")

Sample input file messages.csv (5 lines including header):

timestamp,src,dst,action
2026-01-01T10:00:00,Alice,Bob,message
2026-01-01T10:05:00,Bob,Alice,reply
2026-01-01T10:10:00,Alice,Carol,message
2026-01-01T10:15:00,Alice,Bob,message
2026-01-01T10:20:00,Carol,Alice,reply

Exact program output (order alphabetical):

Alice out=3 in=2
Bob out=1 in=2
Carol out=1 in=1

(These match Example 1.)

Example 2 notes: This program uses only standard library csv and networkx; ensure networkx is installed. For very large logs use streaming counters (collections.Counter) and write the edgelist to disk rather than storing the full graph in memory.

Common mistakes

  • Ignoring timezones or inconsistent timestamp formats — always normalize timestamps (e.g., UTC). (Verify local exam rules for acceptable formats.)
  • Using API results as a complete population when you have a sampled or rate-limited view — this causes biased degree distributions.
  • Treating identifiers as canonical (users can change handles); perform identity resolution and report assumptions.
  • Violating privacy or terms of service: collecting and publishing identifiable user data without consent.

For your exam

Question types you will see for this topic:

  • Definitions: define log, API, edgelist, adjacency matrix, rate limit, sampling bias.
  • Short notes: explain how to convert a mailbox or server log into a network; list legal/ethical issues.
  • Derivations: step-by-step mapping from event table to adjacency matrix and degree calculations (show the matrix and counts).
  • Numericals: small example logs converted into edge lists and degree calculations — show all steps and final units (counts).
  • Programs: short Python program to parse CSV or log format and produce an edgelist or compute degrees (use networkx or counters).
  • Diagrams: draw the event table and the corresponding graph with arrows and adjacency matrix.

What full-marks answers include:

  • Clear definitions of terms used, explicit statement whether directed/undirected and weighted/unweighted, and any assumptions (time window, aggregation function).
  • A small example or diagram showing the mapping from raw records to edges, and the final adjacency matrix.
  • For program questions: correct code or pseudocode that handles deduplication and weights, and sample output.
  • Short discussion of practical issues: rate limits, privacy, sampling bias and how they might affect results.

Quick check

  1. What file format is simplest and universal for representing a graph?
  2. If you have events A→B (2 times) and B→A (1 time) and you convert to an undirected weighted graph by summing both directions, what is the undirected weight between A and B?
  3. Name two constraints you must consider when collecting data from a web API.

Answers: 1) Edgelist. 2) 3. 3) Rate limits and terms-of-service / privacy restrictions.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?