<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[15338] CalendarServer/trunk/contrib/performance</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/15338">15338</a></dd>
<dt>Author</dt> <dd>cdaboo@apple.com</dd>
<dt>Date</dt> <dd>2015-11-19 13:44:28 -0800 (Thu, 19 Nov 2015)</dd>
</dl>

<h3>Log Message</h3>
<pre>LogNormal visualization and curve fitting.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#CalendarServertrunkcontribperformancestatspy">CalendarServer/trunk/contrib/performance/stats.py</a></li>
</ul>

<h3>Added Paths</h3>
<ul>
<li><a href="#CalendarServertrunkcontribperformancestats_analysispy">CalendarServer/trunk/contrib/performance/stats_analysis.py</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="CalendarServertrunkcontribperformancestatspy"></a>
<div class="modfile"><h4>Modified: CalendarServer/trunk/contrib/performance/stats.py (15337 => 15338)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/trunk/contrib/performance/stats.py        2015-11-19 20:00:29 UTC (rev 15337)
+++ CalendarServer/trunk/contrib/performance/stats.py        2015-11-19 21:44:28 UTC (rev 15338)
</span><span class="lines">@@ -298,6 +298,8 @@
</span><span class="cx">         else:
</span><span class="cx">             raise ValueError(&quot;When using mode one of median or mean must be defined&quot;)
</span><span class="cx"> 
</span><ins>+        self._mode = mode
+        self._median = median
</ins><span class="cx">         self._mu = mu
</span><span class="cx">         self._sigma = sigma
</span><span class="cx">         self._scale = scale
</span><span class="lines">@@ -470,28 +472,3 @@
</span><span class="cx">                 return prop
</span><span class="cx"> 
</span><span class="cx">         return None
</span><del>-
-if __name__ == '__main__':
-
-    import matplotlib.pyplot as plt
-    from collections import defaultdict
-    mode_val = 6.0
-    median_val = 8.0
-    distribution = LogNormalDistribution(mode=mode_val, median=median_val, maximum=60)
-    result = defaultdict(int)
-    for i in range(1000000):
-        s = int(distribution.sample())
-        result[s] += 1
-
-    total = 0
-    for k, v in sorted(result.items(), key=lambda x: x[0]):
-        print(&quot;%d\t%.5f&quot; % (k, float(v) / result[1]))
-        total += k * v
-
-    print(&quot;Average: %.2f&quot; % (float(total) / sum(result.values()),))
-
-    x, y = zip(*sorted(result.items()))
-    plt.plot(x, y)
-    plt.xlabel(&quot;Samples&quot;)
-    plt.ylabel(&quot;LogNormal&quot;)
-    plt.show()
</del></span></pre></div>
<a id="CalendarServertrunkcontribperformancestats_analysispy"></a>
<div class="addfile"><h4>Added: CalendarServer/trunk/contrib/performance/stats_analysis.py (0 => 15338)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/trunk/contrib/performance/stats_analysis.py                                (rev 0)
+++ CalendarServer/trunk/contrib/performance/stats_analysis.py        2015-11-19 21:44:28 UTC (rev 15338)
</span><span class="lines">@@ -0,0 +1,229 @@
</span><ins>+##
+# Copyright (c) 2015 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+# 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 &quot;AS IS&quot; 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.
+##
+
+
+from collections import defaultdict, namedtuple
+from contrib.performance.stats import LogNormalDistribution
+from scipy.optimize import curve_fit
+import itertools
+import matplotlib.pyplot as plt
+import numpy as np
+import os
+
+
+class LogNormal(object):
+
+    Params = namedtuple(&quot;Params&quot;, (&quot;mu&quot;, &quot;sigma&quot;, &quot;scale_x&quot;, &quot;scale_y&quot;))
+
+    @staticmethod
+    def fn(x, mu, sigma, scale_x, scale_y):
+        &quot;&quot;&quot;
+        Calculate the LogNormal F(x) value for the given parameters.
+
+        @param x: x value to use
+        @type x: L{float}
+        @param mu: mean
+        @type mu: L{float}
+        @param sigma: standard deviation
+        @type sigma: L{float}
+        @param scale_x: X-scaling factor (to make mode == 1.0)
+        @type scale_x: L{float}
+        @param scale_y: Y-scaling factor for peak height
+        @type scale_y: L{float}
+        &quot;&quot;&quot;
+        return scale_y * (
+            np.exp(-(np.log(x / scale_x) - mu) ** 2 / (2 * sigma ** 2)) /
+            (x / scale_x * sigma * np.sqrt(2 * np.pi))
+        )
+
+
+    @staticmethod
+    def estimate(x, y):
+        &quot;&quot;&quot;
+        Given a set of x-y data that is likely a LogNormal distribution, try and estimate the mode
+        and median, and then derive mu, sigma, scale_x and scale_y values.
+
+        @param x: sequence of values
+        @type x: L{list} of L{float}
+        @param y: sequence of values
+        @type y: L{list} of L{float}
+        &quot;&quot;&quot;
+        estimate_mode = 0.0
+        estimate_median = 0.0
+        max_y = 0.0
+        accumulated_y = 0.0
+        half_y = sum(y) / 2.0
+        for x_val, y_val in itertools.izip(x, y):
+            if y_val &gt; max_y:
+                max_y = y_val
+                estimate_mode = x_val
+            accumulated_y += y_val
+            if half_y is not None and accumulated_y &gt; half_y:
+                estimate_median = x_val
+                half_y = None
+
+        estimate_scale_x = estimate_mode - 0.5
+        estimate_mode = 1.0
+        estimate_median /= estimate_scale_x
+        estimate_mu = np.log(estimate_median)
+        estimate_sigma = np.sqrt(np.log(estimate_median) - np.log(estimate_mode))
+
+        peak_y = LogNormal.fn(estimate_scale_x, estimate_mu, estimate_sigma, estimate_scale_x, 1.0)
+        estimate_scale_y = max(y) / peak_y
+        return (
+            estimate_mode, estimate_median,
+            LogNormal.Params(estimate_mu, estimate_sigma, estimate_scale_x, estimate_scale_y),
+        )
+
+
+    @staticmethod
+    def plot(min_x, max_x, params, color):
+        &quot;&quot;&quot;
+        Plot a LogNormal distribution over the specified x-axis range using the supplied
+        distribution parameters.
+
+        @param min_x: minimum x-axis value
+        @type min_x: L{float}
+        @param max_x: maximum x-asix value
+        @type max_x: L{float}
+        @param params: distribution parameters
+        @type params: L{LogNormal.Params}
+        @param color: color to use for line in plot
+        @type color: L{str}
+        &quot;&quot;&quot;
+        xl = np.linspace(min_x, max_x, 10000)
+        yl = (
+            np.exp(-(np.log(xl / params.scale_x) - params.mu) ** 2 / (2 * params.sigma ** 2)) /
+            (xl / params.scale_x * params.sigma * np.sqrt(2 * np.pi))
+        )
+
+        plt.plot(xl, params.scale_y * yl, linewidth=2, color=color)
+
+
+    @staticmethod
+    def plotCSV(path, cutoff, bucket, color):
+        &quot;&quot;&quot;
+        Plot data from a CSV file.
+
+        @param path: file to read from
+        @type path: L{str}
+        @param cutoff: maximum x-value to process
+        @type cutoff: L{float}
+        @param bucket: size of x-value buckets to use
+        @type bucket: L{int}
+        @param color: color to use for line in plot
+        @type color: L{str}
+        &quot;&quot;&quot;
+        with open(os.path.expanduser(path)) as f:
+            data = f.read()
+        result = defaultdict(int)
+        for line in data.splitlines():
+            sp = line.split(&quot;,&quot;)
+            x_val = int(sp[0])
+            y_val = int(sp[1])
+            if x_val &lt; cutoff:
+                result[(x_val / bucket) * bucket] += y_val
+
+        x, y = zip(*sorted(result.items()))
+        plt.plot(x, y)
+        return (x, y,)
+
+
+    @staticmethod
+    def distributionPlot(mode, median, maximum, color):
+        &quot;&quot;&quot;
+        Plot data from a randomly generated LogNornal distribution.
+
+        @param mode: distribution mode
+        @type mode: L{float}
+        @param median: distribution median
+        @type median: L{float}
+        @param maximum: highest x-value to allow
+        @type maximum: L{float}
+        @param color: color to use for line in plot
+        @type color: L{str}
+        &quot;&quot;&quot;
+        distribution = LogNormalDistribution(mode=mode, median=median, maximum=maximum)
+        result = defaultdict(int)
+        for _ignore in range(1000000):
+            s = int(distribution.sample()) + 0.5
+            result[s] += 1
+
+        x, y = zip(*sorted(result.items()))
+        plt.plot(x, y, color=color)
+
+        peak_y = LogNormal.fn(distribution._scale, distribution._mu, distribution._sigma, distribution._scale, 1.0)
+        scale_y = sum(sorted(y, reverse=True)[0:100]) / 100.0 / peak_y
+
+        return (x, y, LogNormal.Params(distribution._mu, distribution._sigma, distribution._scale, scale_y),)
+
+
+    @staticmethod
+    def fit(x, y):
+        &quot;&quot;&quot;
+        Try and fit a LogNormal distribution to the supplied x-y data.
+
+        @param x: sequence of values
+        @type x: L{list} of L{float}
+        @param y: sequence of values
+        @type y: L{list} of L{float}
+        &quot;&quot;&quot;
+        estimate_mode, estimate_median, estimate_params = LogNormal.estimate(x, y)
+
+        print(&quot;\n==== Estimates&quot;)
+        print(&quot;mode: {}&quot;.format(estimate_mode * estimate_params.scale_x))
+        print(&quot;median: {}&quot;.format(estimate_median * estimate_params.scale_x))
+        print(&quot;mu: {}&quot;.format(estimate_params.mu))
+        print(&quot;sigma: {}&quot;.format(estimate_params.sigma))
+        print(&quot;scale_x: {}&quot;.format(estimate_params.scale_x))
+        print(&quot;scale_y: {}&quot;.format(estimate_params.scale_y))
+
+        popt, _ignore_pcov = curve_fit(LogNormal.fn, x, y, (
+            estimate_params.mu, estimate_params.sigma, estimate_params.scale_x, estimate_params.scale_y,
+        ))
+
+        print(&quot;\n==== Fit results&quot;)
+        print(&quot;mode: {:.2f}&quot;.format(popt[2] * np.exp(popt[0] - popt[1] ** 2)))
+        print(&quot;median: {:.2f}&quot;.format(popt[2] * np.exp(popt[0])))
+        print(&quot;mu: {:.2f}&quot;.format(popt[0]))
+        print(&quot;sigma: {:.2f}&quot;.format(popt[1]))
+        print(&quot;scale_x: {:.2f}&quot;.format(popt[2]))
+        print(&quot;scale_y: {:.2f}&quot;.format(popt[3]))
+
+        return (
+            LogNormal.Params(*popt),
+            estimate_params,
+        )
+
+
+
+if __name__ == '__main__':
+
+    #x, y = LogNormal.plotCSV(&quot;~/data.txt&quot;, 10000, 10, color=&quot;b&quot;)
+    #estimate_mode, estimate_median, estimate_params = LogNormal.estimate(x, y)
+
+    mode_val = 450
+    median_val = 650
+    x, y, estimate_params = LogNormal.distributionPlot(mode_val, median_val, 10000, color=&quot;b&quot;)
+
+    LogNormal.plot(1, 10000, estimate_params, color=&quot;g&quot;)
+
+    popt, estimate = LogNormal.fit(x, y)
+    LogNormal.plot(1, 10000, popt, color=&quot;r&quot;)
+
+    plt.xlabel(&quot;Samples&quot;)
+    plt.ylabel(&quot;LogNormal&quot;)
+    plt.show()
</ins></span></pre>
</div>
</div>

</body>
</html>