{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c32cfc08",
   "metadata": {},
   "source": [
    "<link rel=\"preconnect\" href=\"https://fonts.gstatic.com\">\n",
    "<link href=\"https://fonts.googleapis.com/css2?family=Fira+Code&display=swap\" rel=\"stylesheet\">\n",
    "\n",
    "### License\n",
    "\n",
    "<p style=\"font-family: 'Fira Code', monospace; font-size: 1.2rem\">\n",
    "Copyright 2021 Xilinx, Inc.<br><br>\n",
    "Licensed under the Apache License, Version 2.0 (the \"License\");<br>\n",
    "you may not use this file except in compliance with the License.<br><br>\n",
    "You may obtain a copy of the License at <a href=\"http://www.apache.org/licenses/LICENSE-2.0\"?>http://www.apache.org/licenses/LICENSE-2.0</a><br><br>\n",
    "Unless required by applicable law or agreed to in writing, software<br>\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,<br>\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br>\n",
    "See the License for the specific language governing permissions and<br>\n",
    "limitations under the License.<br>\n",
    "</p>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b3f448b",
   "metadata": {},
   "source": [
    "# ChipScoPy NoC Perfmon Example\n",
    "\n",
    "\n",
    "<img src=\"../img/api_overview.png\" width=\"500\" align=\"left\">"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0148dc10",
   "metadata": {},
   "source": [
    "## Description\n",
    "This example demonstrates how to configure a Versal for taking NoC performance measurements.\n",
    "\n",
    "## Requirements\n",
    "- Local or remote Xilinx Versal board, such as a VCK190\n",
    "- Xilinx hw_server 2022.1 installed and running\n",
    "- Xilinx cs_server 2022.1 installed and running\n",
    "- Python 3.8 or greater installed\n",
    "- ChipScoPy 2022.1 installed\n",
    "- Jupyter notebook support installed - Please do so, using the command `pip install chipscopy[jupyter]`\n",
    "- Matplotlib support installed - Please do so, using the command `pip install chipscopy[core-addons]`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f288847f",
   "metadata": {},
   "source": [
    "## 1 - Initialization: Imports and File Paths\n",
    "\n",
    "After this step,\n",
    "- Required functions and classes are imported\n",
    "- Paths to server(s) and files are set correctly"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59d27cb0",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "import os\n",
    "from time import sleep\n",
    "import matplotlib  # for nbconvert'd script\n",
    "from chipscopy.api.noc import (\n",
    "    TC_BEW,\n",
    "    TC_BER,\n",
    "    NoCPerfMonNodeListener,\n",
    ")\n",
    "from chipscopy.api.noc.plotting_utils import MeasurementPlot\n",
    "from chipscopy import create_session, report_versions\n",
    "from chipscopy import get_design_files"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f17d31b0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Make sure to start the hw_server and cs_server prior to running.\n",
    "# Specify locations of the running hw_server and cs_server below.\n",
    "# The default is localhost - but can be other locations on the network.\n",
    "CS_URL = os.getenv(\"CS_SERVER_URL\", \"TCP:localhost:3042\")\n",
    "HW_URL = os.getenv(\"HW_SERVER_URL\", \"TCP:localhost:3121\")\n",
    "\n",
    "# The get_design_files() function tries to find the PDI and LTX files. In non-standard\n",
    "# configurations, you can put the path for PROGRAMMING_FILE and PROBES_FILE below.\n",
    "design_files = get_design_files(\"vck190/production/chipscopy_ced\")\n",
    "\n",
    "print(\"INFO: HBM design not included in chipscopy, user must provide design!!\")\n",
    "\n",
    "print(f\"HW_URL: {HW_URL}\")\n",
    "print(f\"CS_URL: {CS_URL}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20e8998b",
   "metadata": {},
   "source": [
    "## 2 - Create a session and connect to the hw_server and cs_server\n",
    "\n",
    "The session is a container that keeps track of devices and debug cores.\n",
    "After this step,\n",
    "- Session is initialized and connected to server(s)\n",
    "- Versions are detected and reported to stdout"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4c0a09fc",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "session = create_session(cs_server_url=CS_URL, hw_server_url=HW_URL)\n",
    "report_versions(session)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75fe0dc5",
   "metadata": {},
   "source": [
    "## 3 - Select the device and program\n",
    "\n",
    "After this step,\n",
    "- Device is programmed with the example programming file (for this example the user must supply the design)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc41041b",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "versal_device = session.devices.filter_by(family=\"versal\").get()\n",
    "# use this to program your design\n",
    "# versal_device.program(\"filename.pdi\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8fce0e94",
   "metadata": {},
   "source": [
    "## 4 - Discover Debug Cores\n",
    "\n",
    "Debug core discovery initializes the chipscope server debug cores. This brings debug cores in the chipscope server online.\n",
    "\n",
    "After this step,\n",
    "\n",
    "- The cs_server is initialized and ready for use"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5196bbc2",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "versal_device.discover_and_setup_cores(\n",
    "    noc_scan=True, ila_scan=False, vio_scan=False, pcie_scan=False\n",
    ")\n",
    "print(f\"Debug cores setup and ready for use.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b660dc9",
   "metadata": {},
   "source": [
    "## 5 - Setup NoC core\n",
    "\n",
    "Ensure scan nodes are enabled in the design.\n",
    "\n",
    "We begin by enumerating the debug cores (hard and soft) present in the design.\n",
    "Then we ask the design for the supported timebases. And, finally:\n",
    "The NoC is scanned to determine the activated elements."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2154c02e",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "nocs = versal_device.noc_core\n",
    "base_noc = nocs[0]\n",
    "print(base_noc.name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e06b7fe",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# this will setup the nodes on the server side and return the nodes successfully enumerated\n",
    "# print(\"Discovering NoC, this may take some time...\")\n",
    "# hbm_enable_list = base_noc.discover_noc_elements()\n",
    "# or enumerate!\n",
    "scan_nodes = [\"HBM_MC_X0Y0\", \"NOC_NMU_HBM2E_X0Y0\", \"NOC_NMU_HBM2E_X1Y0\"]\n",
    "print(\"\\nEnumerating nodes: \", end=\"\")\n",
    "for node in scan_nodes:\n",
    "    print(f\"{node}, \", end=\"\")\n",
    "print(\"...\", end=\"\")\n",
    "\n",
    "hbm_enable_list = base_noc.enumerate_noc_elements(scan_nodes)\n",
    "print(\"complete!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8eb7128c",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "supported_periods = base_noc.get_supported_sampling_periods(100 / 3, 100 / 3, {})\n",
    "print(\"Supported sampling periods:\")\n",
    "for domain, periods in supported_periods.items():\n",
    "    print(f\"  {domain}:\")\n",
    "    for p in periods:\n",
    "        print(f\"    {p:.0f}ms\", end=\"\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c797ef2e",
   "metadata": {},
   "source": [
    "Select Timebase and Nodes to Monitor\n",
    "\n",
    "For the various clock domains we must select a sampling period from the hardware supported values. The debug cable used will dictate how much bandwidth is available, so high frequency sampling may not actually produce data at the specified rate. Recommendation is ~500ms for jtag.\n",
    "\n",
    "Then the user must decide what to monitor--again the bandwidth is a definite consideration here. Plot performance may become the bottleneck (Optimizations will come later in the renderer or agg backend). The guidance here is to pick up to 4 nodes to monitor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1bcc1e3d",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "desired_period = 500  # ms\n",
    "sampling_intervals = {}\n",
    "\n",
    "for domain in supported_periods.keys():\n",
    "    sampling_intervals[domain] = 0\n",
    "    for sp in supported_periods[domain]:\n",
    "        if sp >= desired_period:\n",
    "            sampling_intervals[domain] = sp\n",
    "            break\n",
    "\n",
    "    if sampling_intervals[domain] == 0:\n",
    "        print(\n",
    "            f\"Warning, desired period {desired_period}ms is slower than \"\n",
    "            f\"longest supported period {supported_periods[domain][-1]}ms [{domain} domain] \"\n",
    "            f\"defaulting to this value.\"\n",
    "        )\n",
    "        sampling_intervals[domain] = supported_periods[-1]\n",
    "\n",
    "print(f\"Sampling period selection:\")\n",
    "for domain, freq in sampling_intervals.items():\n",
    "    print(f\"  {domain}: {freq:.0f}ms\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3ccd843",
   "metadata": {},
   "source": [
    "##  6 - Configure Monitors\n",
    "\n",
    "As a precaution, it's a good idea to validate the desired nodes are enabled for the design.\n",
    "Using the set of nodes and the desired sampling periods it's time to ask the service to start pushing metric data. Two additional arguments are required to this API.\n",
    "\n",
    "Traffic class\n",
    "\n",
    "This is a bit-or field of the requested traffic classes. Note, One monitor is dedicated to read traffic classes and the other to write--so all read TCs will apply to one channel and all write TCs to the other. `Best effort` is a good place to start.\n",
    "\n",
    "Number of Samples\n",
    "\n",
    "The number of samples allows for a burst of measurements to be taken and then the underlying service will tear down the monitors and stop pumping data back to the client. `-1` denotes that sampling shall continue indefinitely."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f1e5eaf",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# total number of samples to capture (-1 for continuous mode)\n",
    "num_samples = -1\n",
    "\n",
    "enable_list = hbm_enable_list\n",
    "print(\"Setting up monitors for: \")\n",
    "for node in enable_list:\n",
    "    print(node)\n",
    "\n",
    "# When overflow occurs the precision of the monitors must be traded for range\n",
    "# See the server API for more information\n",
    "extended_monitor_config = {\n",
    "    \"NOC_NMU_HBM2E_X0Y0\": {\"tslide\": 0x3},\n",
    "    \"NOC_NMU_HBM2E_X1Y0\": {\"tslide\": 0x3},\n",
    "}  # or None\n",
    "base_noc.configure_monitors(\n",
    "    enable_list, sampling_intervals, (TC_BEW | TC_BER), num_samples, None, extended_monitor_config\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11bb54bb",
   "metadata": {},
   "source": [
    "## 7 - Create plotter and listener\n",
    "\n",
    "Attach both to running view"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "81c69c4b",
   "metadata": {},
   "outputs": [],
   "source": [
    "record_to_file = False  # True | False\n",
    "node_listener = NoCPerfMonNodeListener(\n",
    "    sampling_intervals,\n",
    "    num_samples,\n",
    "    enable_list,\n",
    "    record_to_file,\n",
    "    extended_monitor_config=extended_monitor_config,\n",
    ")\n",
    "session.chipscope_view.add_node_listener(node_listener)\n",
    "\n",
    "plotter = MeasurementPlot(enable_list, mock=False, figsize=(10, 7.5))\n",
    "node_listener.link_plotter(plotter)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2793878b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Build Plotting Graphs\n",
    "matplotlib.use(\"Qt5Agg\")\n",
    "plotter.build_graphs()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7fcf2c5d",
   "metadata": {},
   "source": [
    "## 8 - Main Event Loop\n",
    "\n",
    "This loop runs until you close the plotter.\n",
    "\n",
    "If you are using a finite amount of measurement samples, you can uncomment the if --> break statement to automatically return from execution of this cell upon completion of the burst."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6b954ba2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run Main Event Loop\n",
    "while True:\n",
    "    session.chipscope_view.run_events()\n",
    "    sleep(0.1)\n",
    "    plotter.fig.canvas.draw()\n",
    "    plotter.fig.canvas.flush_events()\n",
    "    if not plotter.alive:\n",
    "        break\n",
    "    # Below will return on burst completion - uncomment if you want to try.\n",
    "    # if all([x <= 0 for x in node_listener.num_samples.values()]):\n",
    "    #     break"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
