Repository navigation
Expand file tree
/
Copy pathpyscript_random_gen.html
More file actions
158 lines (148 loc) · 8.17 KB
/
Copy pathpyscript_random_gen.html
File metadata and controls
158 lines (148 loc) · 8.17 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>PyScript Random Number Generation</title>
<link rel="icon" type="image/png" href="favicon.png" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<py-env>
- matplotlib
</py-env>
</head>
<body style="margin: 25px 75px 25px 75px;">
<div class="container-fluid">
<div class="p-5 text-center bg-light">
<h1 class="mb-3">Random number generation using PyScript</h1>
<p>Demo developed by <a href="https://www.linkedin.com/in/tirthajyoti-sarkar-2127aa7/">Dr. Tirthajyoti sarkar</a></p>
<a class="btn btn-primary" href="https://www.anaconda.com/blog/pyscript-python-in-the-browser" role="button">Check out the announcement from Anaconda about PyScript framework</a>
</div>
<br>
<div class="alert alert-primary" role="alert">
<h3>PyScript is awesome, it just takes a few seconds to load...</h3>
<p>To provide the power of Python on your browser, this technology needs to load <b>a special virtual machine and all necessary Python modules</b></p>
<p>So, sit back and relax. We are loading the modules and generating some random variables as a test.
You can start interacting with the page when you see a histogram of those random variates displayed below.</p>
<p> We promise that, once loaded, your interactions will be <b>Python-powered and fast! </b>You can also read more about this awesome framework here at Anaconda's engineering blog.</p>
<a class="btn btn-primary" href="https://engineering.anaconda.com/2022/04/welcome-pyscript.html" role="button">Anaconda Engineering Blog about PyScript</a>
</div>
<h2 style="border:5px; border-radius: 10px; padding:10px;background-color:gray; color:cyan">Test: Random integers</h2>
<h4>These are 100 random integers, generated by <b><code>NumPy</code></b></h4>
<p>We literally wrote this pure Python code in the HTML file to generate these numbers! If you don't believe us, just right-click and view the source code of this page :-)
The only thing to note here is the <code><py-script></py-script></code> tags around the code block.
</p>
<pre style="background-color:rgb(187, 199, 199); padding: 10px; font-size: 1.2em; width: 50%; text-align:left;">
<code><py-script>
import numpy as np
integers = np.random.randint(0,100,100)
print(integers)
</py-script></code></pre>
<py-script>
import numpy as np
integers = np.random.randint(0,100,100)
print(integers)
</py-script>
<br>
<h4>This is the histogram of those random integers, generated by <b><code>Matplotlib</code></b></h4>
<p>You can do all the usual <code>Matplotlib</code> tweaks and tricks with the visualization as you would in a normal Python script or Jupyter Notebook.
Here, we have just set the <code>dpi=150</code> and <code>figsize=(5,2)</code> inside the <code>plt.subplots()</code> function.
<p>This code is inline too i.e., embedded with this HTML. So, feel free to check it out. The last line of the Python code block is just the figure object <code>fig1</code>.
This tells the PyScript framework to output the object/image (it detects the type intelligently) to the corresponding <code>div</code> section.
</p></p>
<div class="container-md">
<py-script>
import matplotlib.pyplot as plt
fig1,ax1 = plt.subplots(1,1,dpi=150,figsize=(5,2))
ax1.hist(integers,bins=20,edgecolor='k',color='blue')
ax1.set_title("Histogram of random integers",fontsize=11)
fig1
</py-script>
</div>
<br>
<h4>Changing the image output method</h4>
<p>In the next section, we generate histogram based on the type of the distribution that the user (you) choses.
We slightly change the output method for this
as <strong>we grab the <code>div</code> element</strong> where we want to display the image and write the figure object with a code like <code>out.write(fig1)</code></p>
<div class="alert alert-info" role="alert">
<img src="info-circle.svg" width="25px">
The importance of this <em>grabbing a HTML element directly from within the Python code block</em> cannot be emphasized enough.
This opens up all kind of possibilities of user interaction with Python data processing using conventional HTML widgets in a simple, intuitive, and flexible manner.
In the next section, we put this to use with simple action buttons (that call pure Python functions), dropdown menu (that passes user choice to Python functions),
and even a slider (that adjusts a hyperparametr like data density).
</div>
<h2 style="border:5px; border-radius: 10px; padding:10px;background-color:gray; color:cyan">User-defined random variate generation</h2>
<h4 >How many random variates to generate? (if left blank, 10 values will be generated)</h4>
<py-inputbox id="how-many" style="margin-bottom: 10px;">
</py-inputbox>
<div><button id="gen" style="margin-top: 10px;margin-bottom: 10px;" type="button" class="btn btn-primary" pys-onClick="print_num">
Generate random variates</div>
<div id="outputDiv" style="margin-top: 10px;margin-bottom: 10px;"></div>
<div><button id="clear" type="button" class="btn btn-primary" pys-onClick="clear">
Clear random variates</div>
<br>
<h4>Choose the type of distribution you want to generate random variates from</h4>
<p>As you expect, every time the <input type="button" class="btn btn-primary" value="Show distribution"> button is clicked, you will see a new histogram.
<strong>All that computation is happening with pure Python code and in your browser!</strong></p>
<select name="dist" id="dist" class="form-select" aria-label="Default select example">
<option value="Gaussian">Gaussian</option>
<option value="Beta">Beta</option>
<option value="Exponential">Exponential</option>
</select>
<div>
<p style="margin-top:10px;">Adjust the number of random variates</p>
<input type="range" id="slider-num-var" value="500" min="100" max="1000" step="100"
oninput="this.nextElementSibling.value = this.value" style="width:50%;">
<output>500</output>
</div>
<div><button id="show-dist" style="margin-top: 10px;margin-bottom: 10px;" type="button" class="btn btn-primary" pys-onClick="show_dist">
Show distribution</div>
<div id="outputDiv2" class="container-md"></div>
<py-script>
import numpy as np
import matplotlib.pyplot as plt
out = Element("outputDiv")
input_num = Element("how-many")
dist_type = Element("dist").value
out2 = Element("outputDiv2")
def random_num(n):
"""
"""
r = np.random.normal(size=n)
return np.array2string(r)
def clear(*ags, **kws):
out = Element("outputDiv")
out.clear()
def print_num(*ags, **kws):
if input_num.value=='':
n = 10
else:
n = int(input_num.value)
r = random_num(n)
out.write(f"Here are {n} random variates from Normal distribution: {r}")
def show_dist(*ags, **kws):
dist_type = Element("dist").value
dist_size = int(Element("slider-num-var").value)
fig1,ax1 = plt.subplots(1,1,dpi=150,figsize=(6,4))
fig1.subplots_adjust(hspace=0.25)
if dist_type=='Gaussian':
data = np.random.normal(size=dist_size)
ax1.hist(data,bins=20,edgecolor='k',color='blue')
ax1.set_title(f"Histogram of Normal (Gaussian) Distribution \nwith {dist_size} random variates",fontsize=11)
out2.write(fig1)
if dist_type=='Beta':
data = np.random.beta(1,3,size=dist_size)
ax1.hist(data,bins=20,edgecolor='k',color='blue')
ax1.set_title(f"Histogram of Beta Distribution \nwith {dist_size} random variates",fontsize=11)
out2.write(fig1)
if dist_type=='Exponential':
data = np.random.exponential(0.5,size=dist_size)
ax1.hist(data,bins=20,edgecolor='k',color='blue')
ax1.set_title(f"Histogram of Exponential Distribution \nwith {dist_size} random variates",fontsize=11)
out2.write(fig1)
</py-script>
</div>
</body>
</html>