Sunday, August 7, 2022

Plotting Curves based on Numpy Histogram via flask && matplotlib

According  https://numpy.org/doc/stable/reference/generated/numpy.histogram.html

numpy.histogram(a, bins=10, range=None, normed=None, weights=None, density=None)

Options :  a:array_like

Input data. The histogram is calculated from the smoothed array. bins int or sequence of scalars or str, optional. If bins is int,  it specifies the number of bins of equal width in the given range (default 10). If the intervals are a sequence, it defines a monotonically increasing array of interval edges, including the rightmost edge, which allows for non-uniform interval widths.

New in version 1.11.0.

If bins is a string, it specifies the method used to calculate the optimal bin width, as defined by the histogram_bin_edges parameter. Range (float, float) .Lower and upper range bins is optional. If not specified, the range is simply (a.min(), a.max()). Values ​​outside the range are ignored. The first element of the range must be less than or equal to the second. the range also affects the automatic calculation of the bin. While the bin width is calculated as optimal based on the actual data within the range, the bin counter will fill the entire range, including the parts that do not contain data.

With matplotlib version 2.0 or later and numpy version 1.11 or later, you can now specify auto-detected bins directly in matplotlib by specifying bins = 'auto' for example. This uses the maximum possible number of baskets.

(.env) boris@boris-All-Series:~/FLASKHTML$ cat flaskLaplGauss1.py

import io

from flask import Response, render_template

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

from matplotlib.figure import Figure

from flask import Flask

import matplotlib.pyplot as axes

import numpy as np

import scipy.stats as stats

from scipy.optimize import curve_fit

import warnings

warnings.filterwarnings('ignore')


axes.rcParams["figure.figsize"] = [15.50, 11.50]

axes.rcParams["figure.autolayout"] = True

app = Flask(__name__)


@app.route('/')

def upload_form():

return render_template('download.html')

loc, scale = 0., 1.

x = np.random.laplace(loc, scale, 1000)

def laplacian(x,amplitude,loc,scale):

         return amplitude*np.exp(-abs(x-loc)/scale)/(2.*scale)

# Laplacian curve

@app.route('/print-plotlapl')

def plot_pnglapl():

  fig = Figure()

  axes = fig.add_subplot(1, 1, 1)

  bin_heights, bin_borders = np.histogram(x, bins='auto')

  bin_widths = np.diff(bin_borders)

  bin_centers = bin_borders[:-1] + bin_widths / 2

  popt, _ = curve_fit(laplacian, bin_centers, bin_heights, p0=[1., 0., 1.])

  x_interval_for_fit = np.linspace(bin_borders[0], bin_borders[-1], 10000)

 axes.bar(bin_centers, bin_heights, width=bin_widths, label='histogram')

 axes.plot(x_interval_for_fit,laplacian(x_interval_for_fit,*popt),label='fit',c='red')

 output = io.BytesIO()

 FigureCanvas(fig).print_png(output)

 return Response(output.getvalue(), mimetype='image/png')

# Gaussian curve

def gaussian(x, mean, amplitude, standard_deviation):

    return amplitude * np.exp( - (x - mean)**2 / (2*standard_deviation ** 2))

x = np.random.normal(10, 5, size=10000)

@app.route('/print-plotgauss')

def plot_pnggauss():

  fig = Figure()

  axes = fig.add_subplot(1, 1, 1)

  bin_heights, bin_borders = np.histogram(x, bins='auto')

  bin_widths = np.diff(bin_borders)

 bin_centers = bin_borders[:-1] + bin_widths / 2

  popt, _ = curve_fit(gaussian, bin_centers, bin_heights, p0=[1., 0., 1.])

  x_interval_for_fit = np.linspace(bin_borders[0], bin_borders[-1], 10000)

  axes.bar(bin_centers, bin_heights, width=bin_widths, label='histogram')

  axes.plot(x_interval_for_fit,gaussian(x_interval_for_fit,*popt),label='fit',c='red')                  

  output = io.BytesIO()

  FigureCanvas(fig).print_png(output)

  return Response(output.getvalue(), mimetype='image/png')

(.env) boris@boris-All-Series:~/FLASKHTML$ cat templates/download.html

<!doctype html>

<title>Python Flask File Generate Gauss Laplace Reports </title>

<p>

<h2><a href="{{ url_for('.plot_pnglapl') }}">Display Laplacian plot</a></h2>

<h2><a href="{{ url_for('.plot_pnggauss') }}">Display Gaussian plot</a></h2>

</p>

(.env) boris@boris-All-Series:~/FLASKHTML$ env | grep "FLASK_"

FLASK_APP=flaskLaplGauss1.py

FLASK_DEBUG=1

FLASK_ENV=development

(.env) boris@boris-All-Series:~/FLASKHTML$ flask run

WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.

 * Serving Flask app 'flaskLaplGauss1.py'

 * Debug mode: on

 * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)

 * Restarting with stat

 * Debugger is active!

 * Debugger PIN: 424-443-302

127.0.0.1 - - [07/Aug/2022 21:33:37] "GET / HTTP/1.1" 200 -

127.0.0.1 - - [07/Aug/2022 21:34:04] "GET / HTTP/1.1" 200 -

127.0.0.1 - - [07/Aug/2022 21:34:39] "GET /print-plotlapl HTTP/1.1" 200 -

127.0.0.1 - - [07/Aug/2022 21:35:12] "GET /print-plotgauss HTTP/1.1" 200 -

127.0.0.1 - - [07/Aug/2022 21:35:32] "GET /print-plotgauss HTTP/1.1" 200 -

























































No comments:

Post a Comment