#!/usr/bin/python
# -*- coding: utf8 -*-

import os,sys,re

import cgi
import cgitb
cgitb.enable()

from tempfile import mktemp

# set HOME environment variable to a directory the httpd server can write to
os.environ[ 'HOME' ] = '/tmp/'

import matplotlib
# chose a non-GUI backend
matplotlib.use( 'Agg' )

import pylab as l
import numpy as n
from pylab import pi

from matplotlib import rcParams #, rc
#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})

rcParams['text.usetex']=True
rcParams['text.latex.unicode']=True
print "Content-type: text/html; Charset=utf-8\n"
print """
<html>
<head><title>Gama článek RC, RL</title></head>
<body>
<h1>Horní a dolní propust RC, RL</h1>
"""

form = cgi.FieldStorage()
val = re.compile(r'^[-+\w\.]+$')
for f in form.keys():
    if (val.match(form[f].value) == None):
        print f,"  ",form[f].value
        print 'Ee eeee'
        print '<a href="./gamaRCRL.cgi">znovu</a>'
        exit()

#if "fi" in form:
#    if (validate.match(form['fi'].value) == None):
#        print "zadej sem číslo"
#        form['fi'].value = "33"
#    try:
#        angle = float(form['fi'].value)
#    except:
#        angle = 30
#else:
#    angle = 30

Z1value, Z2value, fa = '', '', ''

## musím zjistit mezní mitočet
#         1          R
# fm = -------- = --------
#       2πRC        2πL
stop = False
sel =r'selected="sel"' 

testForm = ("Z1type" in form)and('Z1value' in form)and("Z2type" in form)and\
        ('Z2value' in form)and('f' in form)
testGen  = 'gen' in form

if testForm or testGen:
    
    if testForm:
        fa = float(form['f'].value)
        Z1type, Z2type = form['Z1type'].value, form['Z2type'].value
        Z1value, Z2value = float(form['Z1value'].value), float(form['Z2value'].value)
    if testGen:
        import random
        randR = random.uniform(10,10e3)
        randL = random.uniform(1e-6,100e-3)
        randC = random.uniform(1e-9,10e-3)
        parts = set('RLC')
        Z1type = random.choice(list(parts))
        if Z1type == 'R':
            parts -= set('R')
            Z2type = random.choice(list(parts))
        else:
            Z2type = 'R'

        if Z1type=='R':
            Z1value=randR
        if Z1type=='L':
            Z1value=randL
        if Z1type=='C':
            Z1value=randC
        if Z2type=='R':
            Z2value=randR
        if Z2type=='L':
            Z2value=randL
        if Z2type=='C':
            Z2value=randC
    
# Mezní kmitočet
    if set('RC') <= set([Z1type, Z2type]):
        fm = 1/(2*pi*Z1value*Z2value)
    elif Z1type == 'L' and Z2type == 'R':
        fm = Z2value/(2*pi*Z1value)
    elif Z1type == 'R' and Z2type == 'L':
        fm = Z1value/(2*pi*Z2value)
    else:
        stop = True

    if testGen:
        fa = random.uniform(0.5*fm,5*fm)

    Z1sel = ['','','']
    Z2sel = ['','','']
    Z1sel[ list("RLC").index(Z1type) ] = sel
    Z2sel[ list("RLC").index(Z2type) ] = sel
else:
    Z1sel = [sel,'','']
    Z2sel = ['','',sel]
## Formulář
print """
<p>
    <img src="data/z1z2.png" alt="gama článek" />
</p>

<form  method="get">
<p>
    Z1: <select name="Z1type">
            <option value="R" {1[0]}>R [Ω]</option>
            <option value="L" {1[1]}>L [H]</option>
            <option value="C" {1[2]}>C [F]</option>
        </select>
        <input type="text" name="Z1value" value="{0[0]}" />
</p>
<p>
    Z2: <select name="Z2type">
            <option value="R" {2[0]}>R [Ω]</option>
            <option value="L" {2[1]}>L [H]</option>
            <option value="C" {2[2]}>C [F]</option>
        </select>
        <input type="text" name="Z2value" value="{0[1]}" />
</p>
<p>
     f [Hz]:
        <input type="text" name="f" value="{0[2]}" />
</p>
<p>
        &nbsp; &nbsp; &nbsp; &nbsp;
        <button type="submit" name="vyp" value="1">Vypočítat</button>
        <button type="submit" name="gen" value="1">Náhodně generovat</button>
        Sice vím proč IE neumí tento formulář odeslat,
        ale odmítám to řešit.
</p>
</form>
""".format([Z1value, Z2value, fa], Z1sel, Z2sel)

