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
|
import math
import numpy as np
import pandas as pd
import plotly.graph_objs as go
from plotly.offline import plot
def resource_distribution_plot(df_resources, df_task, type, label, option, columns=20,):
assert type == "psutil_process_time_user" or type == "psutil_process_memory_resident"
assert option == "avg" or option == "max"
min_range = min(df_resources[type].astype('float'))
max_range = max(df_resources[type].astype('float'))
time_step = (max_range - min_range) / columns
if min_range == max_range:
x_axis = [min_range]
else:
x_axis = []
for i in np.arange(min_range, max_range + time_step, time_step):
x_axis.append(i)
tasks_dict = dict()
for i in range(len(df_task)):
row = df_task.iloc[i]
tasks_dict[row['task_id']] = []
def y_axis_setup():
items = [0] * len(x_axis)
for task_id, tasks in tasks_dict.items():
if option == 'avg':
task = df_resources[df_resources['task_id'] ==
task_id][type].astype('float').mean()
elif option == 'max':
task = df_resources[df_resources['task_id'] == task_id][type].astype('float').max()
else:
raise ValueError(f"Cannot plot unknown aggregation option {option}")
for i in range(len(x_axis) - 1):
a = task >= x_axis[i]
b = task < x_axis[i + 1]
if a and b:
items[i] += 1
break
if task >= x_axis[-1]:
items[-1] += 1
return items
if type == "psutil_process_time_user":
xaxis = dict(autorange=True,
title='CPU user time (seconds)')
elif type == "psutil_process_memory_resident":
xaxis = dict(autorange=True,
title='Memory usage (bytes)')
else:
raise ValueError(f"Cannot plot unknown type {type}")
fig = go.Figure(
data=[go.Bar(x=x_axis,
y=y_axis_setup(),
name='tasks')],
layout=go.Layout(xaxis=xaxis,
yaxis=dict(title='Tasks'),
title=label + '(' + option + ')'))
return plot(fig, show_link=False, output_type="div", include_plotlyjs=False)
def resource_time_series(tasks, type='psutil_process_time_user', label='CPU user time'):
tasks['epoch_time'] = (pd.to_datetime(
tasks['timestamp']) - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')
step = int(tasks['resource_monitoring_interval'][0])
start = tasks['epoch_time'].min()
end = tasks['epoch_time'].max()
tasks['relative_time'] = tasks['epoch_time'] - start
if end != start:
bins = pd.cut(tasks['relative_time'],
range(0, end - start + 1, step),
include_lowest=True)
df = tasks.groupby(bins, as_index=False)[type].mean()
df['time'] = step * df.index
fig = go.Figure(
data=[go.Scatter(x=df['time'],
y=df[type],
)],
layout=go.Layout(xaxis=dict(autorange=True,
title='Time (seconds)'),
yaxis=dict(title=label),
title=label))
else:
fig = go.Figure(
data=[go.Scatter(x=[0],
y=[tasks[type].mean()],
)],
layout=go.Layout(xaxis=dict(autorange=True,
title='Time (seconds)'),
yaxis=dict(title=label),
title=label))
return plot(fig, show_link=False, output_type="div", include_plotlyjs=False)
def worker_efficiency(task, node):
try:
node['epoch_time'] = (pd.to_datetime(
node['timestamp']) - pd.Timestamp("1970-01-01")) / pd.Timedelta('1s')
task['epoch_time_start'] = (pd.to_datetime(
task['task_try_time_launched']) - pd.Timestamp("1970-01-01")) / pd.Timedelta('1s')
task['epoch_time_running'] = (pd.to_datetime(
task['task_try_time_running']) - pd.Timestamp("1970-01-01")) / pd.Timedelta('1s')
task['epoch_time_returned'] = (pd.to_datetime(
task['task_try_time_returned']) - pd.Timestamp("1970-01-01")) / pd.Timedelta('1s')
start = int(min(task['epoch_time_start'].min(), node['epoch_time'].min()))
end = int(task['epoch_time_returned'].max())
# worker_plot will be used to make a histogram of worker usage, one bucket per
# second
worker_plot = [0] * (end - start + 1)
total_workers = node['worker_count'].sum()
for i, row in task.iterrows():
if math.isnan(row['epoch_time_running']):
# skip tasks with no running start time
continue
if math.isnan(row['epoch_time_returned']):
# there is no end time for this, so we should assume the "end" time
etr = end
else:
etr = row['epoch_time_returned']
# there's a two cases here:
# The task starts and ends in same one-second bucket:
# populate one bucket with the fraction of second between
# the start and end
#
# or
#
# The task starts in one bucket and ends in another:
# populate middle buckets with 1, and start/end buckets with fraction
start_bucket = int(row['epoch_time_running']) - start
end_bucket = int(etr) - start
if start_bucket == end_bucket:
fraction = etr - row['epoch_time_running']
worker_plot[start_bucket] += fraction
else:
fraction_before = row['epoch_time_running'] - int(row['epoch_time_running'])
worker_plot[start_bucket] += (1 - fraction_before)
for j in range(start_bucket + 1, end_bucket):
worker_plot[j] += 1
fraction_after = etr - int(etr)
worker_plot[end_bucket] += fraction_after
fig = go.Figure(
data=[go.Scatter(x=list(range(0, end - start + 1)),
y=worker_plot,
name='Total busy workers',
),
go.Scatter(x=list(range(0, end - start + 1)),
y=[total_workers] * (end - start + 1),
name='Total of workers in whole run',
)
],
layout=go.Layout(xaxis=dict(autorange=True,
title='Time (seconds)'),
yaxis=dict(title='Number of workers'),
title="Worker efficiency"))
return plot(fig, show_link=False, output_type="div", include_plotlyjs=False)
except Exception as e:
print(e)
return "The worker efficiency plot cannot be generated due to missing data."
def resource_efficiency(resource, node, label):
try:
resource['epoch_time'] = (pd.to_datetime(
resource['timestamp']) - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')
node['epoch_time'] = (pd.to_datetime(
node['timestamp']) - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')
resource = resource.sort_values(by='epoch_time')
start = min(resource['epoch_time'].min(), node['epoch_time'].min())
end = resource['epoch_time'].max()
resource['relative_time'] = resource['epoch_time'] - start
node['relative_time'] = node['epoch_time'] - start
resource['key'] = resource['task_id'].astype(str) + "-" + resource['try_id'].astype(str)
task_plot = [0] * (end - start + 1)
if label == 'CPU':
total = node['cpu_count'].sum()
elif label == 'mem':
total = node['total_memory'].sum() / 1024 / 1024 / 1024
resource['total_cpu_time'] = resource['psutil_process_time_user'] + resource['psutil_process_time_system']
for key in resource['key'].unique():
tmp = resource[resource['key'] == key]
tmp['last_timestamp'] = tmp['relative_time'].shift(1)
if label == 'CPU':
tmp['last_cputime'] = tmp['total_cpu_time'].shift(1)
for index, row in tmp.iterrows():
if np.isnan(row['last_timestamp']):
continue
for i in range(int(row['last_timestamp']), int(row['relative_time'])):
if label == 'CPU':
diff = (row['total_cpu_time'] - row['last_cputime']) / (row['relative_time'] - row['last_timestamp'])
elif label == 'mem':
diff = row['psutil_process_memory_resident'] / 1024 / 1024 / 1024
task_plot[i] += diff
if label == 'CPU':
name1 = 'Used CPU cores'
name2 = 'Total CPU cores'
yaxis = 'Number of CPU cores'
title = 'CPU usage'
elif label == 'mem':
name1 = 'Used memory'
name2 = 'Total memory'
yaxis = 'Memory (GB)'
title = 'Memory usage'
fig = go.Figure(
data=[go.Scatter(x=list(range(0, end - start + 1)),
y=task_plot,
name=name1,
),
go.Scatter(x=list(range(0, end - start + 1)),
y=[total] * (end - start + 1),
name=name2,
)
],
layout=go.Layout(xaxis=dict(autorange=True,
title='Time (seconds)'),
yaxis=dict(title=yaxis),
title=title))
return plot(fig, show_link=False, output_type="div", include_plotlyjs=False)
except Exception as e:
print(e)
return "The resource efficiency plot cannot be generated because of exception {}.".format(e)
|