Nugroho's blog.: Python
Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Tuesday, October 20, 2015

Working with Audio in Python

 What I did is read a .wav file, extract the raw audio data, (I use first 1/20 data for sample), transform it using Fast Fourier Transform, manipulate it (I only use the first cluster frequency spectrum ), transform it back using InverseFFT.

 I use matplotlib and numpy module to plot and compute.

 I also use sys and wave module as 'interface'.


import matplotlib.pyplot as plt
import numpy as np
import wave
import sys


spf = wave.open('violin2.wav','r')

#Extract Raw Audio from Wav File
signal = spf.readframes(-1)
signal = np.fromstring(signal, 'Int16')
fs = spf.getframerate()
print fs

#If Stereo
if spf.getnchannels() == 2:
print 'Just mono files'
sys.exit(0)

Time=np.linspace(0, len(signal)/fs, num=len(signal))
sample = []
st=[]
for i in np.arange(len(signal)/20):
sample.append( signal[i])
st.append(Time[i])

ft=np.fft.fft(sample)
pft=[]
for i in np.arange(len(ft)):
if i<500: data-blogger-escaped-ample="" data-blogger-escaped-else:="" data-blogger-escaped-from="" data-blogger-escaped-ft="" data-blogger-escaped-i="" data-blogger-escaped-ift="" data-blogger-escaped-ignal="" data-blogger-escaped-ime="" data-blogger-escaped-pft.append="" data-blogger-escaped-pft="" data-blogger-escaped-plt.figure="" data-blogger-escaped-plt.grid="" data-blogger-escaped-plt.plot="" data-blogger-escaped-plt.show="" data-blogger-escaped-plt.title="" data-blogger-escaped-pre="" data-blogger-escaped-rue="" data-blogger-escaped-sample="" data-blogger-escaped-signal="" data-blogger-escaped-st="" data-blogger-escaped-wave...="">
.





Wednesday, October 7, 2015

Lagrange Interpolation using Python

 Here it is. We could set the order of interpolation by changing the value of k


from pylab import *
from random import uniform
k = 11

def l(t):
l = []
for i in arange (len(t)):
l.append(0.)
for j in arange(k+1):
lag = 1.
for m in arange(k+1):
if m!=j:
lag = lag * (t[i]-x[m])/(x[j]-x[m])
l[i] = l[i]+y[j]*lag


return l

def f(x):
f = []
for i in arange (len(x)):
f.append(0.)
f[i] = x[i]+uniform(-10,10)
return f

x = arange(0.0, 2.0, 0.1)
t = arange(0.,2.,0.001)
y = f(x)
z = l(t)

plot(x,y)
plot(t,z)
xlabel('x')
ylabel('y')
title('interpolasi')
grid(True)
axis([0,2,-111,111])
#savefig("test.png")
show()

.

Monday, October 5, 2015

Walking Sine on Visual Python GDisplay

 Look, the wrong way often provide a beautiful result. Yeah, it's not what the program should be, but still I like it, :)


from __future__ import division, print_function
from visual import *
from visual.graph import *

def f(x):
f = sin(pi*x+p)
return f
def g(x):
g = cos(pi*x)
return g

graph1 = gdisplay(x=0, y=0, width=600, height=400,
title='A vs. t', xtitle='t', ytitle='A',
foreground=color.black, background=color.white)
p = 0.
f1 = gcurve(color=color.blue)
f2 = gcurve(color=color.red)

t = arange(-2.,2.,0.01)
s = g(t)
while True:
rate(100)
f1.gcurve.pos=[] #delete this and look at the effect :)
f2.gcurve.pos=[]
u = f(t)
for i in arange(len(s)):
f2.plot(pos=((i-len(s)/2.)*.01,s[i]))
f1.plot(pos=((i-len(s)/2.)*.01,u[i]))
p = p + 0.01
if p >100:
p = 0



















Friday, September 25, 2015