if stop:
    print '''
    <p>
    Kombinace LC, RR, CC, LL není možná!
    </p>
    '''
    exit()


if testForm or testGen:

##  osa x
    if fa>0.01*fm:
        fmin=0.01*fm
    else:
        fmin=0.05*fa
    if fa<10*fm:
        fmax = 10*fm
    else:
        fmax = 2*fa
#    f = l.linspace(fmin,fmax,num=10)
    f = l.logspace(int(n.log10(fmin))-1,int(n.log10(fmax))+1,num=100)
    w = 2*pi*f

    wa = 2*pi*fa

## Z1
    if Z1type == "R":
        Z1 = Z1value
        Z1a = Z1value
    elif Z1type == "L": 
        Z1 = 1j*w*Z1value
        Z1a = 1j*wa*Z1value
    elif Z1type == "C": 
        Z1 = 1/( 1j*w*Z1value )
        Z1a = 1/( 1j*wa*Z1value )

### Z2
    if Z2type == "R":
        Z2 = Z2value
        Z2a = Z2value
    elif Z2type == "L": 
        Z2 = 1j*w*Z2value
        Z2a = 1j*wa*Z2value
    elif Z2type == "C": 
        Z2 = 1/( 1j*w*Z2value )
        Z2a = 1/( 1j*wa*Z2value )


    Au =  Z2/( Z1 + Z2 ) 

    l.figure()
    l.grid(True)
    l.title(u"Frekvenční závislost modulu přenosu")
    l.xlabel("$f[Hz]$")
    l.ylabel("$a_u[dB]$")
    l.semilogx(f, 20*n.log10(abs(Au)) )
#l.axis([-0.1,1.1,-1.2,1.2])
    l.axis('auto')

    [xmin1, xmax1, ymin1, ymax1] = l.axis()
    ymin1 -= 2
    ymax1 += 2
    l.axis([xmin1, xmax1, ymin1, ymax1])

    l.axvline(fm, color='r',ls='--')
    l.axhline(-3, color='r',ls='--')
#l.text(1000, 0, '$u(t)=sin(2\pi ft)$', {'fontsize' : 20})
    l.text(fm,ymin1,r'\Large$f_m$',va='top', ha='center')

# Výpočet přenosu na zadané frekvenci
    w = 2*pi*fa
    Auf =  abs(Z2a/( Z1a + Z2a )) 
    auf = 20*n.log10(Auf)

    l.axvline(fa,color='g', ls="-.")
    l.axhline(auf,color='g', ls="-.")

# temfile
    temp = mktemp(suffix=".png",prefix="p", dir="../tmp");
    l.savefig(temp)


# Zadané a vypočtené hodnoty
    print '''
<h2>Výpočet</h2>

<p>
    Z1: {0} = {1:.4G}
</p>
<p>
    Z2: {2} = {3:.4G}
</p>
<p>
    frekvence: <span style="color:green;">f = {4:.4G}</span>, 
               <span style="color:red;">fm = {5:.4G}</span>
</p>
<p>
    Přenos na zadané frekvenci: Au(f) = {6:.4G}, au(f)= {7:.4G} dB
</p>
'''.format(Z1type,Z1value,Z2type,Z2value,fa,fm,Auf,auf)

# Obrázek    
    print """
    <p>
    <img src="{0}"></img>
    </p>
    <p>
    <a href="./gamaRCRL-cgi.py">zdroj této stránky</a>
    </p>

    """.format(temp)

print '''
</body></html>
'''
# vim:nospell:
