Skip to content
Snippets Groups Projects
power-stats.ipynb 15.4 KiB
Newer Older
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Power Stats \n",
    "\n",
    "Use RestAPI to read power consumption info for cluster nodes and generate usage reports.  this is based on the [pandas time series tutorial by Jennifer Walker](https://www.dataquest.io/blog/tutorial-time-series-analysis-with-pandas/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import pprint\n",
    "import datetime\n",
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.dates as mdates"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# https://stackoverflow.com/a/9031848\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.rcParams[\"figure.figsize\"] = (20,6)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Set up credentials to query RestAPI. Bright controls access based on the user identity.  The user's cert.pem and cert.key are automatically generated but the cacert.pem needs to be constructed from the  certs returned by the master."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cert_file='~/.cm/cert.pem'\n",
    "key_file='~/.cm/cert.key'\n",
    "ca_file='cacert.pem'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cert=(os.path.expanduser(cert_file), os.path.expanduser(key_file))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Gather Cluster Power Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "startdate = '2021/06/01 00:00:00'\n",
    "enddate = '2021/10/20 00:00:00'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "displaystart = '2021-06-01'\n",
    "displaystop = '2021-10-20'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "params = (\n",
    "    ('start', startdate),\n",
    "    ('measurable', 'Pwr_Consumption'),\n",
    "    ('indent', '1'),\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if os.path.exists(\"ipower_data.csv\"):\n",
    "    df = pd.read_csv(\"power_data.csv\")\n",
    "else:\n",
    "    response = requests.get('https://master:8081/rest/v1/monitoring/dump', params=params, cert=cert, verify=False)\n",
    "    df = pd.DataFrame(response.json()[\"data\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Simply read the json response into a dataframe for futher parsing."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Clean Data and Resample\n",
    "\n",
    "Some of data values report unrealistic power values.  Any reading over 10kW is considered invalid.  \n",
    "\n",
    "Shouldn't do that until later since it implicitly filters out NaN"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create a datatime type column from the reported sample times."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df['datetime'] = pd.to_datetime(df.time, format=\"%Y/%m/%d %H:%M:%S\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create an index for the hourly "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hourly_idx=pd.date_range(startdate, enddate, freq='H')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hourly_idx"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "demodf=pd.DataFrame(np.zeros((1,len(hourly_idx))).T, index=hourly_idx, columns=['sum'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "demodf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.entity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sorted(df.entity.unique())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "debug=False\n",
    "\n",
    "# prepare data frame to append to, use zeros for default column \n",
    "m6_hourly_pwr=pd.DataFrame(np.zeros((1,len(hourly_idx))).T, index=hourly_idx, columns=['sum'])\n",
    "\n",
    "for num, entity in enumerate(sorted(df.entity.unique())):\n",
    "    if entity not in ['c0009']:\n",
    "        node_pwr=df[df.entity==entity].set_index(\"datetime\")\n",
    "        node_pwr=node_pwr[['raw']].resample('H').mean()\n",
    "        node_pwr=node_pwr[startdate:enddate].fillna(method=\"ffill\")\n",
    "        node_pwr=node_pwr[startdate:enddate].fillna(method=\"bfill\")\n",
    "        if debug:\n",
    "          print(node_pwr)\n",
    "          missing = node_pwr['raw'].isnull().sum()\n",
    "          print(\"{}: {} missing {}\\n\".format(num, entity, missing))\n",
    "        m6_hourly_pwr[entity]= node_pwr[startdate:enddate]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m6_hourly_pwr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m6_hourly_pwr.fillna(0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plot Per-node Hourly for Row 5 Rack 1\n",
    "This is just to see the data for each node in one plot and get a feel for how the nodes behave relative to each other.  Plot nodes in individual subplotes to decern individual behavior of specific nodes. It does give a sense of how the total power adds up. \n",
    "\n",
    "Inspect the nodes in the first rack.\n",
    "\n",
    "Plot help on [shared x-axis](https://stackoverflow.com/a/37738851)\n",
    "on [correct pandas legend use](https://stackoverflow.com/a/59797261)\n",
    "and [subplot legend placement](https://stackoverflow.com/a/27017307)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dftest=m6_hourly_pwr[displaystart:displaystop].fillna(0).iloc[:,1:2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "type(dftest)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(np.__version__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!module "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dftest.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "startnode=35\n",
    "stopnode=71\n",
    "num_nodes=stopnode-startnode\n",
    "fig, axes = plt.subplots(num_nodes,1, sharex=True, figsize=(20,30))\n",
    "for i in range(startnode, startnode+1):\n",
    "    print(i)\n",
    "    dftmp=m6_hourly_pwr[displaystart:displaystop].fillna(0).iloc[:,i+1:i+2]\n",
    "    dftmp.plot(ax=axes[i], legend=True)\n",
    "    axes[i].legend(loc='lower left')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Overview plot reveals missing power data for a number of nodes.  Inspect one up close."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "select_node=\"c0022\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[df.entity==select_node].set_index(\"datetime\")[\"2020-09-01\":\"2020-10-04\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m6_hourly_pwr[displaystart:displaystop].iloc[:,3:4][\"2020-10-03\":\"2020-10-04\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m6_hourly_pwr[displaystart:displaystop].iloc[:,3:4][\"2020-09-28\":\"2020-10-14\"].plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m6_hourly_pwr[displaystart:displaystop].iloc[:,3:4].plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[df[\"entity\"]==\"c0001\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[df[\"entity\"]==\"c0001\"][\"datetime\"].max()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Identify nodes that have missing data\n",
    "\n",
    "Identify nodes by ones that have NaN values over the past month."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nan_mask = m6_hourly_pwr[startdate:enddate].isna()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "power_missing = nan_mask[nan_mask].apply(lambda row: row[row == True].index, axis=1)[1]"
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(*power_missing,sep=\", \")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(num_nodes,1, sharex=True, figsize=(20,30))\n",
    "for i, node in enumerate(power_missing):\n",
    "    m6_hourly_pwr[node].plot(ax=axes[i], legend=True)\n",
    "    axes[i].legend(loc='lower left')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "node"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[df[\"entity\"]==node][\"datetime\"].max()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lastreport = pd.DataFrame(columns=('node', 'datetime'))\n",
    "\n",
    "for i, node in enumerate(power_missing):\n",
    "    lastreport.loc[i] = [node, df[df[\"entity\"]==node][\"datetime\"].max()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lastreport.sort_values(by=\"datetime\") #[\"datetime\"].sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"{}:\\t{}\".format(node, df[df[\"entity\"]==node][\"datetime\"].max()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plot all nodes power\n",
    "\n",
    "Create overview plot of all nodes to observe meta-patterns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_nodes=len(m6_hourly_pwr.iloc[:,1:].columns)\n",
    "\n",
    "fig, axes = plt.subplots(num_nodes,1, sharex=True, figsize=(20,num_nodes))\n",
    "for i, node in enumerate(m6_hourly_pwr.iloc[:,1:].columns):\n",
    "    if (i == num_nodes):\n",
    "        break\n",
    "    m6_hourly_pwr[node][displaystart:displaystop].plot(ax=axes[i], legend=True)\n",
    "    axes[i].legend(loc='lower left')\n"
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m6_hourly_pwr.iloc[:,133:199].columns"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Plot Power Usage Graph\n",
    "\n",
    "\n",
    "Pick the start and end date for the plots from the data range selected above. Generate the sum and plot only it's values.\n",
    "\n",
    "We skip over the first month of collection because it is uncommonly noisy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "kW = m6_hourly_pwr.iloc[:,133:199][displaystart:displaystop].sum(axis=1)/1000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ax = kW.plot()\n",
    "ax.set_ylabel(\"Power (kW)\")\n",
    "ax.set_title(\"Cheaha compute and login node hourly power use\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Resample hourly sum to support the seven day average."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "kW_d = kW.resample('D').mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compute the centered 7-day rolling mean\n",
    "# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html\n",
    "kW_7d = kW_d.rolling(7, center=True).mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Plot houry, daily, 7-day rolling mean\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(kW, marker='.', markersize=2, color='gray', linestyle='None', label='Hourly Average')\n",
    "ax.plot(kW_d, color='brown', linewidth=2, label='1-day Average')\n",
    "ax.plot(kW_7d, color='black', linewidth=4, label='7-day Rolling Average')\n",
    "label='Trend (7 day Rolling Mean)'\n",
    "ax.legend()\n",
    "ax.set_ylabel('Power (kW)')\n",
    "ax.set_title('Cheaha Trends in Electricity Consumption');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Save Hourly Power to Dataframe\n",
    "\n",
    "This makes it easy to use the data in other analysis and learning efforts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m6_hourly_pwr.to_pickle(\"m6_hourly_pwr.gz\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.to_pickle(\"power_stats_raw_df.gz\")"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}