Update Value using Slider in Visual Python


 Here's the code.
 The slider act as..., well..., slider... to change the value on TextCtrl. On slight modification, it'll able to change any variable value.



from __future__ import division, print_function
from visual import *
import wx

L = 400
H = 200
d = 20


def setrate(evt):
value = s1.GetValue()
tc.Clear()
tc.write('kecepatan = '+ str(value)) #mengeset kecepatan sesuai slider


w = window(width=2*(L+window.dwidth), height=L+window.dheight+window.menuheight+H,
menus=True, title='Widgets',
style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX)

#panel#
p = w.panel

tc = wx.TextCtrl(p, pos=(1.4*L,90), value='Tulisan\n',
size=(150,90), style=wx.TE_MULTILINE)
tc.SetInsertionPoint(len(tc.GetValue())+1)
tc.SetFocus()

s1 = wx.Slider(p, pos=(1.0*L,0.8*L), size=(0.9*L,20), minValue=0, maxValue=100)
s1.Bind(wx.EVT_SCROLL, setrate)
wx.StaticText(p, pos=(1.0*L,0.75*L), label='kecepatan')

#standart mantra for vpython#
while True:
rate(100)

.
.
 

Update Visual.Graph Python

 The code below's from vpython example program, modified here and there, of course, :). It plots 5.0+5.0*cos(-0.2*t-p)*exp(0.015*t). Notice that p is act as phase, so the plot will 'walk'. The essential part is

 funct1.gcurve.pos=[]

 without it, the graph wont refresh the old curve (the old plot wouldn't be erased)



from __future__ import division, print_function
from visual import *
from visual.graph import *
import wx

L = 400
H = 200

w = window(width=2*(L+window.dwidth), height=L+window.dheight+window.menuheight+H,
menus=True, title='Widgets',
style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX)

funct1 = gcurve(color=color.cyan)

p = 0.

while True:
rate(100)
funct1.gcurve.pos=[]
for t in arange(-30, 74, 1):
funct1.plot( pos=(t, 5.0+5.0*cos(-0.2*t-p)*exp(0.015*t)) )
p = p + 0.1
if p >100:
p = 0

.



.
 

Monday, December 22, 2014

Compare Native Loop Time in Python with "homemade" Fortran Module

This code print d and e as result of two matrix addition, e's using python native code, d's using fortran module compiled with F2PY

The code
import numpy as np
import aravir as ar
import time

n = 1000

u = np.ones((n,n))
v = np.ones((n,n))
e = np.ones((n,n))

t = time.clock()
d = ar.add3(u,v)
tfortran= time.clock()-t

t = time.clock()
for i in range (n):
for j in range (n):
e[i,j] = u[i,j]+v[i,j]
tnative = time.clock()-t

print 'fortran ', d
print 'native', e
print 'tfortran = ', tfortran, ', tnative = ', tnative


The fortran module I imported to python
        subroutine add3(a, b, c, n)
double precision a(n,n)
double precision b(n,n)
double precision c(n,n)

integer n
cf2py intent(in) :: a,b
cf2py intent(out) :: c,d
cf2py intent(hide) :: n
do 1700 i=1, n
do 1600 j=1, n
c(i,j) = a(i,j)
$ +b(i,j)

1600 continue
1700 continue
end

save it as aravir.f and compile using
$ f2py -c aravir.f -m aravir

And here the result
$ python cobamodul.py 
fortran [[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]
...,
[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]]
native [[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]
...,
[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]]
tfortran = 0.069974 , tnative = 1.202547

The Desktop, :)


Friday, December 19, 2014

Using 'Home-Made' Fortran Binary as Python module

Python is easy to use, but it's slow, especially for loop computation. So I compute it using fortran like this

        subroutine subs(a, b, n)
double precision a(n)
double precision b(n)
integer n
cf2py intent(in) :: a
cf2py intent(out) :: b
cf2py intent(hide) :: n
! b(1) = a(1)
do 100 i=2, n
b(i) = a(i)-1
100 continue
end


