summaryrefslogtreecommitdiffstats
path: root/svm/persist.c
blob: 591072dfd59fc5e14186a9680b2600124c6459e7 (plain)
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
/* 
 *------------------------------------------------------------------
 * persist.c - persistent data structure storage test / demo code
 *
 * Copyright (c) 2013 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *------------------------------------------------------------------
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>
#include <vppinfra/clib.h>
#include <vppinfra/vec.h>
#include <vppinfra/hash.h>
#include <vppinfra/bitmap.h>
#include <vppinfra/fifo.h>
#include <vppinfra/time.h>
#include <vppinfra/mheap.h>
#include <vppinfra/heap.h>
#include <vppinfra/pool.h>
#include <vppinfra/format.h>
#include <vppinfra/serialize.h>
#include <svmdb.h>

typedef struct {
    svmdb_client_t *c;
} persist_main_t;

persist_main_t persist_main;

typedef struct {
    u8 * string1;
    u8 * string2;
} demo_struct2_t;

typedef struct {
    demo_struct2_t * demo2;
    u8 * name;
} demo_struct1_t;

/* 
 * Data structures in persistent shared memory, all the time
 */
clib_error_t * persist_malloc (persist_main_t * pm)
{
    demo_struct2_t *demo2;
    demo_struct1_t *demo1;
    time_t starttime = time(0);
    char *datestring = ctime(&starttime);
    void *oldheap;

    /* Get back the root pointer */
    demo1 = svmdb_local_get_variable_reference 
        (pm->c, SVMDB_NAMESPACE_VEC, "demo1_location");

    /* It doesnt exist create our data structures */
    if (demo1 == 0) {
        /* If you want MP / thread safety, lock the region... */
        pthread_mutex_lock(&pm->c->db_rp->mutex);

        /* Switch to the shared memory region heap */
        oldheap = svm_push_data_heap (pm->c->db_rp);

        /* Allocate the top-level structure as a single element vector */
        vec_validate (demo1, 0);

        /* Allocate the next-level structure as a plain old memory obj */
        demo2 = clib_mem_alloc (sizeof (*demo2));

        demo1->demo2 = demo2;
        demo1->name = format (0, "My name is Ishmael%c", 0);
        demo2->string1 = format (0, "Here is string1%c", 0);
        demo2->string2 = format (0, "Born at %s%c", datestring, 0);

        /* Back to the process-private heap */
        svm_pop_heap(oldheap);
        pthread_mutex_unlock(&pm->c->db_rp->mutex);

        /* 
         * Set the root pointer. Note: this guy switches heaps, locks, etc.
         * We allocated demo1 as a vector to make this "just work..."
         */
        svmdb_local_set_vec_variable (pm->c, "demo1_location", 
                                      demo1, sizeof (demo1));

    }
    else {
        /* retrieve and print data from shared memory */
        demo2 = demo1->demo2;
        fformat (stdout, "name: %s\n", demo1->name);
        fformat (stdout, "demo2 location: %llx\n", demo2);
        fformat (stdout, "string1: %s\n", demo2->string1);
        fformat (stdout, "string2: %s\n", demo2->string2);
    }
    return 0;
}

void unserialize_demo1 (serialize_main_t *sm, va_list * args)
{
    demo_struct1_t ** result = va_arg (*args, demo_struct1_t **);
    demo_struct1_t * demo1;
    demo_struct2_t * demo2;

    /* Allocate data structures in process private memory */
    demo1 = clib_mem_alloc (sizeof (*demo1));
    demo2 = clib_mem_alloc (sizeof (*demo2));
    demo1->demo2 = demo2;

    /* retrieve data from shared memory checkpoint */
    unserialize_cstring (sm, (char **) &demo1->name);
    unserialize_cstring (sm, (char **) &demo2->string1);
    unserialize_cstring (sm, (char **) &demo2->string2);
    *result = demo1;
}

void serialize_demo1 (serialize_main_t *sm, va_list * args)
{
    demo_struct1_t * demo1 = va_arg (*args, demo_struct1_t *);
    demo_struct2_t * demo2 = demo1->demo2;

    serialize_cstring (sm, (char *)demo1->name);
    serialize_cstring (sm, (char *)demo2->string1);
    serialize_cstring (sm, (char *)demo2->string2);
}        

/* Serialize / unserialize variant */
clib_error_t * 
persist_serialize (persist_main_t * pm)
{
    u8 * checkpoint;
    serialize_main_t sm;

    demo_struct2_t *demo2;
    demo_struct1_t *demo1;
    time_t starttime = time(0);
    char *datestring = ctime(&starttime);

    /* Get back the root pointer */
    checkpoint = svmdb_local_get_vec_variable (pm->c, "demo1_checkpoint", 
                                               sizeof (u8));

    /* It doesnt exist create our data structures */
    if (checkpoint == 0) {
        /* Allocate data structures in process-private memory */
        demo1 = clib_mem_alloc (sizeof (*demo2));
        vec_validate (demo1, 0);
        demo2 = clib_mem_alloc (sizeof (*demo2));

        demo1->demo2 = demo2;
        demo1->name = format (0, "My name is Ishmael%c", 0);
        demo2->string1 = format (0, "Here is string1%c", 0);
        demo2->string2 = format (0, "Born at %s%c", datestring, 0);

        /* Create checkpoint */
        serialize_open_vector (&sm, checkpoint);
        serialize (&sm, serialize_demo1, demo1);
        checkpoint = serialize_close_vector (&sm);

        /* Copy checkpoint into shared memory */
        svmdb_local_set_vec_variable (pm->c, "demo1_checkpoint", 
                                      checkpoint, sizeof (u8));
        /* Toss the process-private-memory original.. */
        vec_free (checkpoint);
    }
    else {
        /* Open the checkpoint */
        unserialize_open_data (&sm, checkpoint, vec_len (checkpoint));
        unserialize (&sm, unserialize_demo1, &demo1);

        /* Toss the process-private-memory checkpoint copy */
        vec_free (checkpoint);

        /* Off we go... */
        demo2 = demo1->demo2;
        fformat (stdout, "name: %s\n", demo1->name);
        fformat (stdout, "demo2 location: %llx\n", demo2);
        fformat (stdout, "string1: %s\n", demo2->string1);
        fformat (stdout, "string2: %s\n", demo2->string2);
    }
    return 0;
}


int main (int argc, char **argv)
{
    unformat_input_t _input, *input=&_input;
    persist_main_t * pm = &persist_main;
    clib_error_t * error = 0;

    /* Make a 4mb database arena, chroot so it's truly private */
    pm->c = svmdb_map_chroot_size ("/ptest", 4<<20);

    ASSERT(pm->c);

    unformat_init_command_line (input, argv);

    while (unformat_check_input(input) != UNFORMAT_END_OF_INPUT)  {
        if (unformat (input, "malloc"))
            error = persist_malloc (pm);
        else if (unformat (input, "serialize"))
            error = persist_serialize (pm);
        else {
            error = clib_error_return (0, "Unknown flavor '%U'",
                                       format_unformat_error, input);
            break;
        }
    }

    svmdb_unmap (pm->c);

    if (error) {
        clib_error_report (error);
        exit (1);
    }
    return 0;
}
75'>1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504
# Copyright (c) 2019 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Algorithms to generate plots.
"""


import re
import logging
import pandas as pd
import plotly.offline as ploff
import plotly.graph_objs as plgo

from plotly.exceptions import PlotlyError
from collections import OrderedDict
from copy import deepcopy

from utils import mean, stdev


COLORS = ["SkyBlue", "Olive", "Purple", "Coral", "Indigo", "Pink",
          "Chocolate", "Brown", "Magenta", "Cyan", "Orange", "Black",
          "Violet", "Blue", "Yellow", "BurlyWood", "CadetBlue", "Crimson",
          "DarkBlue", "DarkCyan", "DarkGreen", "Green", "GoldenRod",
          "LightGreen", "LightSeaGreen", "LightSkyBlue", "Maroon",
          "MediumSeaGreen", "SeaGreen", "LightSlateGrey"]

REGEX_NIC = re.compile(r'\d*ge\dp\d\D*\d*-')


def generate_plots(spec, data):
    """Generate all plots specified in the specification file.

    :param spec: Specification read from the specification file.
    :param data: Data to process.
    :type spec: Specification
    :type data: InputData
    """

    logging.info("Generating the plots ...")
    for index, plot in enumerate(spec.plots):
        try:
            logging.info("  Plot nr {0}: {1}".format(index + 1,
                                                     plot.get("title", "")))
            plot["limits"] = spec.configuration["limits"]
            eval(plot["algorithm"])(plot, data)
            logging.info("  Done.")
        except NameError as err:
            logging.error("Probably algorithm '{alg}' is not defined: {err}".
                          format(alg=plot["algorithm"], err=repr(err)))
    logging.info("Done.")


def plot_service_density_reconf_box_name(plot, input_data):
    """Generate the plot(s) with algorithm: plot_service_density_reconf_box_name
    specified in the specification file.

    :param plot: Plot to generate.
    :param input_data: Data to process.
    :type plot: pandas.Series
    :type input_data: InputData
    """

    # Transform the data
    plot_title = plot.get("title", "")
    logging.info("    Creating the data set for the {0} '{1}'.".
                 format(plot.get("type", ""), plot_title))
    data = input_data.filter_tests_by_name(
        plot, params=["result", "parent", "tags", "type"])
    if data is None:
        logging.error("No data.")
        return

    # Prepare the data for the plot
    y_vals = OrderedDict()
    loss = dict()
    for job in data:
        for build in job:
            for test in build:
                if y_vals.get(test["parent"], None) is None:
                    y_vals[test["parent"]] = list()
                    loss[test["parent"]] = list()
                try:
                    y_vals[test["parent"]].append(test["result"]["time"])
                    loss[test["parent"]].append(test["result"]["loss"])
                except (KeyError, TypeError):
                    y_vals[test["parent"]].append(None)

    # Add None to the lists with missing data
    max_len = 0
    nr_of_samples = list()
    for val in y_vals.values():
        if len(val) > max_len:
            max_len = len(val)
        nr_of_samples.append(len(val))
    for key, val in y_vals.items():
        if len(val) < max_len:
            val.extend([None for _ in range(max_len - len(val))])

    # Add plot traces
    traces = list()
    df = pd.DataFrame(y_vals)
    df.head()
    for i, col in enumerate(df.columns):
        tst_name = re.sub(REGEX_NIC, "",
                          col.lower().replace('-ndrpdr', '').
                          replace('2n1l-', ''))
        tst_name = "-".join(tst_name.split("-")[3:-2])
        name = "{nr}. ({samples:02d} run{plural}, packets lost average: " \
               "{loss:.1f}) {name}".format(
                    nr=(i + 1),
                    samples=nr_of_samples[i],
                    plural='s' if nr_of_samples[i] > 1 else '',
                    name=tst_name,
                    loss=mean(loss[col]))

        traces.append(plgo.Box(x=[str(i + 1) + '.'] * len(df[col]),
                               y=[y if y else None for y in df[col]],
                               name=name,
                               hoverinfo="y+name"))
    try:
        # Create plot
        layout = deepcopy(plot["layout"])
        layout["title"] = "<b>Time Lost:</b> {0}".format(layout["title"])
        layout["yaxis"]["title"] = "<b>Implied Time Lost [s]</b>"
        layout["legend"]["font"]["size"] = 14
        layout["yaxis"].pop("range")
        plpl = plgo.Figure(data=traces, layout=layout)

        # Export Plot
        file_type = plot.get("output-file-type", ".html")
        logging.info("    Writing file '{0}{1}'.".
                     format(plot["output-file"], file_type))
        ploff.plot(plpl, show_link=False, auto_open=False,
                   filename='{0}{1}'.format(plot["output-file"], file_type))
    except PlotlyError as err:
        logging.error("   Finished with error: {}".
                      format(repr(err).replace("\n", " ")))
        return


def plot_performance_box_name(plot, input_data):
    """Generate the plot(s) with algorithm: plot_performance_box_name
    specified in the specification file.

    :param plot: Plot to generate.
    :param input_data: Data to process.
    :type plot: pandas.Series
    :type input_data: InputData
    """

    # Transform the data
    plot_title = plot.get("title", "")
    logging.info("    Creating the data set for the {0} '{1}'.".
                 format(plot.get("type", ""), plot_title))
    data = input_data.filter_tests_by_name(
        plot, params=["throughput", "parent", "tags", "type"])
    if data is None:
        logging.error("No data.")
        return

    # Prepare the data for the plot
    y_vals = OrderedDict()
    for job in data:
        for build in job:
            for test in build:
                if y_vals.get(test["parent"], None) is None:
                    y_vals[test["parent"]] = list()
                try:
                    if test["type"] in ("NDRPDR", ):
                        if "-pdr" in plot_title.lower():
                            y_vals[test["parent"]].\
                                append(test["throughput"]["PDR"]["LOWER"])
                        elif "-ndr" in plot_title.lower():
                            y_vals[test["parent"]]. \
                                append(test["throughput"]["NDR"]["LOWER"])
                        else:
                            continue
                    elif test["type"] in ("SOAK", ):
                        y_vals[test["parent"]].\
                            append(test["throughput"]["LOWER"])
                    else:
                        continue
                except (KeyError, TypeError):
                    y_vals[test["parent"]].append(None)

    # Add None to the lists with missing data
    max_len = 0
    nr_of_samples = list()
    for val in y_vals.values():
        if len(val) > max_len:
            max_len = len(val)
        nr_of_samples.append(len(val))
    for key, val in y_vals.items():
        if len(val) < max_len:
            val.extend([None for _ in range(max_len - len(val))])

    # Add plot traces
    traces = list()
    df = pd.DataFrame(y_vals)
    df.head()
    y_max = list()
    for i, col in enumerate(df.columns):
        tst_name = re.sub(REGEX_NIC, "",
                          col.lower().replace('-ndrpdr', '').
                          replace('2n1l-', ''))
        name = "{nr}. ({samples:02d} run{plural}) {name}".\
            format(nr=(i + 1),
                   samples=nr_of_samples[i],
                   plural='s' if nr_of_samples[i] > 1 else '',
                   name=tst_name)

        logging.debug(name)
        traces.append(plgo.Box(x=[str(i + 1) + '.'] * len(df[col]),
                               y=[y / 1000000 if y else None for y in df[col]],
                               name=name,
                               hoverinfo="y+name"))
        try:
            val_max = max(df[col])
        except ValueError as err:
            logging.error(repr(err))
            continue
        if val_max:
            y_max.append(int(val_max / 1000000) + 2)

    try:
        # Create plot
        layout = deepcopy(plot["layout"])
        if layout.get("title", None):
            layout["title"] = "<b>Throughput:</b> {0}". \
                format(layout["title"])
        if y_max:
            layout["yaxis"]["range"] = [0, max(y_max)]
        plpl = plgo.Figure(data=traces, layout=layout)

        # Export Plot
        file_type = plot.get("output-file-type", ".html")
        logging.info("    Writing file '{0}{1}'.".
                     format(plot["output-file"], file_type))
        ploff.plot(plpl, show_link=False, auto_open=False,
                   filename='{0}{1}'.format(plot["output-file"], file_type))
    except PlotlyError as err:
        logging.error("   Finished with error: {}".
                      format(repr(err).replace("\n", " ")))
        return


def plot_latency_error_bars_name(plot, input_data):
    """Generate the plot(s) with algorithm: plot_latency_error_bars_name
    specified in the specification file.

    :param plot: Plot to generate.
    :param input_data: Data to process.
    :type plot: pandas.Series
    :type input_data: InputData
    """

    # Transform the data
    plot_title = plot.get("title", "")
    logging.info("    Creating the data set for the {0} '{1}'.".
                 format(plot.get("type", ""), plot_title))
    data = input_data.filter_tests_by_name(
        plot, params=["latency", "parent", "tags", "type"])
    if data is None:
        logging.error("No data.")
        return

    # Prepare the data for the plot
    y_tmp_vals = OrderedDict()
    for job in data:
        for build in job:
            for test in build:
                try:
                    logging.debug("test['latency']: {0}\n".
                                  format(test["latency"]))
                except ValueError as err:
                    logging.warning(repr(err))
                if y_tmp_vals.get(test["parent"], None) is None:
                    y_tmp_vals[test["parent"]] = [
                        list(),  # direction1, min
                        list(),  # direction1, avg
                        list(),  # direction1, max
                        list(),  # direction2, min
                        list(),  # direction2, avg
                        list()   # direction2, max
                    ]
                try:
                    if test["type"] in ("NDRPDR", ):
                        if "-pdr" in plot_title.lower():
                            ttype = "PDR"
                        elif "-ndr" in plot_title.lower():
                            ttype = "NDR"
                        else:
                            logging.warning("Invalid test type: {0}".
                                            format(test["type"]))
                            continue
                        y_tmp_vals[test["parent"]][0].append(
                            test["latency"][ttype]["direction1"]["min"])
                        y_tmp_vals[test["parent"]][1].append(
                            test["latency"][ttype]["direction1"]["avg"])
                        y_tmp_vals[test["parent"]][2].append(
                            test["latency"][ttype]["direction1"]["max"])
                        y_tmp_vals[test["parent"]][3].append(
                            test["latency"][ttype]["direction2"]["min"])
                        y_tmp_vals[test["parent"]][4].append(
                            test["latency"][ttype]["direction2"]["avg"])
                        y_tmp_vals[test["parent"]][5].append(
                            test["latency"][ttype]["direction2"]["max"])
                    else:
                        logging.warning("Invalid test type: {0}".
                                        format(test["type"]))
                        continue
                except (KeyError, TypeError) as err:
                    logging.warning(repr(err))

    x_vals = list()
    y_vals = list()
    y_mins = list()
    y_maxs = list()
    nr_of_samples = list()
    for key, val in y_tmp_vals.items():
        name = re.sub(REGEX_NIC, "", key.replace('-ndrpdr', '').
                      replace('2n1l-', ''))
        x_vals.append(name)  # dir 1
        y_vals.append(mean(val[1]) if val[1] else None)
        y_mins.append(mean(val[0]) if val[0] else None)
        y_maxs.append(mean(val[2]) if val[2] else None)
        nr_of_samples.append(len(val[1]) if val[1] else 0)
        x_vals.append(name)  # dir 2
        y_vals.append(mean(val[4]) if val[4] else None)
        y_mins.append(mean(val[3]) if val[3] else None)
        y_maxs.append(mean(val[5]) if val[5] else None)
        nr_of_samples.append(len(val[3]) if val[3] else 0)

    traces = list()
    annotations = list()

    for idx in range(len(x_vals)):
        if not bool(int(idx % 2)):
            direction = "West-East"
        else:
            direction = "East-West"
        hovertext = ("No. of Runs: {nr}<br>"
                     "Test: {test}<br>"
                     "Direction: {dir}<br>".format(test=x_vals[idx],
                                                   dir=direction,
                                                   nr=nr_of_samples[idx]))
        if isinstance(y_maxs[idx], float):
            hovertext += "Max: {max:.2f}uSec<br>".format(max=y_maxs[idx])
        if isinstance(y_vals[idx], float):
            hovertext += "Mean: {avg:.2f}uSec<br>".format(avg=y_vals[idx])
        if isinstance(y_mins[idx], float):
            hovertext += "Min: {min:.2f}uSec".format(min=y_mins[idx])

        if isinstance(y_maxs[idx], float) and isinstance(y_vals[idx], float):
            array = [y_maxs[idx] - y_vals[idx], ]
        else:
            array = [None, ]
        if isinstance(y_mins[idx], float) and isinstance(y_vals[idx], float):
            arrayminus = [y_vals[idx] - y_mins[idx], ]
        else:
            arrayminus = [None, ]
        traces.append(plgo.Scatter(
            x=[idx, ],
            y=[y_vals[idx], ],
            name=x_vals[idx],
            legendgroup=x_vals[idx],
            showlegend=bool(int(idx % 2)),
            mode="markers",
            error_y=dict(
                type='data',
                symmetric=False,
                array=array,
                arrayminus=arrayminus,
                color=COLORS[int(idx / 2)]
            ),
            marker=dict(
                size=10,
                color=COLORS[int(idx / 2)],
            ),
            text=hovertext,
            hoverinfo="text",
        ))
        annotations.append(dict(
            x=idx,
            y=0,
            xref="x",
            yref="y",
            xanchor="center",
            yanchor="top",
            text="E-W" if bool(int(idx % 2)) else "W-E",
            font=dict(
                size=16,
            ),
            align="center",
            showarrow=False
        ))

    try:
        # Create plot
        file_type = plot.get("output-file-type", ".html")
        logging.info("    Writing file '{0}{1}'.".
                     format(plot["output-file"], file_type))
        layout = deepcopy(plot["layout"])
        if layout.get("title", None):
            layout["title"] = "<b>Latency:</b> {0}".\
                format(layout["title"])
        layout["annotations"] = annotations
        plpl = plgo.Figure(data=traces, layout=layout)

        # Export Plot
        ploff.plot(plpl,
                   show_link=False, auto_open=False,
                   filename='{0}{1}'.format(plot["output-file"], file_type))
    except PlotlyError as err:
        logging.error("   Finished with error: {}".
                      format(str(err).replace("\n", " ")))
        return


def plot_throughput_speedup_analysis_name(plot, input_data):
    """Generate the plot(s) with algorithm:
    plot_throughput_speedup_analysis_name
    specified in the specification file.

    :param plot: Plot to generate.
    :param input_data: Data to process.
    :type plot: pandas.Series
    :type input_data: InputData
    """

    # Transform the data
    plot_title = plot.get("title", "")
    logging.info("    Creating the data set for the {0} '{1}'.".
                 format(plot.get("type", ""), plot_title))
    data = input_data.filter_tests_by_name(
        plot, params=["throughput", "parent", "tags", "type"])
    if data is None:
        logging.error("No data.")
        return

    y_vals = OrderedDict()
    for job in data:
        for build in job:
            for test in build:
                if y_vals.get(test["parent"], None) is None:
                    y_vals[test["parent"]] = {"1": list(),
                                              "2": list(),
                                              "4": list()}
                try:
                    if test["type"] in ("NDRPDR",):
                        if "-pdr" in plot_title.lower():
                            ttype = "PDR"
                        elif "-ndr" in plot_title.lower():
                            ttype = "NDR"
                        else:
                            continue
                        if "1C" in test["tags"]:
                            y_vals[test["parent"]]["1"]. \
                                append(test["throughput"][ttype]["LOWER"])
                        elif "2C" in test["tags"]:
                            y_vals[test["parent"]]["2"]. \
                                append(test["throughput"][ttype]["LOWER"])
                        elif "4C" in test["tags"]:
                            y_vals[test["parent"]]["4"]. \
                                append(test["throughput"][ttype]["LOWER"])
                except (KeyError, TypeError):
                    pass

    if not y_vals:
        logging.warning("No data for the plot '{}'".
                        format(plot.get("title", "")))
        return

    y_1c_max = dict()
    for test_name, test_vals in y_vals.items():
        for key, test_val in test_vals.items():
            if test_val:
                avg_val = sum(test_val) / len(test_val)
                y_vals[test_name][key] = (avg_val, len(test_val))
                ideal = avg_val / (int(key) * 1000000.0)
                if test_name not in y_1c_max or ideal > y_1c_max[test_name]:
                    y_1c_max[test_name] = ideal

    vals = OrderedDict()
    y_max = list()
    nic_limit = 0
    lnk_limit = 0
    pci_limit = plot["limits"]["pci"]["pci-g3-x8"]
    for test_name, test_vals in y_vals.items():
        try:
            if test_vals["1"][1]:
                name = re.sub(REGEX_NIC, "", test_name.replace('-ndrpdr', '').
                              replace('2n1l-', ''))
                vals[name] = OrderedDict()
                y_val_1 = test_vals["1"][0] / 1000000.0
                y_val_2 = test_vals["2"][0] / 1000000.0 if test_vals["2"][0] \
                    else None
                y_val_4 = test_vals["4"][0] / 1000000.0 if test_vals["4"][0] \
                    else None

                vals[name]["val"] = [y_val_1, y_val_2, y_val_4]
                vals[name]["rel"] = [1.0, None, None]
                vals[name]["ideal"] = [y_1c_max[test_name],
                                       y_1c_max[test_name] * 2,
                                       y_1c_max[test_name] * 4]
                vals[name]["diff"] = [(y_val_1 - y_1c_max[test_name]) * 100 /
                                      y_val_1, None, None]
                vals[name]["count"] = [test_vals["1"][1],
                                       test_vals["2"][1],
                                       test_vals["4"][1]]

                try:
                    val_max = max(vals[name]["val"])
                except ValueError as err:
                    logging.error(repr(err))
                    continue
                if val_max:
                    y_max.append(val_max)

                if y_val_2:
                    vals[name]["rel"][1] = round(y_val_2 / y_val_1, 2)
                    vals[name]["diff"][1] = \
                        (y_val_2 - vals[name]["ideal"][1]) * 100 / y_val_2
                if y_val_4:
                    vals[name]["rel"][2] = round(y_val_4 / y_val_1, 2)
                    vals[name]["diff"][2] = \
                        (y_val_4 - vals[name]["ideal"][2]) * 100 / y_val_4
        except IndexError as err:
            logging.warning("No data for '{0}'".format(test_name))
            logging.warning(repr(err))

        # Limits:
        if "x520" in test_name:
            limit = plot["limits"]["nic"]["x520"]
        elif "x710" in test_name:
            limit = plot["limits"]["nic"]["x710"]
        elif "xxv710" in test_name:
            limit = plot["limits"]["nic"]["xxv710"]
        elif "xl710" in test_name:
            limit = plot["limits"]["nic"]["xl710"]
        elif "x553" in test_name:
            limit = plot["limits"]["nic"]["x553"]
        else:
            limit = 0
        if limit > nic_limit:
            nic_limit = limit

        mul = 2 if "ge2p" in test_name else 1
        if "10ge" in test_name:
            limit = plot["limits"]["link"]["10ge"] * mul
        elif "25ge" in test_name:
            limit = plot["limits"]["link"]["25ge"] * mul
        elif "40ge" in test_name:
            limit = plot["limits"]["link"]["40ge"] * mul
        elif "100ge" in test_name:
            limit = plot["limits"]["link"]["100ge"] * mul
        else:
            limit = 0
        if limit > lnk_limit:
            lnk_limit = limit

    traces = list()
    annotations = list()
    x_vals = [1, 2, 4]

    # Limits:
    try:
        threshold = 1.1 * max(y_max)  # 10%
    except ValueError as err:
        logging.error(err)
        return
    nic_limit /= 1000000.0
    traces.append(plgo.Scatter(
        x=x_vals,
        y=[nic_limit, ] * len(x_vals),
        name="NIC: {0:.2f}Mpps".format(nic_limit),
        showlegend=False,
        mode="lines",
        line=dict(
            dash="dot",
            color=COLORS[-1],
            width=1),
        hoverinfo="none"
    ))
    annotations.append(dict(
        x=1,
        y=nic_limit,
        xref="x",
        yref="y",
        xanchor="left",
        yanchor="bottom",
        text="NIC: {0:.2f}Mpps".format(nic_limit),
        font=dict(
            size=14,
            color=COLORS[-1],
        ),
        align="left",
        showarrow=False
    ))
    y_max.append(nic_limit)

    lnk_limit /= 1000000.0
    if lnk_limit < threshold:
        traces.append(plgo.Scatter(
            x=x_vals,
            y=[lnk_limit, ] * len(x_vals),
            name="Link: {0:.2f}Mpps".format(lnk_limit),
            showlegend=False,
            mode="lines",
            line=dict(
                dash="dot",
                color=COLORS[-2],
                width=1),
            hoverinfo="none"
        ))
        annotations.append(dict(
            x=1,
            y=lnk_limit,
            xref="x",
            yref="y",
            xanchor="left",
            yanchor="bottom",
            text="Link: {0:.2f}Mpps".format(lnk_limit),
            font=dict(
                size=14,
                color=COLORS[-2],
            ),
            align="left",
            showarrow=False
        ))
        y_max.append(lnk_limit)

    pci_limit /= 1000000.0
    if (pci_limit < threshold and
        (pci_limit < lnk_limit * 0.95 or lnk_limit > lnk_limit * 1.05)):
        traces.append(plgo.Scatter(
            x=x_vals,
            y=[pci_limit, ] * len(x_vals),
            name="PCIe: {0:.2f}Mpps".format(pci_limit),
            showlegend=False,
            mode="lines",
            line=dict(
                dash="dot",
                color=COLORS[-3],
                width=1),
            hoverinfo="none"
        ))
        annotations.append(dict(
            x=1,
            y=pci_limit,
            xref="x",
            yref="y",
            xanchor="left",
            yanchor="bottom",
            text="PCIe: {0:.2f}Mpps".format(pci_limit),
            font=dict(
                size=14,
                color=COLORS[-3],
            ),
            align="left",
            showarrow=False
        ))
        y_max.append(pci_limit)

    # Perfect and measured:
    cidx = 0
    for name, val in vals.iteritems():
        hovertext = list()
        try:
            for idx in range(len(val["val"])):
                htext = ""
                if isinstance(val["val"][idx], float):
                    htext += "No. of Runs: {1}<br>" \
                             "Mean: {0:.2f}Mpps<br>".format(val["val"][idx],
                                                            val["count"][idx])
                if isinstance(val["diff"][idx], float):
                    htext += "Diff: {0:.0f}%<br>".format(
                        round(val["diff"][idx]))
                if isinstance(val["rel"][idx], float):
                    htext += "Speedup: {0:.2f}".format(val["rel"][idx])
                hovertext.append(htext)
            traces.append(plgo.Scatter(x=x_vals,
                                       y=val["val"],
                                       name=name,
                                       legendgroup=name,
                                       mode="lines+markers",
                                       line=dict(
                                           color=COLORS[cidx],
                                           width=2),
                                       marker=dict(
                                           symbol="circle",
                                           size=10
                                       ),
                                       text=hovertext,
                                       hoverinfo="text+name"
                                       ))
            traces.append(plgo.Scatter(x=x_vals,
                                       y=val["ideal"],
                                       name="{0} perfect".format(name),
                                       legendgroup=name,
                                       showlegend=False,
                                       mode="lines",
                                       line=dict(
                                           color=COLORS[cidx],
                                           width=2,
                                           dash="dash"),
                                       text=["Perfect: {0:.2f}Mpps".format(y)
                                             for y in val["ideal"]],
                                       hoverinfo="text"
                                       ))
            cidx += 1
        except (IndexError, ValueError, KeyError) as err:
            logging.warning("No data for '{0}'".format(name))
            logging.warning(repr(err))

    try:
        # Create plot
        file_type = plot.get("output-file-type", ".html")
        logging.info("    Writing file '{0}{1}'.".
                     format(plot["output-file"], file_type))
        layout = deepcopy(plot["layout"])
        if layout.get("title", None):
            layout["title"] = "<b>Speedup Multi-core:</b> {0}". \
                format(layout["title"])
        layout["yaxis"]["range"] = [0, int(max(y_max) * 1.1)]
        layout["annotations"].extend(annotations)
        plpl = plgo.Figure(data=traces, layout=layout)

        # Export Plot
        ploff.plot(plpl,
                   show_link=False, auto_open=False,
                   filename='{0}{1}'.format(plot["output-file"], file_type))
    except PlotlyError as err:
        logging.error("   Finished with error: {}".
                      format(repr(err).replace("\n", " ")))
        return


def plot_performance_box(plot, input_data):
    """Generate the plot(s) with algorithm: plot_performance_box
    specified in the specification file.

    TODO: Remove when not needed.

    :param plot: Plot to generate.
    :param input_data: Data to process.
    :type plot: pandas.Series
    :type input_data: InputData
    """

    # Transform the data
    plot_title = plot.get("title", "")
    logging.info("    Creating the data set for the {0} '{1}'.".
                 format(plot.get("type", ""), plot_title))
    data = input_data.filter_data(plot)
    if data is None:
        logging.error("No data.")
        return

    # Prepare the data for the plot
    y_vals = dict()
    y_tags = dict()
    for job in data:
        for build in job:
            for test in build:
                if y_vals.get(test["parent"], None) is None:
                    y_vals[test["parent"]] = list()
                    y_tags[test["parent"]] = test.get("tags", None)
                try:
                    if test["type"] in ("NDRPDR", ):
                        if "-pdr" in plot_title.lower():
                            y_vals[test["parent"]].\
                                append(test["throughput"]["PDR"]["LOWER"])
                        elif "-ndr" in plot_title.lower():
                            y_vals[test["parent"]]. \
                                append(test["throughput"]["NDR"]["LOWER"])
                        else:
                            continue
                    elif test["type"] in ("SOAK", ):
                        y_vals[test["parent"]].\
                            append(test["throughput"]["LOWER"])
                    else:
                        continue
                except (KeyError, TypeError):
                    y_vals[test["parent"]].append(None)

    # Sort the tests
    order = plot.get("sort", None)
    if order and y_tags:
        y_sorted = OrderedDict()
        y_tags_l = {s: [t.lower() for t in ts] for s, ts in y_tags.items()}
        for tag in order:
            logging.debug(tag)
            for suite, tags in y_tags_l.items():
                if "not " in tag:
                    tag = tag.split(" ")[-1]
                    if tag.lower() in tags:
                        continue
                else:
                    if tag.lower() not in tags:
                        continue
                try:
                    y_sorted[suite] = y_vals.pop(suite)
                    y_tags_l.pop(suite)
                    logging.debug(suite)
                except KeyError as err:
                    logging.error("Not found: {0}".format(repr(err)))
                finally:
                    break
    else:
        y_sorted = y_vals

    # Add None to the lists with missing data
    max_len = 0
    nr_of_samples = list()
    for val in y_sorted.values():
        if len(val) > max_len:
            max_len = len(val)
        nr_of_samples.append(len(val))
    for key, val in y_sorted.items():
        if len(val) < max_len:
            val.extend([None for _ in range(max_len - len(val))])

    # Add plot traces
    traces = list()
    df = pd.DataFrame(y_sorted)
    df.head()
    y_max = list()
    for i, col in enumerate(df.columns):
        tst_name = re.sub(REGEX_NIC, "",
                          col.lower().replace('-ndrpdr', '').
                          replace('2n1l-', ''))
        name = "{nr}. ({samples:02d} run{plural}) {name}".\
            format(nr=(i + 1),
                   samples=nr_of_samples[i],
                   plural='s' if nr_of_samples[i] > 1 else '',
                   name=tst_name)

        logging.debug(name)
        traces.append(plgo.Box(x=[str(i + 1) + '.'] * len(df[col]),
                               y=[y / 1000000 if y else None for y in df[col]],
                               name=name,
                               **plot["traces"]))
        try:
            val_max = max(df[col])
        except ValueError as err:
            logging.error(repr(err))
            continue
        if val_max:
            y_max.append(int(val_max / 1000000) + 2)

    try:
        # Create plot
        layout = deepcopy(plot["layout"])
        if layout.get("title", None):
            layout["title"] = "<b>Throughput:</b> {0}". \
                format(layout["title"])
        if y_max:
            layout["yaxis"]["range"] = [0, max(y_max)]
        plpl = plgo.Figure(data=traces, layout=layout)

        # Export Plot
        logging.info("    Writing file '{0}{1}'.".
                     format(plot["output-file"], plot["output-file-type"]))
        ploff.plot(plpl, show_link=False, auto_open=False,
                   filename='{0}{1}'.format(plot["output-file"],
                                            plot["output-file-type"]))
    except PlotlyError as err:
        logging.error("   Finished with error: {}".
                      format(repr(err).replace("\n", " ")))
        return


def plot_soak_bars(plot, input_data):
    """Generate the plot(s) with algorithm: plot_soak_bars
    specified in the specification file.

    :param plot: Plot to generate.
    :param input_data: Data to process.
    :type plot: pandas.Series
    :type input_data: InputData
    """

    # Transform the data
    plot_title = plot.get("title", "")
    logging.info("    Creating the data set for the {0} '{1}'.".
                 format(plot.get("type", ""), plot_title))
    data = input_data.filter_data(plot)
    if data is None:
        logging.error("No data.")
        return

    # Prepare the data for the plot
    y_vals = dict()
    y_tags = dict()
    for job in data:
        for build in job:
            for test in build:
                if y_vals.get(test["parent"], None) is None:
                    y_tags[test["parent"]] = test.get("tags", None)
                try:
                    if test["type"] in ("SOAK", ):
                        y_vals[test["parent"]] = test["throughput"]
                    else:
                        continue
                except (KeyError, TypeError):
                    y_vals[test["parent"]] = dict()

    # Sort the tests
    order = plot.get("sort", None)
    if order and y_tags:
        y_sorted = OrderedDict()
        y_tags_l = {s: [t.lower() for t in ts] for s, ts in y_tags.items()}
        for tag in order:
            logging.debug(tag)
            for suite, tags in y_tags_l.items():
                if "not " in tag:
                    tag = tag.split(" ")[-1]
                    if tag.lower() in tags:
                        continue
                else:
                    if tag.lower() not in tags:
                        continue
                try:
                    y_sorted[suite] = y_vals.pop(suite)
                    y_tags_l.pop(suite)
                    logging.debug(suite)
                except KeyError as err:
                    logging.error("Not found: {0}".format(repr(err)))
                finally:
                    break
    else:
        y_sorted = y_vals

    idx = 0
    y_max = 0
    traces = list()
    for test_name, test_data in y_sorted.items():
        idx += 1
        name = "{nr}. {name}".\
            format(nr=idx, name=test_name.lower().replace('-soak', ''))
        if len(name) > 50:
            name_lst = name.split('-')
            name = ""
            split_name = True
            for segment in name_lst:
                if (len(name) + len(segment) + 1) > 50 and split_name:
                    name += "<br>    "
                    split_name = False
                name += segment + '-'
            name = name[:-1]

        y_val = test_data.get("LOWER", None)
        if y_val:
            y_val /= 1000000
            if y_val > y_max:
                y_max = y_val

        time = "No Information"
        result = "No Information"
        hovertext = ("{name}<br>"
                     "Packet Throughput: {val:.2f}Mpps<br>"
                     "Final Duration: {time}<br>"
                     "Result: {result}".format(name=name,
                                               val=y_val,
                                               time=time,
                                               result=result))
        traces.append(plgo.Bar(x=[str(idx) + '.', ],
                               y=[y_val, ],
                               name=name,
                               text=hovertext,
                               hoverinfo="text"))
    try:
        # Create plot
        layout = deepcopy(plot["layout"])
        if layout.get("title", None):
            layout["title"] = "<b>Packet Throughput:</b> {0}". \
                format(layout["title"])
        if y_max:
            layout["yaxis"]["range"] = [0, y_max + 1]
        plpl = plgo.Figure(data=traces, layout=layout)
        # Export Plot
        logging.info("    Writing file '{0}{1}'.".
                     format(plot["output-file"], plot["output-file-type"]))
        ploff.plot(plpl, show_link=False, auto_open=False,
                   filename='{0}{1}'.format(plot["output-file"],
                                            plot["output-file-type"]))
    except PlotlyError as err:
        logging.error("   Finished with error: {}".
                      format(repr(err).replace("\n", " ")))
        return


def plot_soak_boxes(plot, input_data):
    """Generate the plot(s) with algorithm: plot_soak_boxes
    specified in the specification file.

    :param plot: Plot to generate.
    :param input_data: Data to process.
    :type plot: pandas.Series
    :type input_data: InputData
    """

    # Transform the data
    plot_title = plot.get("title", "")
    logging.info("    Creating the data set for the {0} '{1}'.".
                 format(plot.get("type", ""), plot_title))
    data = input_data.filter_data(plot)
    if data is None:
        logging.error("No data.")
        return

    # Prepare the data for the plot
    y_vals = dict()
    y_tags = dict()
    for job in data:
        for build in job:
            for test in build:
                if y_vals.get(test["parent"], None) is None:
                    y_tags[test["parent"]] = test.get("tags", None)
                try:
                    if test["type"] in ("SOAK", ):
                        y_vals[test["parent"]] = test["throughput"]
                    else:
                        continue
                except (KeyError, TypeError):
                    y_vals[test["parent"]] = dict()

    # Sort the tests
    order = plot.get("sort", None)
    if order and y_tags:
        y_sorted = OrderedDict()
        y_tags_l = {s: [t.lower() for t in ts] for s, ts in y_tags.items()}
        for tag in order:
            logging.debug(tag)
            for suite, tags in y_tags_l.items():
                if "not " in tag:
                    tag = tag.split(" ")[-1]
                    if tag.lower() in tags:
                        continue
                else:
                    if tag.lower() not in tags:
                        continue
                try:
                    y_sorted[suite] = y_vals.pop(suite)
                    y_tags_l.pop(suite)
                    logging.debug(suite)
                except KeyError as err:
                    logging.error("Not found: {0}".format(repr(err)))
                finally:
                    break
    else:
        y_sorted = y_vals

    idx = 0
    y_max = 0
    traces = list()
    for test_name, test_data in y_sorted.items():
        idx += 1
        name = "{nr}. {name}".\
            format(nr=idx, name=test_name.lower().replace('-soak', '').
                   replace('2n1l-', ''))
        if len(name) > 55:
            name_lst = name.split('-')
            name = ""
            split_name = True
            for segment in name_lst:
                if (len(name) + len(segment) + 1) > 55 and split_name:
                    name += "<br>    "
                    split_name = False
                name += segment + '-'
            name = name[:-1]

        y_val = test_data.get("UPPER", None)
        if y_val:
            y_val /= 1000000
            if y_val > y_max:
                y_max = y_val

        y_base = test_data.get("LOWER", None)
        if y_base:
            y_base /= 1000000

        hovertext = ("Upper bound: {upper:.2f}<br>"
                     "Lower bound: {lower:.2f}".format(upper=y_val,
                                                           lower=y_base))
        traces.append(plgo.Bar(x=[str(idx) + '.', ],
                               # +0.05 to see the value in case lower == upper
                               y=[y_val - y_base + 0.05, ],
                               base=y_base,
                               name=name,
                               text=hovertext,
                               hoverinfo="text"))
    try:
        # Create plot
        layout = deepcopy(plot["layout"])
        if layout.get("title", None):
            layout["title"] = "<b>Throughput:</b> {0}". \
                format(layout["title"])
        if y_max:
            layout["yaxis"]["range"] = [0, y_max + 1]
        plpl = plgo.Figure(data=traces, layout=layout)
        # Export Plot
        logging.info("    Writing file '{0}{1}'.".
                     format(plot["output-file"], plot["output-file-type"]))
        ploff.plot(plpl, show_link=False, auto_open=False,
                   filename='{0}{1}'.format(plot["output-file"],
                                            plot["output-file-type"]))
    except PlotlyError as err:
        logging.error("   Finished with error: {}".
                      format(repr(err).replace("\n", " ")))
        return


def plot_latency_error_bars(plot, input_data):
    """Generate the plot(s) with algorithm: plot_latency_error_bars
    specified in the specification file.

    TODO: Remove when not needed.

    :param plot: Plot to generate.
    :param input_data: Data to process.
    :type plot: pandas.Series
    :type input_data: InputData
    """

    # Transform the data
    plot_title = plot.get("title", "")
    logging.info("    Creating the data set for the {0} '{1}'.".
                 format(plot.get("type", ""), plot_title))
    data = input_data.filter_data(plot)
    if data is None:
        logging.error("No data.")
        return

    # Prepare the data for the plot
    y_tmp_vals = dict()
    y_tags = dict()
    for job in data:
        for build in job:
            for test in build:
                try:
                    logging.debug("test['latency']: {0}\n".
                                 format(test["latency"]))
                except ValueError as err:
                    logging.warning(repr(err))
                if y_tmp_vals.get(test["parent"], None) is None:
                    y_tmp_vals[test["parent"]] = [
                        list(),  # direction1, min
                        list(),  # direction1, avg
                        list(),  # direction1, max
                        list(),  # direction2, min
                        list(),  # direction2, avg
                        list()   # direction2, max
                    ]
                    y_tags[test["parent"]] = test.get("tags", None)
                try:
                    if test["type"] in ("NDRPDR", ):
                        if "-pdr" in plot_title.lower():
                            ttype = "PDR"
                        elif "-ndr" in plot_title.lower():
                            ttype = "NDR"
                        else:
                            logging.warning("Invalid test type: {0}".
                                            format(test["type"]))
                            continue
                        y_tmp_vals[test["parent"]][0].append(
                            test["latency"][ttype]["direction1"]["min"])
                        y_tmp_vals[test["parent"]][1].append(
                            test["latency"][ttype]["direction1"]["avg"])
                        y_tmp_vals[test["parent"]][2].append(
                            test["latency"][ttype]["direction1"]["max"])
                        y_tmp_vals[test["parent"]][3].append(
                            test["latency"][ttype]["direction2"]["min"])
                        y_tmp_vals[test["parent"]][4].append(
                            test["latency"][ttype]["direction2"]["avg"])
                        y_tmp_vals[test["parent"]][5].append(
                            test["latency"][ttype]["direction2"]["max"])
                    else:
                        logging.warning("Invalid test type: {0}".
                                        format(test["type"]))
                        continue
                except (KeyError, TypeError) as err:
                    logging.warning(repr(err))
    logging.debug("y_tmp_vals: {0}\n".format(y_tmp_vals))

    # Sort the tests
    order = plot.get("sort", None)
    if order and y_tags:
        y_sorted = OrderedDict()
        y_tags_l = {s: [t.lower() for t in ts] for s, ts in y_tags.items()}
        for tag in order:
            logging.debug(tag)
            for suite, tags in y_tags_l.items():
                if "not " in tag:
                    tag = tag.split(" ")[-1]
                    if tag.lower() in tags:
                        continue
                else:
                    if tag.lower() not in tags:
                        continue
                try:
                    y_sorted[suite] = y_tmp_vals.pop(suite)
                    y_tags_l.pop(suite)
                    logging.debug(suite)
                except KeyError as err:
                    logging.error("Not found: {0}".format(repr(err)))
                finally:
                    break
    else:
        y_sorted = y_tmp_vals

    logging.debug("y_sorted: {0}\n".format(y_sorted))
    x_vals = list()
    y_vals = list()
    y_mins = list()
    y_maxs = list()
    nr_of_samples = list()
    for key, val in y_sorted.items():
        name = re.sub(REGEX_NIC, "", key.replace('-ndrpdr', '').
                      replace('2n1l-', ''))
        x_vals.append(name)  # dir 1
        y_vals.append(mean(val[1]) if val[1] else None)
        y_mins.append(mean(val[0]) if val[0] else None)
        y_maxs.append(mean(val[2]) if val[2] else None)
        nr_of_samples.append(len(val[1]) if val[1] else 0)
        x_vals.append(name)  # dir 2
        y_vals.append(mean(val[4]) if val[4] else None)
        y_mins.append(mean(val[3]) if val[3] else None)
        y_maxs.append(mean(val[5]) if val[5] else None)
        nr_of_samples.append(len(val[3]) if val[3] else 0)

    logging.debug("x_vals :{0}\n".format(x_vals))
    logging.debug("y_vals :{0}\n".format(y_vals))
    logging.debug("y_mins :{0}\n".format(y_mins))
    logging.debug("y_maxs :{0}\n".format(y_maxs))
    logging.debug("nr_of_samples :{0}\n".format(nr_of_samples))
    traces = list()
    annotations = list()

    for idx in range(len(x_vals)):
        if not bool(int(idx % 2)):
            direction = "West-East"
        else:
            direction = "East-West"
        hovertext = ("No. of Runs: {nr}<br>"
                     "Test: {test}<br>"
                     "Direction: {dir}<br>".format(test=x_vals[idx],
                                                   dir=direction,
                                                   nr=nr_of_samples[idx]))
        if isinstance(y_maxs[idx], float):
            hovertext += "Max: {max:.2f}uSec<br>".format(max=y_maxs[idx])
        if isinstance(y_vals[idx], float):
            hovertext += "Mean: {avg:.2f}uSec<br>".format(avg=y_vals[idx])
        if isinstance(y_mins[idx], float):
            hovertext += "Min: {min:.2f}uSec".format(min=y_mins[idx])

        if isinstance(y_maxs[idx], float) and isinstance(y_vals[idx], float):
            array = [y_maxs[idx] - y_vals[idx], ]
        else:
            array = [None, ]
        if isinstance(y_mins[idx], float) and isinstance(y_vals[idx], float):
            arrayminus = [y_vals[idx] - y_mins[idx], ]
        else:
            arrayminus = [None, ]
        logging.debug("y_vals[{1}] :{0}\n".format(y_vals[idx], idx))
        logging.debug("array :{0}\n".format(array))
        logging.debug("arrayminus :{0}\n".format(arrayminus))
        traces.append(plgo.Scatter(
            x=[idx, ],
            y=[y_vals[idx], ],
            name=x_vals[idx],
            legendgroup=x_vals[idx],
            showlegend=bool(int(idx % 2)),
            mode="markers",
            error_y=dict(
                type='data',
                symmetric=False,
                array=array,
                arrayminus=arrayminus,
                color=COLORS[int(idx / 2)]
            ),
            marker=dict(
                size=10,
                color=COLORS[int(idx / 2)],
            ),
            text=hovertext,
            hoverinfo="text",
        ))
        annotations.append(dict(
            x=idx,
            y=0,
            xref="x",
            yref="y",
            xanchor="center",
            yanchor="top",
            text="E-W" if bool(int(idx % 2)) else "W-E",
            font=dict(
                size=16,
            ),
            align="center",
            showarrow=False
        ))

    try:
        # Create plot
        logging.info("    Writing file '{0}{1}'.".
                     format(plot["output-file"], plot["output-file-type"]))
        layout = deepcopy(plot["layout"])
        if layout.get("title", None):
            layout["title"] = "<b>Latency:</b> {0}".\
                format(layout["title"])
        layout["annotations"] = annotations
        plpl = plgo.Figure(data=traces, layout=layout)

        # Export Plot
        ploff.plot(plpl,
                   show_link=False, auto_open=False,
                   filename='{0}{1}'.format(plot["output-file"],
                                            plot["output-file-type"]))
    except PlotlyError as err:
        logging.error("   Finished with error: {}".
                      format(str(err).replace("\n", " ")))
        return


def plot_throughput_speedup_analysis(plot, input_data):
    """Generate the plot(s) with algorithm:
    plot_throughput_speedup_analysis
    specified in the specification file.

    TODO: Remove when not needed.

    :param plot: Plot to generate.
    :param input_data: Data to process.
    :type plot: pandas.Series
    :type input_data: InputData
    """

    # Transform the data
    plot_title = plot.get("title", "")
    logging.info("    Creating the data set for the {0} '{1}'.".
                 format(plot.get("type", ""), plot_title))
    data = input_data.filter_data(plot)
    if data is None:
        logging.error("No data.")
        return

    y_vals = dict()
    y_tags = dict()
    for job in data:
        for build in job:
            for test in build:
                if y_vals.get(test["parent"], None) is None:
                    y_vals[test["parent"]] = {"1": list(),
                                              "2": list(),
                                              "4": list()}
                    y_tags[test["parent"]] = test.get("tags", None)
                try:
                    if test["type"] in ("NDRPDR",):
                        if "-pdr" in plot_title.lower():
                            ttype = "PDR"
                        elif "-ndr" in plot_title.lower():
                            ttype = "NDR"
                        else:
                            continue
                        if "1C" in test["tags"]:
                            y_vals[test["parent"]]["1"]. \
                                append(test["throughput"][ttype]["LOWER"])
                        elif "2C" in test["tags"]:
                            y_vals[test["parent"]]["2"]. \
                                append(test["throughput"][ttype]["LOWER"])
                        elif "4C" in test["tags"]:
                            y_vals[test["parent"]]["4"]. \
                                append(test["throughput"][ttype]["LOWER"])
                except (KeyError, TypeError):
                    pass

    if not y_vals:
        logging.warning("No data for the plot '{}'".
                        format(plot.get("title", "")))
        return

    y_1c_max = dict()
    for test_name, test_vals in y_vals.items():
        for key, test_val in test_vals.items():
            if test_val:
                avg_val = sum(test_val) / len(test_val)
                y_vals[test_name][key] = (avg_val, len(test_val))
                ideal = avg_val / (int(key) * 1000000.0)
                if test_name not in y_1c_max or ideal > y_1c_max[test_name]:
                    y_1c_max[test_name] = ideal

    vals = dict()
    y_max = list()
    nic_limit = 0
    lnk_limit = 0
    pci_limit = plot["limits"]["pci"]["pci-g3-x8"]
    for test_name, test_vals in y_vals.items():
        try:
            if test_vals["1"][1]:
                name = re.sub(REGEX_NIC, "", test_name.replace('-ndrpdr', '').
                              replace('2n1l-', ''))
                vals[name] = dict()
                y_val_1 = test_vals["1"][0] / 1000000.0
                y_val_2 = test_vals["2"][0] / 1000000.0 if test_vals["2"][0] \
                    else None
                y_val_4 = test_vals["4"][0] / 1000000.0 if test_vals["4"][0] \
                    else None

                vals[name]["val"] = [y_val_1, y_val_2, y_val_4]
                vals[name]["rel"] = [1.0, None, None]
                vals[name]["ideal"] = [y_1c_max[test_name],
                                       y_1c_max[test_name] * 2,
                                       y_1c_max[test_name] * 4]
                vals[name]["diff"] = [(y_val_1 - y_1c_max[test_name]) * 100 /
                                      y_val_1, None, None]
                vals[name]["count"] = [test_vals["1"][1],
                                       test_vals["2"][1],
                                       test_vals["4"][1]]

                try:
                    # val_max = max(max(vals[name]["val"], vals[name]["ideal"]))
                    val_max = max(vals[name]["val"])
                except ValueError as err:
                    logging.error(err)
                    continue
                if val_max:
                    # y_max.append(int((val_max / 10) + 1) * 10)
                    y_max.append(val_max)

                if y_val_2:
                    vals[name]["rel"][1] = round(y_val_2 / y_val_1, 2)
                    vals[name]["diff"][1] = \
                        (y_val_2 - vals[name]["ideal"][1]) * 100 / y_val_2
                if y_val_4:
                    vals[name]["rel"][2] = round(y_val_4 / y_val_1, 2)
                    vals[name]["diff"][2] = \
                        (y_val_4 - vals[name]["ideal"][2]) * 100 / y_val_4
        except IndexError as err:
            logging.warning("No data for '{0}'".format(test_name))
            logging.warning(repr(err))

        # Limits:
        if "x520" in test_name:
            limit = plot["limits"]["nic"]["x520"]
        elif "x710" in test_name:
            limit = plot["limits"]["nic"]["x710"]
        elif "xxv710" in test_name:
            limit = plot["limits"]["nic"]["xxv710"]
        elif "xl710" in test_name:
            limit = plot["limits"]["nic"]["xl710"]
        elif "x553" in test_name:
            limit = plot["limits"]["nic"]["x553"]
        else:
            limit = 0
        if limit > nic_limit:
            nic_limit = limit

        mul = 2 if "ge2p" in test_name else 1
        if "10ge" in test_name:
            limit = plot["limits"]["link"]["10ge"] * mul
        elif "25ge" in test_name:
            limit = plot["limits"]["link"]["25ge"] * mul
        elif "40ge" in test_name:
            limit = plot["limits"]["link"]["40ge"] * mul
        elif "100ge" in test_name:
            limit = plot["limits"]["link"]["100ge"] * mul
        else:
            limit = 0
        if limit > lnk_limit:
            lnk_limit = limit

    # Sort the tests
    order = plot.get("sort", None)
    if order and y_tags:
        y_sorted = OrderedDict()
        y_tags_l = {s: [t.lower() for t in ts] for s, ts in y_tags.items()}
        for tag in order:
            for test, tags in y_tags_l.items():
                if tag.lower() in tags:
                    name = re.sub(REGEX_NIC, "",
                                  test.replace('-ndrpdr', '').
                                  replace('2n1l-', ''))
                    try:
                        y_sorted[name] = vals.pop(name)
                        y_tags_l.pop(test)
                    except KeyError as err:
                        logging.error("Not found: {0}".format(err))
                    finally:
                        break
    else:
        y_sorted = vals

    traces = list()
    annotations = list()
    x_vals = [1, 2, 4]

    # Limits:
    try:
        threshold = 1.1 * max(y_max)  # 10%
    except ValueError as err:
        logging.error(err)
        return
    nic_limit /= 1000000.0
    # if nic_limit < threshold:
    traces.append(plgo.Scatter(
        x=x_vals,
        y=[nic_limit, ] * len(x_vals),
        name="NIC: {0:.2f}Mpps".format(nic_limit),
        showlegend=False,
        mode="lines",
        line=dict(
            dash="dot",
            color=COLORS[-1],
            width=1),
        hoverinfo="none"
    ))
    annotations.append(dict(
        x=1,
        y=nic_limit,
        xref="x",
        yref="y",
        xanchor="left",
        yanchor="bottom",
        text="NIC: {0:.2f}Mpps".format(nic_limit),
        font=dict(
            size=14,
            color=COLORS[-1],
        ),
        align="left",
        showarrow=False
    ))
    # y_max.append(int((nic_limit / 10) + 1) * 10)
    y_max.append(nic_limit)

    lnk_limit /= 1000000.0
    if lnk_limit < threshold:
        traces.append(plgo.Scatter(
            x=x_vals,
            y=[lnk_limit, ] * len(x_vals),
            name="Link: {0:.2f}Mpps".format(lnk_limit),
            showlegend=False,
            mode="lines",
            line=dict(
                dash="dot",
                color=COLORS[-2],
                width=1),
            hoverinfo="none"
        ))
        annotations.append(dict(
            x=1,
            y=lnk_limit,
            xref="x",
            yref="y",
            xanchor="left",
            yanchor="bottom",
            text="Link: {0:.2f}Mpps".format(lnk_limit),
            font=dict(
                size=14,
                color=COLORS[-2],
            ),
            align="left",
            showarrow=False
        ))
        # y_max.append(int((lnk_limit / 10) + 1) * 10)
        y_max.append(lnk_limit)

    pci_limit /= 1000000.0
    if (pci_limit < threshold and
        (pci_limit < lnk_limit * 0.95 or lnk_limit > lnk_limit * 1.05)):
        traces.append(plgo.Scatter(
            x=x_vals,
            y=[pci_limit, ] * len(x_vals),
            name="PCIe: {0:.2f}Mpps".format(pci_limit),
            showlegend=False,
            mode="lines",
            line=dict(
                dash="dot",
                color=COLORS[-3],
                width=1),
            hoverinfo="none"
        ))
        annotations.append(dict(
            x=1,
            y=pci_limit,
            xref="x",
            yref="y",
            xanchor="left",
            yanchor="bottom",
            text="PCIe: {0:.2f}Mpps".format(pci_limit),
            font=dict(
                size=14,
                color=COLORS[-3],
            ),
            align="left",
            showarrow=False
        ))
        # y_max.append(int((pci_limit / 10) + 1) * 10)
        y_max.append(pci_limit)

    # Perfect and measured:
    cidx = 0
    for name, val in y_sorted.iteritems():
        hovertext = list()
        try:
            for idx in range(len(val["val"])):
                htext = ""
                if isinstance(val["val"][idx], float):
                    htext += "No. of Runs: {1}<br>" \
                             "Mean: {0:.2f}Mpps<br>".format(val["val"][idx],
                                                            val["count"][idx])
                if isinstance(val["diff"][idx], float):
                    htext += "Diff: {0:.0f}%<br>".format(round(val["diff"][idx]))
                if isinstance(val["rel"][idx], float):
                    htext += "Speedup: {0:.2f}".format(val["rel"][idx])
                hovertext.append(htext)
            traces.append(plgo.Scatter(x=x_vals,
                                       y=val["val"],
                                       name=name,
                                       legendgroup=name,
                                       mode="lines+markers",
                                       line=dict(
                                           color=COLORS[cidx],
                                           width=2),
                                       marker=dict(
                                           symbol="circle",
                                           size=10
                                       ),
                                       text=hovertext,
                                       hoverinfo="text+name"
                                       ))
            traces.append(plgo.Scatter(x=x_vals,
                                       y=val["ideal"],
                                       name="{0} perfect".format(name),
                                       legendgroup=name,
                                       showlegend=False,
                                       mode="lines",
                                       line=dict(
                                           color=COLORS[cidx],
                                           width=2,
                                           dash="dash"),
                                       text=["Perfect: {0:.2f}Mpps".format(y)
                                             for y in val["ideal"]],
                                       hoverinfo="text"
                                       ))
            cidx += 1
        except (IndexError, ValueError, KeyError) as err:
            logging.warning("No data for '{0}'".format(name))
            logging.warning(repr(err))

    try:
        # Create plot
        logging.info("    Writing file '{0}{1}'.".
                     format(plot["output-file"], plot["output-file-type"]))
        layout = deepcopy(plot["layout"])
        if layout.get("title", None):
            layout["title"] = "<b>Speedup Multi-core:</b> {0}". \
                format(layout["title"])
        # layout["yaxis"]["range"] = [0, int((max(y_max) / 10) + 1) * 10]
        layout["yaxis"]["range"] = [0, int(max(y_max) * 1.1)]
        layout["annotations"].extend(annotations)
        plpl = plgo.Figure(data=traces, layout=layout)

        # Export Plot
        ploff.plot(plpl,
                   show_link=False, auto_open=False,
                   filename='{0}{1}'.format(plot["output-file"],
                                            plot["output-file-type"]))
    except PlotlyError as err:
        logging.error("   Finished with error: {}".
                      format(str(err).replace("\n", " ")))
        return


def plot_http_server_performance_box(plot, input_data):
    """Generate the plot(s) with algorithm: plot_http_server_performance_box
    specified in the specification file.

    :param plot: Plot to generate.
    :param input_data: Data to process.
    :type plot: pandas.Series
    :type input_data: InputData
    """

    # Transform the data
    logging.info("    Creating the data set for the {0} '{1}'.".
                 format(plot.get("type", ""), plot.get("title", "")))
    data = input_data.filter_data(plot)
    if data is None:
        logging.error("No data.")
        return

    # Prepare the data for the plot
    y_vals = dict()
    for job in data:
        for build in job:
            for test in build:
                if y_vals.get(test["name"], None) is None:
                    y_vals[test["name"]] = list()
                try:
                    y_vals[test["name"]].append(test["result"])
                except (KeyError, TypeError):
                    y_vals[test["name"]].append(None)

    # Add None to the lists with missing data
    max_len = 0
    nr_of_samples = list()
    for val in y_vals.values():
        if len(val) > max_len:
            max_len = len(val)
        nr_of_samples.append(len(val))
    for key, val in y_vals.items():
        if len(val) < max_len:
            val.extend([None for _ in range(max_len - len(val))])

    # Add plot traces
    traces = list()
    df = pd.DataFrame(y_vals)
    df.head()
    for i, col in enumerate(df.columns):
        name = "{nr}. ({samples:02d} run{plural}) {name}".\
            format(nr=(i + 1),
                   samples=nr_of_samples[i],
                   plural='s' if nr_of_samples[i] > 1 else '',
                   name=col.lower().replace('-ndrpdr', ''))
        if len(name) > 50:
            name_lst = name.split('-')
            name = ""
            split_name = True
            for segment in name_lst:
                if (len(name) + len(segment) + 1) > 50 and split_name:
                    name += "<br>    "
                    split_name = False
                name += segment + '-'
            name = name[:-1]

        traces.append(plgo.Box(x=[str(i + 1) + '.'] * len(df[col]),
                               y=df[col],
                               name=name,
                               **plot["traces"]))
    try:
        # Create plot
        plpl = plgo.Figure(data=traces, layout=plot["layout"])

        # Export Plot
        logging.info("    Writing file '{0}{1}'.".
                     format(plot["output-file"], plot["output-file-type"]))
        ploff.plot(plpl, show_link=False, auto_open=False,
                   filename='{0}{1}'.format(plot["output-file"],
                                            plot["output-file-type"]))
    except PlotlyError as err:
        logging.error("   Finished with error: {}".
                      format(str(err).replace("\n", " ")))
        return


def plot_service_density_heatmap(plot, input_data):
    """Generate the plot(s) with algorithm: plot_service_density_heatmap
    specified in the specification file.

    :param plot: Plot to generate.
    :param input_data: Data to process.
    :type plot: pandas.Series
    :type input_data: InputData
    """

    REGEX_CN = re.compile(r'^(\d*)R(\d*)C$')
    REGEX_TEST_NAME = re.compile(r'^.*-(\d+ch|\d+pl)-'
                                 r'(\d+mif|\d+vh)-'
                                 r'(\d+vm\d+t|\d+dcr\d+t).*$')

    txt_chains = list()
    txt_nodes = list()
    vals = dict()

    # Transform the data
    logging.info("    Creating the data set for the {0} '{1}'.".
                 format(plot.get("type", ""), plot.get("title", "")))
    data = input_data.filter_data(plot, continue_on_error=True)
    if data is None or data.empty:
        logging.error("No data.")
        return

    for job in data:
        for build in job:
            for test in build:
                for tag in test['tags']:
                    groups = re.search(REGEX_CN, tag)
                    if groups:
                        c = str(groups.group(1))
                        n = str(groups.group(2))
                        break
                else:
                    continue
                groups = re.search(REGEX_TEST_NAME, test["name"])
                if groups and len(groups.groups()) == 3:
                    hover_name = "{chain}-{vhost}-{vm}".format(
                        chain=str(groups.group(1)),
                        vhost=str(groups.group(2)),
                        vm=str(groups.group(3)))
                else:
                    hover_name = ""
                if vals.get(c, None) is None:
                    vals[c] = dict()
                if vals[c].get(n, None) is None:
                    vals[c][n] = dict(name=hover_name,
                                      vals=list(),
                                      nr=None,
                                      mean=None,
                                      stdev=None)
                try:
                    if plot["include-tests"] == "MRR":
                        result = test["result"]["receive-rate"].avg
                    elif plot["include-tests"] == "PDR":
                        result = test["throughput"]["PDR"]["LOWER"]
                    elif plot["include-tests"] == "NDR":
                        result = test["throughput"]["NDR"]["LOWER"]
                    else:
                        result = None
                except TypeError:
                    result = None

                if result:
                    vals[c][n]["vals"].append(result)

    if not vals:
        logging.error("No data.")
        return

    for key_c in vals.keys():
        txt_chains.append(key_c)
        for key_n in vals[key_c].keys():
            txt_nodes.append(key_n)
            if vals[key_c][key_n]["vals"]:
                vals[key_c][key_n]["nr"] = len(vals[key_c][key_n]["vals"])
                vals[key_c][key_n]["mean"] = \
                    round(mean(vals[key_c][key_n]["vals"]) / 1000000, 1)
                vals[key_c][key_n]["stdev"] = \
                    round(stdev(vals[key_c][key_n]["vals"]) / 1000000, 1)
    txt_nodes = list(set(txt_nodes))

    txt_chains = sorted(txt_chains, key=lambda chain: int(chain))
    txt_nodes = sorted(txt_nodes, key=lambda node: int(node))

    chains = [i + 1 for i in range(len(txt_chains))]
    nodes = [i + 1 for i in range(len(txt_nodes))]

    data = [list() for _ in range(len(chains))]
    for c in chains:
        for n in nodes:
            try:
                val = vals[txt_chains[c - 1]][txt_nodes[n - 1]]["mean"]
            except (KeyError, IndexError):
                val = None
            data[c - 1].append(val)

    # Colorscales:
    my_green = [[0.0, 'rgb(235, 249, 242)'],
                [1.0, 'rgb(45, 134, 89)']]

    my_blue = [[0.0, 'rgb(236, 242, 248)'],
               [1.0, 'rgb(57, 115, 172)']]

    my_grey = [[0.0, 'rgb(230, 230, 230)'],
               [1.0, 'rgb(102, 102, 102)']]

    hovertext = list()
    annotations = list()

    text = ("Test: {name}<br>"
            "Runs: {nr}<br>"
            "Thput: {val}<br>"
            "StDev: {stdev}")

    for c in range(len(txt_chains)):
        hover_line = list()
        for n in range(len(txt_nodes)):
            if data[c][n] is not None:
                annotations.append(dict(
                    x=n+1,
                    y=c+1,
                    xref="x",
                    yref="y",
                    xanchor="center",
                    yanchor="middle",
                    text=str(data[c][n]),
                    font=dict(
                        size=14,
                    ),
                    align="center",
                    showarrow=False
                ))
                hover_line.append(text.format(
                    name=vals[txt_chains[c]][txt_nodes[n]]["name"],
                    nr=vals[txt_chains[c]][txt_nodes[n]]["nr"],
                    val=data[c][n],
                    stdev=vals[txt_chains[c]][txt_nodes[n]]["stdev"]))
        hovertext.append(hover_line)

    traces = [
        plgo.Heatmap(x=nodes,
                     y=chains,
                     z=data,
                     colorbar=dict(
                         title=plot.get("z-axis", ""),
                         titleside="right",
                         titlefont=dict(
                            size=16
                         ),
                         tickfont=dict(
                             size=16,
                         ),
                         tickformat=".1f",
                         yanchor="bottom",
                         y=-0.02,
                         len=0.925,
                     ),
                     showscale=True,
                     colorscale=my_green,
                     text=hovertext,
                     hoverinfo="text")
    ]

    for idx, item in enumerate(txt_nodes):
        # X-axis, numbers:
        annotations.append(dict(
            x=idx+1,
            y=0.05,
            xref="x",
            yref="y",
            xanchor="center",
            yanchor="top",
            text=item,
            font=dict(
                size=16,
            ),
            align="center",
            showarrow=False
        ))
    for idx, item in enumerate(txt_chains):
        # Y-axis, numbers:
        annotations.append(dict(
            x=0.35,
            y=idx+1,
            xref="x",
            yref="y",
            xanchor="right",
            yanchor="middle",
            text=item,
            font=dict(
                size=16,
            ),
            align="center",
            showarrow=False
        ))
    # X-axis, title:
    annotations.append(dict(
        x=0.55,
        y=-0.15,
        xref="paper",
        yref="y",
        xanchor="center",
        yanchor="bottom",
        text=plot.get("x-axis", ""),
        font=dict(
            size=16,
        ),
        align="center",
        showarrow=False
    ))
    # Y-axis, title:
    annotations.append(dict(
        x=-0.1,
        y=0.5,
        xref="x",
        yref="paper",
        xanchor="center",
        yanchor="middle",
        text=plot.get("y-axis", ""),
        font=dict(
            size=16,
        ),
        align="center",
        textangle=270,
        showarrow=False
    ))
    updatemenus = list([
        dict(
            x=1.0,
            y=0.0,
            xanchor='right',
            yanchor='bottom',
            direction='up',
            buttons=list([
                dict(
                    args=[{"colorscale": [my_green, ], "reversescale": False}],
                    label="Green",
                    method="update"
                ),
                dict(
                    args=[{"colorscale": [my_blue, ], "reversescale": False}],
                    label="Blue",
                    method="update"
                ),
                dict(
                    args=[{"colorscale": [my_grey, ], "reversescale": False}],
                    label="Grey",
                    method="update"
                )
            ])
        )
    ])

    try:
        layout = deepcopy(plot["layout"])
    except KeyError as err:
        logging.error("Finished with error: No layout defined")
        logging.error(repr(err))
        return

    layout["annotations"] = annotations
    layout['updatemenus'] = updatemenus

    try:
        # Create plot
        plpl = plgo.Figure(data=traces, layout=layout)

        # Export Plot
        logging.info("    Writing file '{0}{1}'.".
                     format(plot["output-file"], plot["output-file-type"]))
        ploff.plot(plpl, show_link=False, auto_open=False,
                   filename='{0}{1}'.format(plot["output-file"],
                                            plot["output-file-type"]))
    except PlotlyError as err:
        logging.error("   Finished with error: {}".
                      format(str(err).replace("\n", " ")))
        return


def plot_service_density_heatmap_compare(plot, input_data):
    """Generate the plot(s) with algorithm: plot_service_density_heatmap_compare
    specified in the specification file.

    :param plot: Plot to generate.
    :param input_data: Data to process.
    :type plot: pandas.Series
    :type input_data: InputData
    """

    REGEX_CN = re.compile(r'^(\d*)R(\d*)C$')
    REGEX_TEST_NAME = re.compile(r'^.*-(\d+ch|\d+pl)-'
                                 r'(\d+mif|\d+vh)-'
                                 r'(\d+vm\d+t|\d+dcr\d+t).*$')
    REGEX_THREADS = re.compile(r'^(\d+)(VM|DCR)(\d+)T$')

    txt_chains = list()
    txt_nodes = list()
    vals = dict()

    # Transform the data
    logging.info("    Creating the data set for the {0} '{1}'.".
                 format(plot.get("type", ""), plot.get("title", "")))
    data = input_data.filter_data(plot, continue_on_error=True)
    if data is None or data.empty:
        logging.error("No data.")
        return

    for job in data:
        for build in job:
            for test in build:
                for tag in test['tags']:
                    groups = re.search(REGEX_CN, tag)
                    if groups:
                        c = str(groups.group(1))
                        n = str(groups.group(2))
                        break
                else:
                    continue
                groups = re.search(REGEX_TEST_NAME, test["name"])
                if groups and len(groups.groups()) == 3:
                    hover_name = "{chain}-{vhost}-{vm}".format(
                        chain=str(groups.group(1)),
                        vhost=str(groups.group(2)),
                        vm=str(groups.group(3)))
                else:
                    hover_name = ""
                if vals.get(c, None) is None:
                    vals[c] = dict()
                if vals[c].get(n, None) is None:
                    vals[c][n] = dict(name=hover_name,
                                      vals_r=list(),
                                      vals_c=list(),
                                      nr_r=None,
                                      nr_c=None,
                                      mean_r=None,
                                      mean_c=None,
                                      stdev_r=None,
                                      stdev_c=None)
                try:
                    if plot["include-tests"] == "MRR":
                        result = test["result"]["receive-rate"].avg
                    elif plot["include-tests"] == "PDR":
                        result = test["throughput"]["PDR"]["LOWER"]
                    elif plot["include-tests"] == "NDR":
                        result = test["throughput"]["NDR"]["LOWER"]
                    else:
                        result = None
                except TypeError:
                    result = None

                if result:
                    for tag in test['tags']:
                        groups = re.search(REGEX_THREADS, tag)
                        if groups and len(groups.groups()) == 3:
                            if str(groups.group(3)) == \
                                    plot["reference"]["include"]:
                                vals[c][n]["vals_r"].append(result)
                            elif str(groups.group(3)) == \
                                    plot["compare"]["include"]:
                                vals[c][n]["vals_c"].append(result)
                            break
    if not vals:
        logging.error("No data.")
        return

    for key_c in vals.keys():
        txt_chains.append(key_c)
        for key_n in vals[key_c].keys():
            txt_nodes.append(key_n)
            if vals[key_c][key_n]["vals_r"]:
                vals[key_c][key_n]["nr_r"] = len(vals[key_c][key_n]["vals_r"])
                vals[key_c][key_n]["mean_r"] = \
                    mean(vals[key_c][key_n]["vals_r"])
                vals[key_c][key_n]["stdev_r"] = \
                    round(stdev(vals[key_c][key_n]["vals_r"]) / 1000000, 1)
            if vals[key_c][key_n]["vals_c"]:
                vals[key_c][key_n]["nr_c"] = len(vals[key_c][key_n]["vals_c"])
                vals[key_c][key_n]["mean_c"] = \
                    mean(vals[key_c][key_n]["vals_c"])
                vals[key_c][key_n]["stdev_c"] = \
                    round(stdev(vals[key_c][key_n]["vals_c"]) / 1000000, 1)

    txt_nodes = list(set(txt_nodes))

    txt_chains = sorted(txt_chains, key=lambda chain: int(chain))
    txt_nodes = sorted(txt_nodes, key=lambda node: int(node))

    chains = [i + 1 for i in range(len(txt_chains))]
    nodes = [i + 1 for i in range(len(txt_nodes))]

    data_r = [list() for _ in range(len(chains))]
    data_c = [list() for _ in range(len(chains))]
    diff = [list() for _ in range(len(chains))]
    for c in chains:
        for n in nodes:
            try:
                val_r = vals[txt_chains[c - 1]][txt_nodes[n - 1]]["mean_r"]
            except (KeyError, IndexError):
                val_r = None
            try:
                val_c = vals[txt_chains[c - 1]][txt_nodes[n - 1]]["mean_c"]
            except (KeyError, IndexError):
                val_c = None
            if val_c is not None and val_r:
                val_d = (val_c - val_r) * 100 / val_r
            else:
                val_d = None

            if val_r is not None:
                val_r = round(val_r / 1000000, 1)
            data_r[c - 1].append(val_r)
            if val_c is not None:
                val_c = round(val_c / 1000000, 1)
            data_c[c - 1].append(val_c)
            if val_d is not None:
                val_d = int(round(val_d, 0))
            diff[c - 1].append(val_d)

    # Colorscales:
    my_green = [[0.0, 'rgb(235, 249, 242)'],
                [1.0, 'rgb(45, 134, 89)']]

    my_blue = [[0.0, 'rgb(236, 242, 248)'],
               [1.0, 'rgb(57, 115, 172)']]

    my_grey = [[0.0, 'rgb(230, 230, 230)'],
               [1.0, 'rgb(102, 102, 102)']]

    hovertext = list()

    annotations = list()
    annotations_r = list()
    annotations_c = list()
    annotations_diff = list()

    text = ("Test: {name}"
            "<br>{title_r}: {text_r}"
            "<br>{title_c}: {text_c}{text_diff}")
    text_r = "Thput: {val_r}; StDev: {stdev_r}; Runs: {nr_r}"
    text_c = "Thput: {val_c}; StDev: {stdev_c}; Runs: {nr_c}"
    text_diff = "<br>Relative Difference {title_c} vs. {title_r}: {diff}%"

    for c in range(len(txt_chains)):
        hover_line = list()
        for n in range(len(txt_nodes)):
            point = dict(
                x=n + 1,
                y=c + 1,
                xref="x",
                yref="y",
                xanchor="center",
                yanchor="middle",
                text="",
                font=dict(
                    size=14,
                ),
                align="center",
                showarrow=False
            )

            point_text_r = "Not present"
            point_text_c = "Not present"
            point_text_diff = ""
            try:
                point_r = data_r[c][n]
                if point_r is not None:
                    point_text_r = text_r.format(
                        val_r=point_r,
                        stdev_r=vals[txt_chains[c]][txt_nodes[n]]["stdev_r"],
                        nr_r=vals[txt_chains[c]][txt_nodes[n]]["nr_r"])
            except KeyError:
                point_r = None
            point["text"] = "" if point_r is None else point_r
            annotations_r.append(deepcopy(point))

            try:
                point_c = data_c[c][n]
                if point_c is not None:
                    point_text_c = text_c.format(
                        val_c=point_c,
                        stdev_c=vals[txt_chains[c]][txt_nodes[n]]["stdev_c"],
                        nr_c=vals[txt_chains[c]][txt_nodes[n]]["nr_c"])
            except KeyError:
                point_c = None
            point["text"] = "" if point_c is None else point_c
            annotations_c.append(deepcopy(point))

            try:
                point_d = diff[c][n]
                if point_d is not None:
                    point_text_diff = text_diff.format(
                        title_r=plot["reference"]["name"],
                        title_c=plot["compare"]["name"],
                        diff=point_d)
            except KeyError:
                point_d = None
            point["text"] = "" if point_d is None else point_d
            annotations_diff.append(deepcopy(point))

            try:
                name = vals[txt_chains[c]][txt_nodes[n]]["name"]
            except KeyError:
                continue

            hover_line.append(text.format(
                name=name,
                title_r=plot["reference"]["name"],
                text_r=point_text_r,
                title_c=plot["compare"]["name"],
                text_c=point_text_c,
                text_diff=point_text_diff
            ))

        hovertext.append(hover_line)

    traces = [
        plgo.Heatmap(x=nodes,
                     y=chains,
                     z=data_r,
                     visible=True,
                     colorbar=dict(
                         title=plot.get("z-axis", ""),
                         titleside="right",
                         titlefont=dict(
                            size=16
                         ),
                         tickfont=dict(
                             size=16,
                         ),
                         tickformat=".1f",
                         yanchor="bottom",
                         y=-0.02,
                         len=0.925,
                     ),
                     showscale=True,
                     colorscale=my_green,
                     reversescale=False,
                     text=hovertext,
                     hoverinfo="text"),
        plgo.Heatmap(x=nodes,
                     y=chains,
                     z=data_c,
                     visible=False,
                     colorbar=dict(
                         title=plot.get("z-axis", ""),
                         titleside="right",
                         titlefont=dict(
                             size=16
                         ),
                         tickfont=dict(
                             size=16,
                         ),
                         tickformat=".1f",
                         yanchor="bottom",
                         y=-0.02,
                         len=0.925,
                     ),
                     showscale=True,
                     colorscale=my_blue,
                     reversescale=False,
                     text=hovertext,
                     hoverinfo="text"),
        plgo.Heatmap(x=nodes,
                     y=chains,
                     z=diff,
                     name="Diff",
                     visible=False,
                     colorbar=dict(
                         title="Relative Difference {name_c} vs. {name_r} [%]".
                             format(name_c=plot["compare"]["name"],
                                    name_r=plot["reference"]["name"]),
                         titleside="right",
                         titlefont=dict(
                             size=16
                         ),
                         tickfont=dict(
                             size=16,
                         ),
                         tickformat=".1f",
                         yanchor="bottom",
                         y=-0.02,
                         len=0.925,
                     ),
                     showscale=True,
                     colorscale=my_grey,
                     reversescale=False,
                     text=hovertext,
                     hoverinfo="text")
    ]

    for idx, item in enumerate(txt_nodes):
        # X-axis, numbers:
        annotations.append(dict(
            x=idx+1,
            y=0.05,
            xref="x",
            yref="y",
            xanchor="center",
            yanchor="top",
            text=item,
            font=dict(
                size=16,
            ),
            align="center",
            showarrow=False
        ))
    for idx, item in enumerate(txt_chains):
        # Y-axis, numbers:
        annotations.append(dict(
            x=0.35,
            y=idx+1,
            xref="x",
            yref="y",
            xanchor="right",
            yanchor="middle",
            text=item,
            font=dict(
                size=16,
            ),
            align="center",
            showarrow=False
        ))
    # X-axis, title:
    annotations.append(dict(
        x=0.55,
        y=-0.15,
        xref="paper",
        yref="y",
        xanchor="center",
        yanchor="bottom",
        text=plot.get("x-axis", ""),
        font=dict(
            size=16,
        ),
        align="center",
        showarrow=False
    ))
    # Y-axis, title:
    annotations.append(dict(
        x=-0.1,
        y=0.5,
        xref="x",
        yref="paper",
        xanchor="center",
        yanchor="middle",
        text=plot.get("y-axis", ""),
        font=dict(
            size=16,
        ),
        align="center",
        textangle=270,
        showarrow=False
    ))
    updatemenus = list([
        dict(
            active=0,
            x=1.0,
            y=0.0,
            xanchor='right',
            yanchor='bottom',
            direction='up',
            buttons=list([
                dict(
                    label=plot["reference"]["name"],
                    method="update",
                    args=[
                        {
                            "visible": [True, False, False]
                        },
                        {
                            "colorscale": [my_green, ],
                            "reversescale": False,
                            "annotations": annotations + annotations_r,
                        },
                    ]
                ),
                dict(
                    label=plot["compare"]["name"],
                    method="update",
                    args=[
                        {
                            "visible": [False, True, False]
                        },
                        {
                            "colorscale": [my_blue, ],
                            "reversescale": False,
                            "annotations": annotations + annotations_c,
                        },
                    ]
                ),
                dict(
                    label="Diff",
                    method="update",
                    args=[
                        {
                            "visible": [False, False, True]
                        },
                        {
                            "colorscale": [my_grey, ],
                            "reversescale": False,
                            "annotations": annotations + annotations_diff,
                        },
                    ]
                ),
            ])
        )
    ])

    try:
        layout = deepcopy(plot["layout"])
    except KeyError as err:
        logging.error("Finished with error: No layout defined")
        logging.error(repr(err))
        return

    layout["annotations"] = annotations + annotations_r
    layout['updatemenus'] = updatemenus

    try:
        # Create plot
        plpl = plgo.Figure(data=traces, layout=layout)

        # Export Plot
        logging.info("    Writing file '{0}{1}'.".
                     format(plot["output-file"], plot["output-file-type"]))
        ploff.plot(plpl, show_link=False, auto_open=False,
                   filename='{0}{1}'.format(plot["output-file"],
                                            plot["output-file-type"]))
    except PlotlyError as err:
        logging.error("   Finished with error: {}".
                      format(str(err).replace("\n", " ")))
        return