To improve the data analysis and visualization of your script, you can indeed separate the parsing logic from the analysis and use modern Python data analysis tools like pandas for data manipulation and libraries like matplotlib or seaborn for creating pretty charts. Below is a step-by-step guide to refactor your code, improve the analysis, and create visualizations.
Step 1: Separate Parsing from Analysis
To make your code more modular, you can split the parsing logic (which processes the log file and builds the data structures) from the analysis logic (which computes statistics and generates visualizations). This will make it easier to maintain and extend your code.
Step 2: Use pandas for Data Analysis
pandas is a powerful library for data manipulation and analysis. You can store your data in a pandas.DataFrame, which makes it easy to compute statistics, filter data, and prepare it for visualization.
Step 3: Use Visualization Libraries
For creating "pretty charts," you can use:
matplotlib: A low-level plotting library that is highly customizable.
seaborn: A high-level library built on top of matplotlib that provides attractive statistical visualizations with less code.
Step 4: Refactored Code
Below is a refactored version of your script that incorporates these ideas. I've added comments to explain the changes.
#!/usr/bin/env python3
from collections import defaultdict
import sys
from dataclasses import dataclass
from enum import Enum
import re
from typing import Optional, Tuple, Dict, List
import logkicker
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Set up seaborn for prettier plots
sns.set(style="whitegrid")
# Your existing dataclasses, enums, and log patterns remain unchanged
@dataclass
class BlockReceived:
cb_size_bytes: int = 0
cb_missing_bytes: int = 0
cb_missing_tx_count: int = 0
cb_bytes_from_extra_pool: Optional[int] = None
@dataclass
class BlockSent:
block_received: BlockReceived
peer_id: int
cb_bytes_sent: int = 0
tcp_window_bytes: int = 0
class ReasonsToCare(Enum):
WE_DONT = 0
CB_SEND = 1
CB_RECEIVE = 2
CB_RECONSTRUCTION = 3
CB_TO_ANNOUNCE = 4
CB_REQUESTED = 5
NET_MAX_SEND = 6
@dataclass(frozen=True)
class LogPattern:
reason: ReasonsToCare
category: str
regex: re.Pattern[str]
LOG_PATTERNS = [
LogPattern(
reason=ReasonsToCare.CB_RECONSTRUCTION,
category="cmpctblock",
regex=re.compile(
r'Successfully reconstructed block (?P<blockhash>[0-9a-f]+) with '
r'(?P<prefill_count>\d+) txn prefilled, (?P<mempool_count>\d+) '
r'txn from mempool \(incl at least (?P<extrapool_count>\d+) from '
r'extra pool\) and (?P<requested_count>\d+) txn '
r'\((?P<requested_bytes>\d+) bytes\) requested'
),
),
LogPattern(
reason=ReasonsToCare.CB_RECEIVE,
category="cmpctblock",
regex=re.compile(r'Initialized PartiallyDownloadedBlock for block (?P<blockhash>[0-9a-f]+) using a cmpctblock of (?P<cmpctblock_bytes>\d+) bytes'),
),
LogPattern(
reason=ReasonsToCare.CB_SEND,
category="net",
regex=re.compile(r'sending cmpctblock \((?P<cmpctblock_bytes>\d+) bytes\) peer=(?P<peer_id>\d+)'),
),
LogPattern(
reason=ReasonsToCare.CB_TO_ANNOUNCE,
category="net",
regex=re.compile(r'PeerManager::NewPoWValidBlock sending header-and-ids (?P<blockhash>[0-9a-f]+) to peer=(?P<peer_id>\d+)'),
),
LogPattern(
reason=ReasonsToCare.CB_REQUESTED,
category="net",
regex=re.compile(r'received getdata for: cmpctblock (?P<blockhash>[0-9a-f]+) peer=(?P<peer_id>\d+)'),
),
LogPattern(
reason=ReasonsToCare.NET_MAX_SEND,
category="net",
regex=re.compile(r'\s*- Max send per-rtt: (?P<max_send_bytes>\d+) bytes'),
),
]
def we_care(entry: logkicker.LogEntry) -> Tuple[ReasonsToCare, Optional[dict]]:
entry_category = entry.metadata.category
for pattern in LOG_PATTERNS:
if entry_category == pattern.category:
if match := pattern.regex.match(entry.body):
data = match.groupdict()
return pattern.reason, data
return ReasonsToCare.WE_DONT, None
def parse_log(filepath: str) -> Tuple[Dict[str, BlockReceived], Dict[str, List[BlockSent]]]:
"""
Parse the log file and return the data structures for analysis.
"""
blocks_received: Dict[str, BlockReceived] = {}
blocks_sent: Dict[str, List[BlockSent]] = defaultdict(list)
pending_block_send: Optional[BlockSent] = None
pending_max_send: Optional[BlockSent] = None
for entry in logkicker.process_log_generator(filepath):
why, match = we_care(entry)
if why == ReasonsToCare.WE_DONT or match is None:
continue
match why:
case ReasonsToCare.CB_RECEIVE:
blocks_received[match['blockhash']] = BlockReceived(cb_size_bytes=int(match['cmpctblock_bytes']))
case ReasonsToCare.CB_RECONSTRUCTION:
block = blocks_received[match['blockhash']]
block.cb_missing_tx_count = int(match['requested_count'])
block.cb_missing_bytes = int(match['requested_bytes'])
case ReasonsToCare.CB_TO_ANNOUNCE | ReasonsToCare.CB_REQUESTED:
blockhash = match['blockhash']
if blockhash not in blocks_received:
continue
pending_block_send = BlockSent(block_received=blocks_received[blockhash], peer_id=int(match['peer_id']))
blocks_sent[blockhash].append(pending_block_send)
case ReasonsToCare.CB_SEND:
if not pending_block_send:
continue
assert pending_block_send.peer_id == int(match['peer_id'])
pending_block_send.cb_bytes_sent = int(match['cmpctblock_bytes'])
pending_max_send = pending_block_send
pending_block_send = None
case ReasonsToCare.NET_MAX_SEND:
if not pending_max_send:
continue
pending_max_send.tcp_window_bytes = int(match['max_send_bytes'])
pending_max_send = None
return blocks_received, blocks_sent
def analyze_data(blocks_received: Dict[str, BlockReceived], blocks_sent: Dict[str, List[BlockSent]]) -> pd.DataFrame:
"""
Analyze the parsed data and return a pandas DataFrame for further analysis and visualization.
"""
# Prepare data for analysis
data = []
for blockhash, sent_list in blocks_sent.items():
if blockhash not in blocks_received:
continue
received = blocks_received[blockhash]
received_size = received.cb_size_bytes
for sent in sent_list:
prefill_size = sent.cb_bytes_sent - received_size
bytes_used_in_tcp_window = received_size % sent.tcp_window_bytes
bytes_left_in_tcp_window = sent.tcp_window_bytes - bytes_used_in_tcp_window
rtts_needed_with_no_prefill = received_size // sent.tcp_window_bytes
# Calculate extra pool bytes if applicable
extra_pool_bytes = sent.cb_bytes_sent - received_size - received.cb_missing_bytes if prefill_size > 0 else 0
received.cb_bytes_from_extra_pool = extra_pool_bytes
data.append({
'blockhash': blockhash,
'received_size': received_size,
'cb_bytes_sent': sent.cb_bytes_sent,
'tcp_window_bytes': sent.tcp_window_bytes,
'prefill_size': prefill_size,
'extra_pool_bytes': extra_pool_bytes,
'bytes_left_in_tcp_window': bytes_left_in_tcp_window,
'rtts_needed_with_no_prefill': rtts_needed_with_no_prefill,
'cb_missing_tx_count': received.cb_missing_tx_count,
})
# Convert to DataFrame
df = pd.DataFrame(data)
return df
def print_statistics(df: pd.DataFrame, blocks_received: Dict[str, BlockReceived]):
"""
Print key statistics from the data.
"""
total_blocks_received = len(blocks_received)
blocks_failing_reconstruction = len([b for b in blocks_received.values() if b.cb_missing_tx_count > 0])
fail_rate = blocks_failing_reconstruction / total_blocks_received
reco_rate = 1 - fail_rate
print(f"{blocks_failing_reconstruction} out of {total_blocks_received} blocks received failed reconstruction.")
print(f"Reconstruction rate was {reco_rate * 100:.2f}%")
total_cb_sent = len(df)
sent_per_block = total_cb_sent / total_blocks_received
print(f"{total_cb_sent} CMPCTBLOCK messages sent, {sent_per_block:.2f} per block.")
exceeded_without_prefill = len(df[df['rtts_needed_with_no_prefill'] > 1])
already_over_rtt_rate = exceeded_without_prefill / total_cb_sent
print(f"{exceeded_without_prefill}/{total_cb_sent} CMPCTBLOCK's sent were already over the window for a single RTT before prefilling. ({already_over_rtt_rate * 100:.2f}%)")
avg_available_bytes = df['bytes_left_in_tcp_window'].mean()
print(f"Avg available prefill bytes for all CMPCTBLOCK's we sent: {avg_available_bytes:.2f}")
prefilled_df = df[df['prefill_size'] > 0]
if not prefilled_df.empty:
avg_available_bytes_for_needed = prefilled_df['bytes_left_in_tcp_window'].mean()
print(f"Avg available prefill bytes for prefilled CMPCTBLOCK's we sent: {avg_available_bytes_for_needed:.2f}")
avg_prefill_bytes = prefilled_df['prefill_size'].mean()
print(f"Avg total prefill size for CMPCTBLOCK's we prefilled: {avg_prefill_bytes:.2f}")
avg_extra_prefill_bytes = prefilled_df['extra_pool_bytes'].mean()
print(f"Avg bytes of prefill that were extra_txn: {avg_extra_prefill_bytes:.2f}")
avg_prefill_without_extra = (prefilled_df['prefill_size'] - prefilled_df['extra_pool_bytes']).mean()
print(f"Avg prefill size w/o extras: {avg_prefill_without_extra:.2f}")
total_prefilled_cb_sent = len(prefilled_df)
prefill_needed_rate = total_prefilled_cb_sent / total_cb_sent
prefills_that_fit = len(prefilled_df[prefilled_df['prefill_size'] <= prefilled_df['bytes_left_in_tcp_window']])
prefill_fit_rate = prefills_that_fit / total_prefilled_cb_sent
no_extra_prefills_that_fit = len(prefilled_df[prefilled_df['prefill_size'] - prefilled_df['extra_pool_bytes'] <= prefilled_df['bytes_left_in_tcp_window']])
print(f"{total_prefilled_cb_sent}/{total_cb_sent} blocks sent required prefills. ({prefill_needed_rate * 100:.2f}%)")
print(f"{prefills_that_fit}/{total_prefilled_cb_sent} prefilled blocks sent fit in the available bytes. ({prefill_fit_rate * 100:.2f}%)")
print(f"{no_extra_prefills_that_fit}/{total_prefilled_cb_sent} prefilled blocks would have fit if we hadn't prefilled extra txn's. ({no_extra_prefills_that_fit / total_prefilled_cb_sent * 100:.2f}%)")
def create_visualizations(df: pd.DataFrame, output_dir: str = "plots"):
"""
Create visualizations and save them to the specified output directory.
"""
import os
os.makedirs(output_dir, exist_ok=True)
# Plot 1: Distribution of prefill sizes
plt.figure(figsize=(10, 6))
sns.histplot(data=df, x="prefill_size", bins=30, kde=True)
plt.title("Distribution of Prefill Sizes")
plt.xlabel("Prefill Size (bytes)")
plt.ylabel("Count")
plt.savefig(f"{output_dir}/prefill_size_distribution.png")
plt.close()
# Plot 2: Prefill size vs. available bytes in TCP window
plt.figure(figsize=(10, 6))
sns.scatterplot(data=df, x="bytes_left_in_tcp_window", y="prefill_size", hue="extra_pool_bytes", palette="viridis")
plt.title("Prefill Size vs. Available Bytes in TCP Window")
plt.xlabel("Available Bytes in TCP Window")
plt.ylabel("Prefill Size (bytes)")
plt.savefig(f"{output_dir}/prefill_vs_available_bytes.png")
plt.close()
# Plot 3: Boxplot of prefill sizes by whether they fit in the TCP window
df['fits_in_window'] = df['prefill_size'] <= df['bytes_left_in_tcp_window']
plt.figure(figsize=(10, 6))
sns.boxplot(data=df, x="fits_in_window", y="prefill_size")
plt.title("Prefill Sizes by Whether They Fit in TCP Window")
plt.xlabel("Fits in TCP Window")
plt.ylabel("Prefill Size (bytes)")
plt.savefig(f"{output_dir}/prefill_fit_boxplot.png")
plt.close()
print(f"Visualizations saved to {output_dir}/")
def main(filepath: str):
# Step 1: Parse the log file
blocks_received, blocks_sent = parse_log(filepath)
# Step 2: Analyze the data and create a DataFrame
df = analyze_data(blocks_received, blocks_sent)
# Step 3: Print statistics
print_statistics(df, blocks_received)
# Step 4: Create visualizations
create_visualizations(df)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python script.py <filepath>")
sys.exit(1)
filepath = sys.argv[1]
main(filepath)