save it as aravir.py and do the following command
$ f2py -c aravir.f -m aravir

To use the module on the python I use the code below
import numpy as np
import aravir as ar

a = np.linspace(0,1,100)

b = ar.subs(a)

print a
print b

:)


3D Waterwave Simulation using Python

I used Numpy  Matplotlib with Animation and 3d Plot module on my OS X Yosemite.

The code is still messy and clearly not efficient (there's slow loop here and there) but it works, :)
Here The Result
The Code
import numpy as np

n = 8;
g = 9.8;
dt = 0.02;
dx = 1.0;
dy = 1.0;

h = np.ones((n+2,n+2))
u = np.zeros((n+2,n+2))
v = np.zeros((n+2,n+2))

hx = np.zeros((n+1,n+1))
ux = np.zeros((n+1,n+1))
vx = np.zeros((n+1,n+1))

hy = np.zeros((n+1,n+1))
uy = np.zeros((n+1,n+1))
vy = np.zeros((n+1,n+1))

nsteps = 0
h[1,1] = .5;

def reflective():
h[:,0] = h[:,1]
h[:,n+1] = h[:,n]
h[0,:] = h[1,:]
h[n+1,:] = h[n,:]
u[:,0] = u[:,1]
u[:,n+1] = u[:,n]
u[0,:] = -u[1,:]
u[n+1,:] = -u[n,:]
v[:,0] = -v[:,1]
v[:,n+1] = -v[:,n]
v[0,:] = v[1,:]
v[n+1,:] = v[n,:]

def proses():
#hx = (h[1:,:]+h[:-1,:])/2-dt/(2*dx)*(u[1:,:]-u[:-1,:])
for i in range (n+1):
for j in range(n):
hx[i,j] = (h[i+1,j+1]+h[i,j+1])/2 - dt/(2*dx)*(u[i+1,j+1]-u[i,j+1])
ux[i,j] = (u[i+1,j+1]+u[i,j+1])/2- dt/(2*dx)*((pow(u[i+1,j+1],2)/h[i+1,j+1]+ g/2*pow(h[i+1,j+1],2))- (pow(u[i,j+1],2)/h[i,j+1]+ g/2*pow(h[i,j+1],2)))
vx[i,j] = (v[i+1,j+1]+v[i,j+1])/2 - dt/(2*dx)*((u[i+1,j+1]*v[i+1,j+1]/h[i+1,j+1]) - (u[i,j+1]*v[i,j+1]/h[i,j+1]))

for i in range (n):
for j in range(n+1):
hy[i,j] = (h[i+1,j+1]+h[i+1,j])/2 - dt/(2*dy)*(v[i+1,j+1]-v[i+1,j])
uy[i,j] = (u[i+1,j+1]+u[i+1,j])/2 - dt/(2*dy)*((v[i+1,j+1]*u[i+1,j+1]/h[i+1,j+1]) - (v[i+1,j]*u[i+1,j]/h[i+1,j]))
vy[i,j] = (v[i+1,j+1]+v[i+1,j])/2 - dt/(2*dy)*((pow(v[i+1,j+1],2)/h[i+1,j+1] + g/2*pow(h[i+1,j+1],2)) - (pow(v[i+1,j],2)/h[i+1,j] + g/2*pow(h[i+1,j],2)))

for i in range (1,n+1):
for j in range(1,n+1):
h[i,j] = h[i,j] - (dt/dx)*(ux[i,j-1]-ux[i-1,j-1]) - (dt/dy)*(vy[i-1,j]-vy[i-1,j-1])
u[i,j] = u[i,j] - (dt/dx)*((pow(ux[i,j-1],2)/hx[i,j-1] + g/2*pow(hx[i,j-1],2)) - (pow(ux[i-1,j-1],2)/hx[i-1,j-1] + g/2*pow(hx[i-1,j-1],2))) - (dt/dy)*((vy[i-1,j]*uy[i-1,j]/hy[i-1,j]) - (vy[i-1,j-1]*uy[i-1,j-1]/hy[i-1,j-1]))
v[i,j] = v[i,j] - (dt/dx)*((ux[i,j-1]*vx[i,j-1]/hx[i,j-1]) - (ux[i-1,j-1]*vx[i-1,j-1]/hx[i-1,j-1])) - (dt/dy)*((pow(vy[i-1,j],2)/hy[i-1,j] + g/2*pow(hy[i-1,j],2)) - (pow(vy[i-1,j-1],2)/hy[i-1,j-1] + g/2*pow(hy[i-1,j-1],2)))

#dh = dt/dt*(ux[1:,:]-ux[:-1,:])+ dt/dy*(vy[:,1:]-vy[:,:-1])
reflective()
return h,u,v
'''
for i in range (17):
#print h
proses(1)
'''

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from mpl_toolkits.mplot3d import Axes3D
a = n
x = np.arange(n+2)
y = np.arange(n+2)
x,y = np.meshgrid(x,y)

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

def plotset():
ax.set_xlim3d(0, a)
ax.set_ylim3d(0, a)
ax.set_zlim3d(0.5,1.5)
ax.set_autoscalez_on(False)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
cset = ax.contour(x, y, h, zdir='x', offset=0 , cmap=cm.coolwarm)
cset = ax.contour(x, y, h, zdir='y', offset=n , cmap=cm.coolwarm)
cset = ax.contour(x, y, h, zdir='z', offset=.5, cmap=cm.coolwarm)

plotset()

surf = ax.plot_surface(x, y, h,rstride=1, cstride=1,cmap=cm.coolwarm,linewidth=0,antialiased=False, alpha=0.7)

fig.colorbar(surf, shrink=0.5, aspect=5)


from matplotlib import animation


def data(k,h,surf):
proses()
ax.clear()
plotset()
surf = ax.plot_surface(x, y, h,rstride=1, cstride=1,cmap=cm.coolwarm,linewidth=0,antialiased=False, alpha=0.7)
return surf,

ani = animation.FuncAnimation(fig, data, fargs=(h,surf), interval=10, blit=False)
#ani.save('air.mp4', bitrate=512)
plt.show()

and the snapshot






Thursday, December 18, 2014

3D Surface Plot Animation using Matplotlib in Python

And here's the animation
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D

def data(i, z, line):
    z = np.sin(x+y+i)
    ax.clear()
    line = ax.plot_surface(x, y, z,color= 'b')
    return line,

n = 2.*np.pi
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = np.linspace(0,n,100)
y = np.linspace(0,n,100)
x,y = np.meshgrid(x,y)
z = np.sin(x+y)
line = ax.plot_surface(x, y, z,color= 'b')

ani = animation.FuncAnimation(fig, data, fargs=(z, line), interval=30, blit=False)

plt.show()

The result

The snapshot



3D Surface Plot using Matplotlib in Python

It's slightly modified from before

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D

n = 2.*np.pi
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = np.linspace(0,n,100)
y = np.linspace(0,n,100)
x,y = np.meshgrid(x,y)
z = np.sin(x+y)
line = ax.plot_surface(x, y, z,color= 'b')

plt.show()


the result


the snapshot



Wednesday, December 17, 2014

Matplotlib Animation in Python

Here is the update from before

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def simData():
t_max = n
dt = 1./8
k = 0.0
t = np.linspace(0,t_max,100)
while k < t_max:
x = np.sin(np.pi*t+np.pi*k)
k = k + dt
yield x, t

def simPoints(simData):
x, t = simData[0], simData[1]
line.set_data(t, x)
return line
n = 2.
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([], [], 'b')
ax.set_ylim(-1, 1)
ax.set_xlim(0, n)

ani = animation.FuncAnimation(fig, simPoints, simData, blit=False,\
interval=100, repeat=True)
plt.show()

and the result

Tuesday, December 16, 2014

Playing with Matplotlib Animation in Python

Coding like this

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure()
n = 10
x = np.linspace(0,2*np.pi,100)



def init():
pass
def animate(k):
h = np.sin(x+np.pik)
plt.plot(x,h)


ax = plt.axes(xlim=(0, 2*np.pi), ylim=(-1.1, 1.1))

anim = animation.FuncAnimation(fig, animate,init_func=init,frames=360,interval=20,blit=False)

plt.show()

The result

Thursday, November 7, 2013

Laggy Mavericks and QuickLook that Neither Quick nor Look on Anything

Don't know what happened, but my Maverick is getting slower and slower.

QuickLook can't preview .f,  .py and .tex files (and other files type too as I tried to "quick-looking" other type but fortran, python and latex  is what I "quick-looking" most).

Tuesday, November 13, 2012

2D/3D Ball Collision

I used on 1D collission problem where, in case of elastic collision, the ball is changing velocity each other. In 2D/3D case however, the collision is not always head-on collision (which is basically 1 dimension collision).

Head-on
The system above's easy too solve, as simple as interchanging velocity (in elastic case).




Not head-on

When two balls are in non-head-on collision we could always using transposed new coordinate where both of ball center are on the new x-axis like below



On the new coordinate, we can treat the velocities along x-axis as one dimensional collision case and let go on other component (y, z) intact.

Below's snippet from python code of balls collision detection; the whole code is code of moving many ball on a box.

###deteksi tumbukan antar bola
for i in arange(jumlah):
for j in arange(i+1,jumlah):
jarak=mag(lbola[i].pos-lbola[j].pos)
if jarak<(lbola[i].radius+lbola[j].radius):
arah=norm(lbola[j].pos-lbola[i].pos)
vi=dot(lbola[i].v,arah)
vj=dot(lbola[j].v,arah)
tukar=vj-vi
lbola[i].v=lbola[i].v+tukar*arah
lbola[j].v=lbola[j].v-tukar*arah
pantul=lbola[i].radius+lbola[j].radius-jarak
lbola[i].pos=lbola[i].pos-pantul*arah
lbola[j].pos=lbola[j].pos+pantul*arah

Wednesday, September 19, 2012

Simulate Circular Motion using Visual Python


This little code below show how to move an object in VPython. There’s two object in program, a box and a sphere. The latter object move in circular using simple sin and cos formula. 

I set the angular speed 10 and radius of the motion (not the sphere) is 10. I use label to show sphere’s x and y position. 

Here the result





Here the code

from visual import *

kotak = box(pos=vector(0, 0, 0), length=14, height=14, width=1, color = (0.7,0.7,0.7))

ball=sphere(color=color.green,radius=5)
ball.pos=vector(10,10,0)

timestep = 0.05
a=10
t = .0
omega= 10
px = label(pos=(0,-1,0), text='x = %1.5f' % pi)
py = label(pos=(0,+1,0), text='y = %1.5f' % pi)
while (1==1):
rate(100)
ball.pos.x = a*sin(omega*t)
ball.pos.y = a*cos(omega*t)
px.text = 'x = %1.5f' % ball.pos.x
py.text = 'y = %1.5f' % ball.pos.y
t=t+0.01

Monday, December 19, 2011

Python-based Web Page to Compute Function with User Input Flexible Function

This is improved from my python-based web based to display function. In this version, users have ability to input a function and then display it with it value for given variable to python-based web page.

The code below will get input from users (if no input, the default value is sin(x)), parsed it to function python understand, and then eval it for given variable (in this code, x=10). After computed, it's inserted to template that resembling html code. Thus, since it's displayed in html style, we could add our customization (background, css, etc)



Here's the code


#!/usr/bin/python
# -*- coding: utf-8 -*-
import BaseHTTPServer, urllib, re
import sys,parser
from math import *

class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
    template = u"""<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd"><html><head><title>%s</title>
        </head><body><h1>%s</h1><pre>%s</pre>Function<form action="" method="POST"
        class="editor"><div><textarea name="text">%s</textarea><input type="submit"
        value="Compute"></div></form></body></html>"""
    
    def escape_html(self, text):
        """Replace special HTML characters with HTML entities"""
        return text.replace(
                            "&", "&amp;").replace(">", "&gt;").replace("<", "&lt;")
    
    def link_repl(self, match):
        """Return HTML for link"""
        title = match.group(1)
        if title in self.server.pages:
            return u"""<a href="%s">%s</a>""" % (title, title)
        return u"""%s<a href="%s">?</a>""" % (title, title)
    
    def do_HEAD(self):
        """Send response headers"""
        self.send_response(200)
        self.send_header("content-type", "text/html;charset=utf-8")
        self.end_headers()
    
    def do_GET(self):
        """Send page text"""
        self.do_HEAD()
        page = self.escape_html(urllib.unquote(self.path.strip('/')))
        text = self.escape_html(self.server.pages.get(page, "sin(x)"))
        parsed = re.sub(r"\[\[([^]]+)\]\]", self.link_repl, text)
        #hitung fungsi
        fungsi=parser.expr(parsed).compile()
        x = 10
        y = eval(fungsi)
        tout = 'The value of  ',parsed, ' on x = ',x,' is ',y
        tout = str(tout)
        tout = re.sub(r",", "", tout)
        tout = re.sub(r"\'", "", tout)
        tout= tout[1:]
        tout= tout[:-1]
        self.wfile.write(self.template % (page, page, tout, text))
    
    def do_POST(self):
        """Save new page text and display it"""
        length = int(self.headers.getheader('content-length'))
        if length:
            text = self.rfile.read(length)
            page = self.escape_html(urllib.unquote(self.path.strip('/')))
            self.server.pages[page] = urllib.unquote_plus(text[5:])
        self.do_GET()

if __name__ == '__main__':
    server = BaseHTTPServer.HTTPServer(("", 8080), Handler)
    server.pages = {}
    server.serve_forever()

Here's the screenshot
From python

Sunday, December 18, 2011

User Input on Python during Runtime

Eventually, we want interactivity when executing Python script. We want user to give input for some variable. It'll useful for, lets call, application form where user have to input her/his name, age, etc. On math field, user will have flexibility to input the function and range of variable used to computation.



There is raw_input command and input command we can used.

raw_input command will translate all we type to string, while input command treat it as command

Here difference between the two

raw_input
x=raw_input('type anything \n')
print 'you typed ', x

Execute it
Nugrohos-MacBook-Pro:python nugroho$ python input.py 
type anything
a
you typed a
Nugrohos-MacBook-Pro:python nugroho$ python input.py
type anything
12
you typed 12
Nugrohos-MacBook-Pro:python nugroho$ python input.py
type anything
sin(x)+x**2
you typed sin(x)+x**2
Nugrohos-MacBook-Pro:python nugroho$

input
c='sin(x)+x**2'
me='Hello folks, Aravir here'
x=input('type anything \n')
print 'you typed ', x

Execute it
Nugrohos-MacBook-Pro:python nugroho$ python input.py 
type anything
a
Traceback (most recent call last):
File "input.py", line 3, in
x=input('type anything \n')
File "", line 1, in
NameError: name 'a' is not defined
Nugrohos-MacBook-Pro:python nugroho$ python input.py
type anything
12
you typed 12
Nugrohos-MacBook-Pro:python nugroho$ python input.py
type anything
sin(x)+x**2
Traceback (most recent call last):
File "input.py", line 3, in
x=input('type anything \n')
File "", line 1, in
NameError: name 'sin' is not defined
Nugrohos-MacBook-Pro:python nugroho$ python input.py
type anything
c
you typed sin(x)+x**2
Nugrohos-MacBook-Pro:python nugroho$ python input.py
type anything
me
you typed Hello folks, Aravir here
Nugrohos-MacBook-Pro:python nugroho$

Displaying Calculation Output of Python on Web (customizing)

After success displaying output using python based web, it's normal if we want to display the value of function with a range of variable.

The code below will create web page hosted by Python 2.7 BaseHttpServer module. The page contains list of value of function sin(x)+x**2 at -7<x<7



from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import sys,parser
from math import *
import numpy as np

class Handler(BaseHTTPRequestHandler):
def do_GET(self):
n=10
x1=-7
x2=7
y = 'sin(x)+x**2'
z = parser.expr(y).compile()

self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()

self.wfile.write("Hi Folks, Aravir here")
self.wfile.write("")
self.wfile.write("Hi Folks, Aravir here
")
self.wfile.write("
")
for i in (range(x1,x2)):
x=i
self.wfile.write("The value of ")
self.wfile.write(y )
self.wfile.write(" on x = " )
self.wfile.write(x)
self.wfile.write(" is " )
self.wfile.write(eval(z) )
self.wfile.write("
")

self.wfile.write("")

if __name__=="__main__":
try:
server = HTTPServer(("", 8080), Handler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()


Here the result in Safari, Mac OS X Lion

From python

Displaying Calculation Output of Python Script to Web Page using Python-based Web Server

It'll be convenient if we could displaying output from our Python code to web page.

To convert calculation output of Python script to web page we need BaseHTTPServer, a Python-based web server. With it, we could write any python code and display it in no time. It has advantage in form of simplicity, we don't need php to convert our result or typing it to static html code, we just used python alone (it's possible to write html and php code on python though).
This code below will display python script calculating value of a function (sin(x)+x^2) to web page. As it behave as web server too, we don't need apache or other web server to broadcast it.

Here the code. It's written in Python 2.7 on Mac OS X Lion with numpy module and sys, parser and basehttpserver built in module.

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import sys,parser
from math import *
import numpy as np

class Handler(BaseHTTPRequestHandler):
def do_GET(self):
n=10
x=7
y = 'sin(x)+x**2'
z = parser.expr(y).compile()

self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()

self.wfile.write("Hi Folks, Aravir here")
self.wfile.write("")
self.wfile.write("Hi Folks, Aravir here
")
self.wfile.write("
")
self.wfile.write("The value of ")
self.wfile.write(y )
self.wfile.write(" on x = " )
self.wfile.write(x)
self.wfile.write(" is " )
self.wfile.write(eval(z) )

self.wfile.write("")

if __name__=="__main__":
try:
server = HTTPServer(("", 8080), Handler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()

Access it using web browser in localhost:8080 from your computer running code above, or :8080 and get this


From python

Creating Web Page using Python including its Webserver (basehttpserver module)

It's possible to create web page using Python, even self hosted it using Python built in webserver (basehttpserver module)

Here the code. It'll create web server with port 8080 and if it's accessed, it'll show a page. In the code below, page showed for us is just plain text "magic content goes here". I am planning to investigate this self.wfile.write behavior.




from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()

self.wfile.write("magic content goes here")

if __name__=="__main__":
try:
server = HTTPServer(("", 8080), Handler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()

Access with browser in address localhost:8080 or <whatever your ip address>:8080 and get this

From python

323f (5) amp (1) android (12) apple (7) arduino (18) art (1) assembler (21) astina (4) ATTiny (23) blackberry (4) camera (3) canon (2) cerita (2) computer (106) crazyness (11) debian (1) delphi (39) diary (286) flash (8) fortran (6) freebsd (6) google apps script (8) guitar (2) HTML5 (10) IFTTT (7) Instagram (7) internet (12) iOS (5) iPad (6) iPhone (5) java (1) javascript (1) keynote (2) LaTeX (6) lazarus (1) linux (29) lion (15) mac (28) macbook air (8) macbook pro (3) macOS (1) Math (3) mathematica (1) maverick (6) mazda (4) microcontroler (35) mountain lion (2) music (37) netbook (1) nugnux (6) os x (36) php (1) Physicist (29) Picture (3) programming (189) Python (109) S2 (13) software (7) Soliloquy (125) Ubuntu (5) unix (4) Video (8) wayang (3) yosemite (3)