-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathplot.py
More file actions
executable file
·283 lines (231 loc) · 7.23 KB
/
Copy pathplot.py
File metadata and controls
executable file
·283 lines (231 loc) · 7.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#!/usr/bin/env python3
"""Plot analysis results."""
from pathlib import Path
from types import SimpleNamespace
from typing import List, Optional
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import typer
from plotly.subplots import make_subplots
from esp_cpa_board.aes_utils import AesDecryptOperationType
app = typer.Typer()
def _render(ctx: typer.Context, fig: go.Figure):
"""Render the given figure to HTML."""
fig.update_layout(template="plotly_white")
fig.update_xaxes(
mirror=True,
ticks="outside",
showline=True,
linecolor="black",
gridcolor="lightgrey",
)
fig.update_yaxes(
mirror=True,
ticks="outside",
showline=True,
linecolor="black",
gridcolor="lightgrey",
)
if ctx.obj.json_output:
fig.write_json(
ctx.obj.output_filename,
)
else:
fig.write_html(ctx.obj.output_filename, auto_open=True)
@app.command()
def plot_ranks(ctx: typer.Context, input_file: Path):
"""Plot the rank evolution of each byte."""
df = pd.read_csv(input_file)
fig = px.line(
df,
x="Measurement Index",
y="Rank",
color="Name",
title=ctx.obj.graph_title,
render_mode="svg",
)
fig.update_traces(
line=dict(dash="dash", width=5, color="red"), selector=dict(name="Average")
)
_render(ctx, fig)
@app.command()
def plot_traces(ctx: typer.Context, input_file: Path):
"""Plot the rank evolution of each byte."""
df = pd.read_csv(input_file)
fig = px.line(
df,
x="Sample Index",
y="Value",
color="Name",
title=ctx.obj.graph_title,
)
_render(ctx, fig)
@app.command()
def plot_spread(ctx: typer.Context, input_file: Path, pruning_rate: float = 0.9):
"""Plot the spread at a given timestamp."""
df = pd.read_csv(input_file)
n_rows = len(df[df["Name"] == "Raw"]["Value"])
mask = np.random.rand(n_rows) > pruning_rate
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Scatter(
name="Samples",
x=df[df["Name"] == "Raw"]["Measurement Index"][mask],
y=df[df["Name"] == "Raw"]["Value"][mask],
mode="markers",
),
secondary_y=False,
)
fig.add_trace(
go.Scatter(
name="Temperature",
x=df[df["Name"] == "Temperature"]["Measurement Index"][mask],
y=df[df["Name"] == "Temperature"]["Temperature"][mask],
),
secondary_y=True,
)
fig.update_layout(title_text=ctx.obj.graph_title)
fig.update_xaxes(title_text="Measurement Index")
fig.update_yaxes(title_text="Sample Value (LSB)", secondary_y=False)
fig.update_yaxes(title_text="Temperature (°C)", secondary_y=True)
_render(ctx, fig)
@app.command()
def plot_correlations(ctx: typer.Context, input_file: Path, step_size: int = 50_000):
"""Plot the correlation coefficients evolution of each guess."""
df = pd.read_csv(input_file)
fig = px.line(
df[df["Measurement Index"] % step_size == 0],
x="Measurement Index",
y="Correlation Value",
color="Name",
facet_col="Byte",
facet_col_wrap=4,
title=ctx.obj.graph_title,
height=800,
)
fig.update_traces(line=dict(color="grey"))
fig.update_traces(line=dict(color="red"), selector=dict(name="Correct Guess"))
_render(ctx, fig)
@app.command()
def plot_leakages(ctx: typer.Context, input_file: Path):
"""Plot data from the leakage assessment results."""
df = pd.read_csv(input_file)
# Placeholder for blank operations, it makes the plot look cleaner
dataframes = []
for operation, round_index in [
(AesDecryptOperationType.INV_MIX_COLUMN, 0),
(AesDecryptOperationType.INV_MIX_COLUMN, 10),
(AesDecryptOperationType.INV_SHIFT_ROW, 10),
(AesDecryptOperationType.INV_SUB_BYTES, 10),
]:
d = pd.DataFrame(
{
"Sample Index": [0],
"Value": [0],
"Round": round_index,
"Operation Type": operation,
}
)
dataframes.append(d)
df = pd.concat([df, *dataframes])
fig = px.line(
df[df["Operation Type"] != "Input"],
x="Sample Index",
y="Value",
color="Operation Type",
facet_col="Operation Type",
facet_row="Round",
title=ctx.obj.graph_title,
facet_row_spacing=0.03,
facet_col_spacing=0.03,
category_orders={
"Operation Type": [
AesDecryptOperationType.ADD_ROUND_KEY,
AesDecryptOperationType.INV_MIX_COLUMN,
AesDecryptOperationType.INV_SHIFT_ROW,
AesDecryptOperationType.INV_SUB_BYTES,
]
},
height=800,
)
_render(ctx, fig)
@app.command()
def plot_correlations_at_index(
ctx: typer.Context, input_file: Path, byte_index: List[int], step_size: int = 10_000
):
"""Plot the correlation coefficients evolution of each guess."""
df = pd.read_csv(input_file)
df = df[df["Measurement Index"] % step_size == 0]
if len(byte_index) == 1:
fig = px.line(
df[df["Byte"] == byte_index[0]],
x="Measurement Index",
y="Correlation Value",
color="Name",
title=ctx.obj.graph_title,
)
else:
fig = px.line(
df[df["Byte"].isin(byte_index)],
x="Measurement Index",
y="Correlation Value",
color="Name",
facet_col="Byte",
title=ctx.obj.graph_title,
)
fig.update_traces(line=dict(color="grey"))
fig.update_traces(line=dict(color="red"), selector=dict(name="Correct Guess"))
_render(ctx, fig)
@app.command()
def plot_compare_spread(
ctx: typer.Context, input_file: Path, separator: Optional[int] = None
):
"""Plot a sample spread comparison."""
df = pd.read_csv(input_file)
vmin = np.min(df["Values"])
vmax = np.max(df["Values"])
dataframes = []
for name in df["Name"].unique():
counts, bins = np.histogram(
df["Values"][df["Name"] == name], bins=512, range=(vmin, vmax)
)
dataframes.append(
pd.DataFrame(
{
"Counts": counts,
"Values": bins[:-1],
"Name": name,
}
)
)
processed_df = pd.concat(dataframes)
fig = px.bar(
processed_df,
x="Values",
y="Counts",
color="Name",
title=ctx.obj.graph_title,
barmode="overlay",
)
fig.update_traces({"marker_line_width": 0})
fig.update_layout({"bargap": 0})
if separator is not None:
fig.add_vline(x=separator)
_render(ctx, fig)
@app.callback()
def main(
ctx: typer.Context,
json_output: bool = False,
output_filename: Path = Path("/tmp/render.html"),
graph_title: Optional[str] = None,
):
"""Plotting tools for analysis results."""
ctx.obj = SimpleNamespace(
json_output=json_output,
output_filename=output_filename,
graph_title=graph_title,
)
if __name__ == "__main__":
app()