Edit: 2026-11-21
<script src="/js/wave_demo_103.js"></script> <script src="https://cdn.plot.ly/plotly-3.7.0.min.js"></script>1) the first file contains my JS glue which used to send HTML messages to python, and receive the response
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Wave Demo (via Python)</title>
<link href="css/nsr-20170909.css" rel="stylesheet" type="text/css">
<script src="/js/wave_demo_103.js"></script>
<script src="https://cdn.plot.ly/plotly-3.7.0.min.js"></script>
<style>
body {font-family: monospace; font-weight:bold;border:1px solid gray;padding:4px;}
.r {color:red}
</style>
</head>
<body>
<h4>Wave Demo (Python via CGI)</h4>
<form id="form1">
<div style="width:600px;text-align:left;margin-left:20px">Frequency
Amplitude <br>
<div style="width:100%">
<div style="float:left">
Harmonic 01: <input id="h1" type="checkbox">
<input id="a1" size="12" maxlength="12" type="text"><br>
Harmomic 02: <input id="h2" type="checkbox">
<input id="a2" size="12" maxlength="12" type="text"><br>
Harmonic 03: <input id="h3" type="checkbox">
<input id="a3" size="12" maxlength="12" type="text"><br>
Harmonic 04: <input id="h4" type="checkbox">
<input id="a4" size="12" maxlength="12" type="text"><br>
Harmonic 05: <input id="h5" type="checkbox">
<input id="a5" size="12" maxlength="12" type="text"><br>
Harmonic 06: <input id="h6" type="checkbox">
<input id="a6" size="12" maxlength="12" type="text"><br>
Harmonic 07: <input id="h7" type="checkbox">
<input id="a7" size="12" maxlength="12" type="text"><br>
Harmonic 08: <input id="h8" type="checkbox">
<input id="a8" size="12" maxlength="12" type="text"><br>
Harmonic 09: <input id="h9" type="checkbox">
<input id="a9" size="12" maxlength="12" type="text"><br>
</div>
<div style="float:left;margin-left:4px">
Harmonic 10: <input id="h10" type="checkbox">
<input id="a10" size="12" maxlength="12" type="text"><br>
Harmomic 11: <input id="h11" type="checkbox">
<input id="a11" size="12" maxlength="12" type="text"><br>
Harmonic 12: <input id="h12" type="checkbox">
<input id="a12" size="12" maxlength="12" type="text"><br>
Harmonic 13: <input id="h13" type="checkbox">
<input id="a13" size="12" maxlength="12" type="text"><br>
Harmonic 14: <input id="h14" type="checkbox">
<input id="a14" size="12" maxlength="12" type="text"><br>
Harmonic 15: <input id="h15" type="checkbox">
<input id="a15" size="12" maxlength="12" type="text"><br>
Harmonic 16: <input id="h16" type="checkbox">
<input id="a16" size="12" maxlength="12" type="text"><br>
Harmonic 17: <input id="h17" type="checkbox">
<input id="a17" size="12" maxlength="12" type="text"><br>
Harmonic 18: <input id="h18" type="checkbox">
<input id="a18" size="12" maxlength="12" type="text"><br>
</div>
<div style="width:100%;height:1px;clear:both"> </div>
</div>
<button type="button" id="but1" onclick="setDefaults1();">Fundamental</button>
<button type="button" id="but2" onclick="setDefaults2();">Odd Harmonics</button>
<button type="button" id="but3" onclick="setDefaults3();">All Harmonics</button>
<button type="button" id="but4" onclick="runDemo();">Run Demo</button>
<button type="button" id="but5" onclick="doReset();">Reset</button>
</div>
<hr>interface message:<br>
<div id="msg" style="width:396px;min-height:40px;padding:2px;border:1px solid gray;display:inline-block;"> </div>
</form>
<div id="pix_buffer1"> </div>
<hr>
<div style="font-family:Calibri, Arial, sans-serif;font-weight:normal">
<p>Neil Rieck<br>
Waterloo, Ontario, Canada.<br>
<a href="https://neilrieck.net" target="_blank">https://neilrieck.net</a></p>
<p><span class="r">Caveat:</span> This demo occasionally breaks at this hobbyist site.
If you notice any problems then please send me an email here: <a href="MAILTO:n.rieck@bell.net">n.rieck@bell.net</a></p>
<hr>
<div style="font-weight:700">Additional information for inquiring minds</div>
<ul>
<li>Signal Overview
<ul>
<li>NO HARMONICS: the tranverse flute comes the closest to producing a pure sign wave with no harmonics</li>
<li>ODD HARMONICS: reed instruments tend to involve square waves</li>
<li>ALL HARMONICS: plucked strings tend to involve saw-tooth waves</li>
</ul>
</li>
<li>FFT Overview
<ul>
<li>This FFT (Fast Fourier Transform) demo converts signals from the time-domain (think oscilloscope) to the
frequency-domain.</li>
<li>FFT is based upon the <b>Fourier Series</b> which can convert any complicated signal into a series of sine
and cosine waves</li>
<li>The <a href="https://en.wikipedia.org/wiki/Fourier_series" target="_blank">Fourier series</a> was first
published by <a href="https://en.wikipedia.org/wiki/Joseph_Fourier" target="_blank">Joseph Fourier</a>
in 1822 (original work purportedly done in Egypt while serving under Napoleon)<br>
Note: Daniel Bernoulli and Leonhard Euler worked on this branch of mathematics before Fourier, but did not
publish (or properly publish)</li>
<li>The <a href="https://en.wikipedia.org/wiki/Fast_Fourier_transform" target="_blank">Fast Fourier Transform</a>
was first published in 1965 by J. W. Cooley and John Tukey while working at the research division of IBM<br>
Note: While working on a theory for planetary orbits, Carl Gauss proposed a solution very close to the 1965
FFT publication.</li>
<li>video: <a href="https://www.youtube.com/watch?v=nmgFG7PUHfo" target="_blank">
https://www.youtube.com/watch?v=nmgFG7PUHfo</a> (24 min)</li>
<li>video: <a href="https://www.youtube.com/watch?v=iOsGkk63NfE" target="_blank">
https://www.youtube.com/watch?v=iOsGkk63NfE</a> (9:47 min)</li>
</ul>
</li>
<li>Source Code:
<ul>
<li><a href="https://neilrieck.net/docs/python_notes.html" target="_blank">python: notes</a> - for people
new to python programming</li>
</ul>
</li>
</ul>
</div>
</body>
</html>
// ===========================================================================
// title : wave_demo_103.js
// author : Neil Rieck
// created: 2026-10-27
// ver who when what
// 103 NSR 2026-10-27 original effort (derived from fft_demo_103.js)
// notes :
// 1) this SPA (single page application) employs AJAX (Asynchronous JavaScript And XML)
// 2) this demo employs plain JavaScript in order to make things clearer to you
// 3) a real world application would employ jQuery and/or ReactJS or AngularJS
// 4) this demo employs HTTP GET. A real world application would use HTTP POST
// ===========================================================================
var JSFILE="wave_demo_103.js" // this js file
var PYFILE="wave_demo_103_loader" // python file to execute
var state=0; // ajax state
var timeOutId1=0; // timer ID
var debug=0; // 0:off 1:on (send xtra info to console)
var MINITEM=1; //
var MAXITEM=19; //
var a = new Map(); // amplitude
var h = new Map(); // harmonic (was: wave)
var SECS=15; //
var MS=SECS*1000; //
var nsr_domain=window.location.hostname; // server address
var nsr_protocol=window.location.protocol; // http or https
//
// init data
//
function initData(){
try{
for (var i=MINITEM; i<=MAXITEM; i++){
a.set("a"+i, ""); // ampl
h.set("h"+i, "false"); // harm
}
state=0;
if (timeOutId1!=0){
clearTimeout(timeOutId1);
timeOutId1=0;
}
}catch(e){
console.log("-e-initData: ",e);
}
}
function updateForm(){
try{
for (var i=MINITEM; i<=MAXITEM; i++){
document.getElementById("a"+i).value=a.get("a"+i);
tmp = h.get("h"+i);
updateCheckbox("h"+i, tmp);
}
}catch(e){
console.log("-e-updateForm: ",e);
}
}
//
// called by the RESET button
//
function doReset(){
console.log("-i-script: "+ JSFILE);
initData();
updateForm();
clearPixBuffer();
writeMsg("Reset Done");
}
function clearPixBuffer(){
try{
document.getElementById("pix_buffer1").innerHTML = "";
}catch(e){
console.log("-e-clearPixBuffer: ",e);
}
}
function writeMsg(x){
try{
// document.getElementById("msg").value=x; // if element is INPUT
document.getElementById("msg").innerHTML=x; // if element is DIV
}catch(e){
console.log("-i-writeMsg: ",x);
console.log("-e-writeMsg: ",e);
}
}
//
// called by the "SET DEFAULTS 1" button
//
function setDefaults1() {
send_ajax("setDefaults1");
}
//
// called by the "SET DEFAULTS 2" button
//
function setDefaults2() {
send_ajax("setDefaults2");
}
//
// called by the "SET DEFAULTS 3" button
//
function setDefaults3() {
send_ajax("setDefaults3");
}
//
// read form fields
//
function readFields(){
var tmp;
var label;
try{
for (var i=MINITEM; i<=MAXITEM; i++){
label="a"+i;
tmp=document.getElementById(label).value;
a.set(label, tmp);
// ---
label="h"+i;
tmp=document.getElementById(label).checked;
if (tmp==false){
h.set(label,"false");
}else{
h.set(label,"true")
}
}
}catch(e){
console.log("-w-readFields: "+label);
console.log("-e-readFields: ",e);
}
}
//
// build paramList
//
function paramList(){
var tmp="";
var out="";
var label;
try{
for (var i=MINITEM; i<=MAXITEM; i++){
label="a"+i;
tmp=a.get(label);
tmp=tmp.replace(/\s/g, "");
out+="&"+label+"="+tmp;
// ---
label="h"+i;
tmp=h.get(label);
tmp=tmp.replace(/\s/g, "");
out+="&"+label+"="+tmp;
}
}catch(e){
console.log("-w-paramList: ",label);
console.log("-e-paramList: ",e);
return;
}
return(out);
}
//
// called by the RUN DEMO button
//
function runDemo() {
var score=0;
var tmp;
readFields();
try{
for (var i=MINITEM; i<=MAXITEM; i++){
label="h"+i;
tmp = h.get(label);
// console.log("-i-runDemo: "+label, tmp, typeof(tmp));
if (typeof(tmp) == "string"){
if (tmp.toLowerCase() == "true"){
tmp = true;
}else{
tmp = false;
}
}
if (tmp==true) score++;
}
}catch(e){
console.log("-e-runDemo: "+label);
console.log("-e-runDemo:",e);
writeMsg("error, bad data detected");
return;
}
if (score==0){
writeMsg("error, no waves enabled");
return;
}
clearPixBuffer();
send_ajax("runDemo");
}
//
// send_ajax (send an HTTP message via AJAX)
//
function send_ajax(action){
var params=paramList();
switch(state){
case 0:
writeMsg("Connecting");
var msg = ""; // init
switch(action){
case "runDemo":
msg = (nsr_protocol +"//"+ nsr_domain +"/cgi-bin/"+
PYFILE +"?op="+ action + params);
console.log("msg:"+ msg);
start_ajax(msg);
break;
case "setDefaults1":
case "setDefaults2":
case "setDefaults3":
msg=nsr_protocol +"//"+ nsr_domain +"/cgi-bin/"+ PYFILE +"?op="+ action;
start_ajax(msg);
break;
default:
writeMsg("programmer error (001)");
break;
}
default:
writeMsg("Please wait up to "+SECS+" seconds (state:"+state+")");
break;
}
}
//
// start_ajax (start an AJAX transaction)
//
function start_ajax(cmd){
response=null;
if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest=function(){
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP") } catch (e) {}
throw new Error("This browser does not support XMLHttpRequest or XMLHTTP.")
}
if (cmd != ""){
//
// code to block AJAX caching
//
var dt = new Date(); // today's local date time on YOUR machine
var stamp = ""+ dt.getTime(); // millisecs since 1970-01-01
// console.log("time:",stamp);
//
// original code continues
//
response=new XMLHttpRequest();
if (response != null){
cmd += "×tamp=" + stamp; // to foil browser caching
console.log("cmd:",cmd);
response.onreadystatechange=ajax_event_handler;
response.open("GET", cmd, true); // async=true
response.send(null); // not null for POST
}
state = 1;
init_timer1();
}
}
//
// ajax_event_handler (only executed if something is received)
//
function ajax_event_handler(){
if (response.readyState == 4){
state=0;
if (timeOutId1!=0){
clearTimeout(timeOutId1);
timeOutId1=0;
}
if (response.status == 500) {
writeMsg("Server Error 500")
}
if (response.status == 200) {
writeMsg("Ready");
var resp$=response.responseText;
if (debug==1) {
console.log("raw data:"+htmlEncode(resp$));
}
if (window.DOMParser) {
parser=new DOMParser();
gXmlDoc=parser.parseFromString(resp$,"text/xml");
}else{
gXmlDoc=new ActiveXObject("Microsoft.XMLDOM");
gXmlDoc.async=false;
gXmlDoc.loadXML(resp$);
}
var msg = get_xml_data("msg");
var gra = get_xml_data("gra");
var status = get_xml_data("status");
clearPixBuffer();
// var status = 1;
if ((status == 1)||(status == 2)) {
// document.getElementById("msg").innerHTML="raw data:"+htmlEncode(resp$);
try{
for (var i=MINITEM; i<=MAXITEM; i++){
xml = get_xml_data("a"+i);
if (xml !=null) document.getElementById("a"+i).value=xml;
xml = get_xml_data("h"+i);
if (xml !=null) updateCheckbox("h"+i,xml);
}
}catch(e){
console.log("-e-ajax-event-handler: ",e)
}
if (msg!=null) writeMsg(msg);
if (gra!=null){
if (debug>0){
console.log("========== gra is not null ==========");
console.log(gra.length);
console.log(gra);
}
try{
var tmp = gra;
console.log("outputting received response");
if (1==0){
// this injects js properly, but nothing is executed
document.getElementById("pix_buffer1").innerHTML = gra;
}else{
// this injects js properly -AND- executes the js
myDiv = document.getElementById("pix_buffer1");
myDiv.innerHTML = gra;
const scripts = myDiv.getElementsByTagName('script');
for (let script of scripts) {
const freshScript = document.createElement('script');
if (script.src) {
freshScript.src = script.src;
}else{
freshScript.textContent = script.textContent;
}
document.body.appendChild(freshScript);
}
}
}catch(e){
console.log("error during data extract:",e);
}
}
}else{
writeMsg("error: "+status);
}
}
}
}
//
// string to boolean to checkbox on form
//
function updateCheckbox(id, state){
if (debug>0) console.log("updateCheckbox1: ",id,state,typeof(state));
if (typeof(state) == "string"){
if (state.toLowerCase() == "true"){
state = true;
}else{
state = false;
}
}
if (debug>0) console.log("updateCheckbox2: ",id,state,typeof(state));
try{
document.getElementById(id).checked=state;
}catch{
console.log("checked error: ",id,state);
}
}
//
// the server must answer back in 15 seconds
//
function init_timer1(){
if (timeOutId1==0){ // if available
timeOutId1=setTimeout("timer_job1();",MS); // arm timer
}
}
//
// this code is ONLY executed on TIMEOUT
//
function timer_job1(){
state=0; // reset state
if (timeOutId1!=0){
clearTimeout(timeOutId1);
timeOutId1=0;
}
var txt="Error: the timer has expired after "+SECS+" secs";
document.getElementById("msg").innerHTML=txt;
}
//
// does string 'x' represent a positive integer?
//
function isStrInt(x){
x=x.replace(/\s/g,'');
if (x=="") return false;
try{
y = parseInt(x);
}catch(e){
y = -1;
}
if(y>0){
return true;
}else{
return false;
}
}
function htmlEncode(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
// new decode
function htmlDecode(htmlString) {
const doc = new DOMParser().parseFromString(htmlString, 'text/html');
return doc.documentElement.textContent;
}
// old decode (supports IE11, etc.)
function htmlDecode9(text) {
var entities = [
['amp', '&'],
['apos', '\''],
['#x27', '\''],
['#x2F', '/'],
['#39', '\''],
['#47', '/'],
['lt', '<'],
['gt', '>'],
['nbsp', ' '],
['quot', '"']
];
for (var i = 0, max = entities.length; i < max; ++i)
text = text.replace(new RegExp('&' + entities[i][0] + ';', 'g'), entities[i][1]);
return text;
}
//
// get_xml_data (look for one item)
//
function get_xml_data(tag){
var x;
try{
x = gXmlDoc.getElementsByTagName(tag)[0].childNodes[0].nodeValue;
}catch(e){
// alert("t:"+tag+" e:"+e);
x = null;
}
return(x);
}
//
// get_xml_data2 (look for numerous similar items)
//
function get_xml_data2(xmlObj, tag){
var x;
try{
x = xmlObj.getElementsByTagName(tag)[0].childNodes[0].nodeValue;
}catch(e){
// alert("t:"+tag+" e:"+e);
x = null;
}
return(x);
}
function convertToJson() {
let form = document.getElementById("dataForm");
let formData = {};
for (let i = 0; i < form.elements.length; i++) {
let element = form.elements[i];
if (element.type !== "submit") {
formData[element.name] = element.value;
}
}
let jsonData = JSON.stringify(formData);
let jsonOutput = document.getElementById("jsonOutput");
jsonOutput.innerHTML = "<pre>" + jsonData + "</pre>";
}
//
// do this on initial file load
//
if (document.readyState === 'loading') {
// HTML is still parsing, wait for the event
document.addEventListener('DOMContentLoaded', doReset);
}else{
// HTML is already parsed, run immediately
doReset();
}
#!/usr/bin/python3 # ------------------------------------------------------ # title : /var/html/cgi-bin/wave_demo_103_loader # author : Neil Rieck # created: 2026-10-27 # purpose: import invokes the JIT compiler (.py -> .pyc) # ------------------------------------------------------ import wave_demo_103 wave_demo_103.main() #
#!/usr/bin/python3
# ====================================================================
# Title : wave_demo_103.py
# Author : Neil Rieck
# created : 2025-05-12
# notes :
# ver who when what
# 103 NSR 2026-10-27 original effort (derived from fft_demo_103.py
# ====================================================================
#
import math, sys, cgi, cgitb, os, datetime, markupsafe
import numpy as np
from numpy.fft import fft
#
# constants
#
FNAME = "wave_demo_103"
PATH = "wave-log/"
#
# globals (ugh!)
#
n_samples = 0 # number of samples (init)
ts = 0 # number of time slots (init)
t = 0 # time data (an array, after processing)
signal = "init" # composite signal data (an array, after processing)
debug = 0 # 0=off(web), 1=on(BASH shell)
dvlp = 0 # 0=off, 1=trace, 2=trace+data
#
# storage for input parameters
#
MINITEM=1 # lower design limit (a1,f1,w1)
MAXITEM=19 # upper design limit
h={} # harmonic data (was: wave)
a={} # ampl data
CYCLES=2 # number of waves
#
# generate one analog signal
#
# NOTE: freq is a number but sometimes may request NOISE
#
def generateSignal(freq=1.0, ampl=1.0):
global n_samples, ts, t
if n_samples == 0: # if first time (if init)
n_samples = 1000 # set number of samples
ts = 1.0 / n_samples # sampling interval (time slots)
# t = np.arange(0, 1, ts) # time
t = np.linspace(0, (n_samples)*ts, n_samples) #
if (type(freq) is str) and freq == "NOISE":
ana = ampl * np.random.normal(0, 2, n_samples)
else:
ana = ampl * np.sin(2 * np.pi * freq * t) # generate analog signal data (a numpy array)
return ana #
#
# text to int (called by processData) to process FREQ
#
def textToInt(data, label, wc):
msg = ""
try:
tmp = int(data)
except Exception:
tmp = 0
if (tmp > 999):
msg = f"Skipped Wave-{wc} because {label} > 999."
if (tmp < 1):
msg = f"Skipped Wave-{wc} because bad value for {label}."
return tmp, msg
#
# text to real (called by processData) to process AMPL
#
def textToFloat(data, label, wc):
msg = ""
try:
tmp = float(data)
except Exception:
tmp = 0.0
if (tmp > 99.9):
msg = f"Skipped Wave-{wc} because {label} > 99.9."
if tmp <= 0.0:
msg = f"Skipped Wave-{wc} because bad value for {label}."
return tmp, msg
#
# process data (single data set)
# note: this may be called numerous times (or once)
# params: w wave (a.h.a. harmonic number)
# f freq
# a ampl
# wc wave count
# sc signal count
# msg a running string
#
def processData(w, f, a, wc, sc, msg9):
global sr, ts, t, signal
wc += 1 # update 'wave count'
if (w == "true"): # if this item is checked
if (type(f) is str) and (f == "NOISE"):
# skipping numeric check of FREQ
freq = "NOISE"
msgF = ""
else:
freq, msgF = textToInt(f, "Freq", wc)
if msgF != "":
if msg9 != "":
msg9 += "\n"
msg9 += msgF
ampl, msgA = textToFloat(a, "Ampl", wc)
if msgA != "":
if msg9 != "":
msg9 += "\n"
msg9 += msgA
if (msgF == "") and (msgA == ""): # if both are okay
sc += 1 # update 'signal count'
x = generateSignal(freq, ampl) #
if dvlp >= 2:
logIt(f"{wc} {sc} {type(x)} {len(x)} {x}")
if (type(signal) is str) and (signal == "init"): # if first time
if dvlp >= 1:
logIt("copy")
signal = x.copy() # copy data as-is
else: # else
if dvlp >= 1:
logIt("merge")
signal += x.copy() # add the two data items
if dvlp >= 2:
logIt(f"9 9 {type(x)} {len(x)} {x}")
return wc, sc, msg9
#
# generate Graphical Data (only come here when we need to generate a graphic)
#
def generateGraphicalData():
global signal, n_samples, t
logIt("-i-generateGraphicalData()")
#
# call matplotlib etc.
#
os.environ['MPLCONFIGDIR'] = '/tmp'
if debug >= 1:
logIt("trace-1")
import matplotlib.pyplot as plt
#
# developer's recipe:
# 1- 9: mpld3
# 10-10: plotly
#
recipe = 16 # DEVELOPER CHOICE
logIt(f"recipe: {recipe}")
if recipe >= 10: # new way (python3.9 on AlmaLinux-9)
import plotly.graph_objects as go
import plotly.express as px
import plotly.io as pio
else: # old way (python3.9 on AlmaLinux-8)
import mpld3
#
# use: plotly
# notes: this code replaces mpld3 (see below) which stopped working after a server move
#
if recipe == 10: # DVLP: really simple demo (Plotly Express)
fig = px.line(x=[1, 2], y=[3, 4], title="Demo-10")
html_str = fig.to_html(full_html=False, include_plotlyjs=False, div_id="pix_buffer9")
''' <<<--- disabled code (start)
experimental code deleted (see older versions)
disabled code (stop) --->>> '''
if recipe == 15: # DVLP (FFT based upon static data)
from numpy import fft
from plotly.subplots import make_subplots
# 1. Generate a noisy composite signal
n_samples = 1000
dt = 0.001
t = np.linspace(0, (n_samples - 1) * dt, n_samples)
# Signal = 50 Hz sine wave + 120 Hz sine wave + random noise
signal = (
5 * np.sin(2 * np.pi * 50 * t)
+ 10 * np.sin(2 * np.pi * 120 * t)
+ np.random.normal(0, 2, n_samples)
)
# 2. Compute FFT
fft_values = np.fft.fft(signal)
fft_freq = np.fft.fftfreq(n_samples, dt)
# Keep only the positive frequencies
pos_mask = fft_freq >= 0
frequencies = fft_freq[pos_mask]
magnitudes = (2 / n_samples) * np.abs(fft_values[pos_mask])
# 3. Create interactive subplots with Plotly
fig = make_subplots(
rows=2, cols=1, subplot_titles=("Time Domain Signal", "Frequency Domain (FFT)")
)
# Time domain trace
fig.add_trace(
go.Scatter(x=t, y=signal, mode="lines", name="Signal", line=dict(color="blue")),
row=1,
col=1,
)
# Frequency domain trace
fig.add_trace(
go.Scatter(
x=frequencies,
y=magnitudes,
mode="lines",
name="FFT Magnitude",
line=dict(color="red"),
),
row=2,
col=1,
)
# Update layout
fig.update_xaxes(title_text="Time (s)", row=1, col=1)
fig.update_yaxes(title_text="Amplitude", row=1, col=1)
fig.update_xaxes(title_text="Frequency (Hz)", row=2, col=1)
fig.update_yaxes(title_text="Magnitude", row=2, col=1)
fig.update_layout(
height=600,
title_text="Interactive FFT Demo with Plotly",
showlegend=False,
)
html_str = pio.to_html(fig, full_html=False, include_plotlyjs=False, div_id="pix_buffer9")
if recipe == 16: # PROD (works like 15 but with variable data)
from numpy import fft
from plotly.subplots import make_subplots
# 1. Generate a noisy composite signal
'''
n_samples = 1000
dt = 0.001 # note: 1.0 seconds / 1000 = 0.001
t = np.linspace(0, (n_samples - 1) * dt, n_samples)
# Signal = 50 Hz sine wave + 120 Hz sine wave + random noise
signal = (
5 * np.sin(2 * np.pi * 50 * t)
+ 10 * np.sin(2 * np.pi * 120 * t)
+ np.random.normal(0, 2, n_samples)
)
'''
# dt = 0.001 # temp fix (for n_samples = 1000)
dt = 1.0 / float( n_samples ) # eg. 1000 = 0.001
# 2. Compute FFT
fft_values = np.fft.fft(signal)
fft_freq = np.fft.fftfreq(n_samples, dt)
# Keep only the positive frequencies
pos_mask = fft_freq >= 0
frequencies = fft_freq[pos_mask]
magnitudes = (2 / n_samples) * np.abs(fft_values[pos_mask])
# 3. Create interactive subplots with Plotly
fig = make_subplots(
rows=2, cols=1, subplot_titles=("Time Domain Signal", "Frequency Domain (FFT)")
)
# Time domain trace
fig.add_trace(
go.Scatter(x=t, y=signal, mode="lines", name="Signal", line=dict(color="blue")),
row=1,
col=1,
)
# Frequency domain trace
fig.add_trace(
go.Scatter(
x=frequencies,
y=magnitudes,
mode="lines",
name="FFT Magnitude",
line=dict(color="red"),
),
row=2,
col=1,
)
# Update layout
fig.update_xaxes(title_text="Time (s)", row=1, col=1)
fig.update_yaxes(title_text="Amplitude", row=1, col=1)
fig.update_xaxes(title_text="Frequency (Hz)", row=2, col=1)
fig.update_yaxes(title_text="Magnitude", row=2, col=1)
fig.update_layout(
height=600,
title_text="Interactive FFT Demo with Plotly (drag your mouse to zoom)",
showlegend=False,
)
html_str = pio.to_html(fig, full_html=False, include_plotlyjs=False, div_id="pix_buffer9")
#
# use: mpld3
# notes: these routines worked properly with mpdl3 (0.5.10) via python3.9 on AlmaLinux-8.
# After the move to AlmaLinux-9, I installed mpdl3 (0.5.12) which is now throwing errors
# with the lastest matplotlib (3.9.4). Rather than attempting to install older libraries,
# I abandonded this code (for now) then switched to plotly.
#
if recipe == 1: # DVLP: really simple demo
fig = plt.figure()
obj = plt.plot([3,1,4,1,5])
html_str = mpld3.fig_to_html(fig, figid='pix_buffer9', include_libraries=False)
''' <<<--- disabled code (start)
experimental code deleted (see older versions)
disabled code (stop) --->>> '''
return html_str #
#
# logIt (a simple logger)
# note: SELinux needs to allow this
#
def logIt(log):
stamp14 = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
try:
stamp8 = stamp14[:8]
fn=f"{PATH}{FNAME}_{stamp8}.txt"
f = open(fn,"a")
f.write(f"-i-event: {stamp14}\n"
f"-i-txt: {log}\n=====\n")
f.close()
except Exception as e:
if debug > 0: # only interactive mode
print(f"-e-error: {e}") #
if debug > 0: #
print(f"-i-txt: {log}") #
#
# build html to send parms back to Apache/Nginx
#
def htmlData():
global a,h
out = ""
for i in range(MINITEM, MAXITEM+1):
label = f"a{i}"
tmp = a[label]
if tmp == "":
tmp = " "
out += f"<{label}>{tmp}</{label}>"
#
label = f"h{i}"
tmp = h[label]
if tmp == "":
tmp = " "
out += f"<{label}>{tmp}</{label}>\n"
return out
#
# set default data
#
def defaultData(mode=1):
global a,h
for i in range(MINITEM, MAXITEM+1):
ampl = 1 / i # compute amplitude
a[f"a{i}"] = f"{ampl:.3f}"
if mode == 1: # Fundamental
h["h1"] = "true"
if mode == 2: # Odd Harmonics
for i in range(MINITEM, MAXITEM+1, 2):
h[f"h{i}"] = "true"
if mode == 3: # All Harmonics
for i in range(MINITEM, MAXITEM+1):
h[f"h{i}"] = "true"
#
# the name says it all
#
def main():
global debug,a,h
#
# declare/init a few variables
#
wc = 0 # wave count
sc = 0 # signal data
#
# declare a few program variables
#
method = os.environ.get('REQUEST_METHOD', "BLANK")
qs = os.environ.get('QUERY_STRING', "BLANK")
#
# a little hook for interactive testing
#
if method == "BLANK":
debug = 1
print("-i-interactive debug mode")
print(f"-i-QUERY_STRING: {qs} (from your shell)")
else:
debug = 0
#
# extract CGI field data
#
fld = cgi.FieldStorage(keep_blank_values=True) # grab all CGI data
for i in range(MINITEM, MAXITEM+1):
label = f"h{i}" # harm
h[label] = fld.getvalue(label, '')
label = f"a{i}" # freq
a[label] = fld.getvalue(label, '')
op = fld.getvalue('op', 'setDefaults1')
msg = ""
gra = ""
#
log = (f"qs: '{qs}'\n"
f"{h}\n"
f"{a}\n"
f"m : {method}")
logIt(log)
#
# send a response back to Apache/Nginx
# note: some popular return types include text/html, text/xml, text/plain
#
resp = ('Content-Type: text/xml; charset=windows-1252\n' # we're returning an XML response
'\n' # this marks the end of the HTTP header
'<?xml version="1.0" encoding="iso-8859-1"?>\n' # start of XML content
'<result>\n') # user-defined by me (see JavaScript)
if (op=="setDefaults1"): # user hit button-1
defaultData(1) #
tmp = htmlData() #
resp += ('<status>1</status>\n'
f'{tmp}'
'<msg>Fundamental</msg>\n')
elif op=="setDefaults2": # user hit button-2
defaultData(2) #
tmp = htmlData() #
resp += ('<status>1</status>\n'
f'{tmp}'
'<msg>Odd Harmonics</msg>\n')
elif op=="setDefaults3": # user hit button-3
defaultData(3) #
tmp = htmlData() #
resp += ('<status>1</status>\n'
f'{tmp}'
'<msg>All Harmonics</msg>\n')
elif op=="runDemo": # user hit button-4
try:
for i in range(MINITEM, MAXITEM+1):
ampl = a[ f"a{i}" ]
harm = h[ f"h{i}" ]
freq = i * CYCLES #
wc, sc, msg = processData(harm, freq, ampl, wc, sc, msg)
if msg != "":
msg += "\n<br>"
msg += f"Signal count: {sc}"
# logIt(f"msg: {msg}")
status = 1
if (sc > 0): # if we generated at least one signal
gra = generateGraphicalData()
else:
gra = ""
log = (f"status: {status}\n"
f"msg: {msg}")
logIt(log)
except Exception as e:
status = 95
msg = f"{e}"
logIt(msg)
#
# since we're sending back XML it might be wise to escape the data
#
gra2 = markupsafe.escape(gra)
msg2 = markupsafe.escape(msg)
resp += ('<status>'+ str(status) +'</status>\n'
f'<msg>{msg2}</msg>\n'
f'<gra>{gra2}</gra>\n')
else: # this should never happen
resp = ('<status>1</status>\n'
'<msg>Program Defaults #1</msg>\n')
resp += ('</result>\n')
# logIt(resp)
print(resp) # this goes to Apache
sys.exit() # no more work to do
#
# boilerplate
#
if __name__ == '__main__':
main()
#
# this is the last line
Back to Home