Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # coding=UTF-8
- import csv
- import matplotlib
- matplotlib.use('Agg')
- import matplotlib.pyplot as plt
- import numpy as np
- from cStringIO import StringIO
- import os
- from flask import Flask, request, redirect, url_for
- from werkzeug import secure_filename
- UPLOAD_FOLDER = '/home/renato/mysite'
- ALLOWED_EXTENSIONS = set(['csv'])
- app = Flask(__name__)
- app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
- def allowed_file(filename):
- return '.' in filename and \
- filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
- @app.route('/', methods=['GET', 'POST'])
- def upload_file():
- global filename, CONtempo
- if request.method == 'POST':
- CONtempo = int(request.form['CONtempo'])
- if request.method == 'POST':
- file = request.files['file']
- if file and allowed_file(file.filename):
- filename = secure_filename(file.filename)
- print filename
- file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
- return redirect("http://renato.pythonanywhere.com/grafico")
- return '''
- <!doctype html>
- <title>P-I-D</title>
- <h1>Carregar arquivo de dados (.csv)</h1>
- <form action=""
- method="post" enctype="multipart/form-data">
- Constante de tempo: <input type="number" name="CONtempo" value="1"><br><br>
- <input type="file" name="file">
- <input type="submit" value="Enviar">
- </form>
- <h3>A constante de tempo será utilizada como divisor para o tempo morto e tau, servindo como ajuste para certos controladores, deixe o valor em 1 caso esta alteração não seja necessária.<h3>
- <h3>O arquivo .csv deve respeitar a seguinte formatação: O valor da PV deve estar na primeira coluna, o valor de MV deve estar na segunda coluna, sendo ambas separadas por tabulação.<h3>
- <h3>Arquivos de exemplo podem ser baixados em: </h3>
- <a href="https://mega.co.nz/#!dJQhUbYZ!Hl766E418-lchr6R9w7f1H-WEPo3VO9DIk9GFK4UQcE" target="_blank">Arquivo de exemplo 1</a>
- <a href="https://mega.co.nz/#!YI5DmbzI!WXYSTV2_xbHoa-CFou9DnS6ksmUrzCwx-GiPNp2RDEI" target="_blank">Arquivo de exemplo 2</a>
- </form>
- '''
- @app.route("/grafico")
- def Calcular():
- html = '''
- <html>
- <body>
- <img src="data:image/png;base64,{}" NAME="k" /> <br/>
- <iframe src="http://renato.pythonanywhere.com/ZPID" height = 30 width = 800 scrolling="no"></iframe>
- <iframe src="http://renato.pythonanywhere.com/ZPI" height = 30 width = 800 scrolling="no"></iframe>
- <iframe src="http://renato.pythonanywhere.com/ZP" height = 30 width = 800 scrolling="no"></iframe>
- <iframe src="http://renato.pythonanywhere.com/CPID" height = 30 width = 800 scrolling="no"></iframe>
- <iframe src="http://renato.pythonanywhere.com/CPI" height = 30 width = 800 scrolling="no"></iframe>
- <iframe src="http://renato.pythonanywhere.com/CPD" height = 30 width = 800 scrolling="no"></iframe>
- <iframe src="http://renato.pythonanywhere.com/CP" height = 30 width = 800 scrolling="no"></iframe>
- <iframe src="http://renato.pythonanywhere.com/APID" height = 30 width = 800 scrolling="no"></iframe>
- </body>
- </html>
- '''
- global np, tau, tempoMorto, k, ifl, PVmudanca, mudancaPV, MVmudanca, mudancaMV, MVmax, MVmin, PVmax, PVmin, infl, coluna,coluna2, tauPV
- try:
- plt.delaxes()
- coluna = np.array(list(csv.reader(open('/home/renato/mysite/%(1)s' % {"1":filename},"rb"),delimiter='\t'))).astype('float')
- coluna2 = np.array(list(csv.reader(open('/home/renato/mysite/%(1)s' % {"1":filename},"rb"),delimiter='\t'))).astype('float')
- ConTempo = CONtempo
- coluna = coluna/1000
- coluna = np.round(coluna)
- PV = coluna[:,0]
- MV = coluna[:,1]
- PVmax = np.amax(PV)
- PVmin = np.amin(PV)
- MVmax = np.amax(MV)
- MVmin = np.amin(MV)
- k = (PVmax - PVmin)/(MVmax - MVmin)
- print k
- MudancaPV = np.nditer(PV, flags=['f_index'])
- MudancaMV = np.nditer(MV, flags=['f_index'])
- while MudancaPV == PVmin:
- PVmudanca = ("%d") % (MudancaPV.index)
- PVmudanca = float(PVmudanca)
- MudancaPV.iternext()
- print PVmudanca
- while MudancaMV == MVmin:
- MVmudanca = ("%d") % (MudancaMV.index)
- MVmudanca = float(MVmudanca)
- MudancaMV.iternext()
- print MVmudanca
- tempoMorto = PVmudanca - MVmudanca
- tempoMorto = float(tempoMorto)
- tempoMorto = tempoMorto/ConTempo
- print tempoMorto
- infl = ((PVmax-PVmin)*0.632)+PVmin
- print infl
- while MudancaPV <= infl:
- tauPV = ("%d") % (MudancaPV.index)
- tauPV = float(tauPV)
- MudancaPV.iternext()
- print tauPV
- tau = tauPV - PVmudanca
- tau = float(tau)
- tau = tau/ConTempo
- print tau
- fig = plt.figure("Resposta do Sistema")
- plt.xlabel("k = %(1)s Tempo Morto = %(2)s Tau = %(3)s" % {"1":k, "2":tempoMorto, "3":tau})
- plt.ylabel("%")
- plt.axhline(infl, color='blue', ls = ':', lw = 3, label = "63,2% (PV)")
- plt.axvline(PVmudanca, color='green', ls = ':', lw = 3, label = "Tempo morto")
- plt.axvline(tauPV, color='magenta', ls = ':', lw = 3, label = "Tau")
- plt.plot(coluna2[:,0]/1000, color='red', label = "PV")
- plt.plot(coluna2[:,1]/1000, color='black', label = "MV")
- plt.legend(["63,2%(PV)","Tempo Morto", "Tau", "PV", "MV"],loc='upper center', bbox_to_anchor=(0.485, +1.13), fancybox=False, ncol=5)
- plt.axvline(MVmudanca, color='green', ls = ':', lw = 3)
- plt.xticks([np.around(MVmudanca), np.around(PVmudanca), np.around(tauPV)])
- plt.yticks([PVmax, PVmin, MVmax, MVmin,np.around(infl)])
- io = StringIO()
- fig.savefig(io, format='png')
- data = io.getvalue().encode('base64')
- return html.format(data)
- except:
- return "Erro, verifique o arquivo selecionado"
- @app.route("/ZPID")
- def ZieglerPID():
- try:
- global Kp, Ti, Td
- Kp = (1.2 * tau)/(tempoMorto*k)
- Ti = 2 * tempoMorto
- Td = 0.5 * tempoMorto
- return "Kp = %(1)s\nTi = %(2)s\nTd = %(3)s - Ziegler Nichols (P.I.D)" % {"1":Kp, "2":Ti, "3":Td}
- except:
- return "Erro, verifique o arquivo selecionado"
- @app.route("/ZPI")
- def ZieglerPI():
- try:
- global Kp, Ti
- Kp = (0.9 * tau)/(tempoMorto*k)
- Ti = 3.33 * tempoMorto
- return "Kp = %(1)s\nTi = %(2)s - Ziegler Nichols (P.I)" % {"1":Kp, "2":Ti}
- except:
- return "Erro, verifique o arquivo selecionado"
- @app.route("/ZP")
- def ZieglerP():
- try:
- global Kp
- Kp = tau/(k*tempoMorto)
- return "Kp = %(1)s - Ziegler Nichols (P)" % {"1":Kp}
- except:
- return "Erro, verifique o arquivo selecionado"
- @app.route("/CPID")
- def CohenPID():
- try:
- global Kp, Ti, Td
- Kp = (1.35/k)*((tau/tempoMorto)+0.185)
- Ti = (2.5 * tempoMorto)*((tau+(0.185*tempoMorto))/(tau+(0.611*tempoMorto)))
- Td = (0.37 * tempoMorto)/(tau/(tau+(0.185*tempoMorto)))
- return "Kp = %(1)s\nTi = %(2)s\nTd = %(3)s - Cohen Coon (P.I.D)" % {"1":Kp, "2":Ti, "3":Td}
- except:
- return "Erro, verifique o arquivo selecionado"
- @app.route("/CPI")
- def CohenPI():
- try:
- global Kp, Ti
- Kp = (0.9/k)*((tau/tempoMorto)+0.092)
- Ti = (3.33 * tempoMorto)*((tau+(0.092*tempoMorto))/(tau+(2.22*tempoMorto)))
- return "Kp = %(1)s\nTi = %(2)s - Cohen Coon (P.I)" % {"1":Kp, "2":Ti}
- except:
- return "Erro, verifique o arquivo selecionado"
- @app.route("/CPD")
- def CohenPD():
- try:
- global Kp, Td
- Kp = (1.24/k)*((tau/tempoMorto)+0.129)
- Td = (0.27 * tempoMorto)/(tau-(0.34*tempoMorto/(tau+(0.185*tempoMorto))))
- return "Kp = %(1)s\nTd = %(2)s - Cohen Coon (P.D)" % {"1":Kp, "2":Td}
- except:
- return "Erro, verifique o arquivo selecionado"
- @app.route("/CP")
- def CohenP():
- try:
- global Kp
- Kp = (1.03/k)*((tau/tempoMorto)+0.34)
- return "Kp = %(1)s - Cohen Coon (P)" % {"1":Kp}
- except:
- return "Erro, verifique o arquivo selecionado"
- @app.route("/APID")
- def AmigoPID():
- try:
- global Kp, Ti, Td
- Kp = (1/k)*(0.2+(0.45*(tau/tempoMorto)))
- Ti = (((0.4 * tempoMorto)+0.8*tau)/(tempoMorto+(0.1*tau)))*tempoMorto
- Td = (0.5 * tempoMorto*tau)/(0.3*tempoMorto+tau)
- return "Kp = %(1)s\nTi = %(2)s\nTd = %(3)s - AMIGO (P.I.D)" % {"1":Kp, "2":Ti, "3":Td}
- except:
- return "Erro, verifique o arquivo selecionado"
- if __name__ == "__main__":
- app.debug = True
- app.run(host= 'renato.pythonanywhere.com')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement