repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
bit-bots/karma
|
karma/karma/admin.py
|
from django.contrib import admin
from .models import KarmaPoints, Project, Category
admin.site.register(KarmaPoints)
admin.site.register(Category)
admin.site.register(Project)
|
bit-bots/karma
|
karma/karma/migrations/0003_project_karma_rules.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-11-05 10:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('karma', '0002_auto_20170307_1645'),
]
operations = [
migrations.AddField(
model_name='project',
name='karma_rules',
field=models.TextField(default='No special rules', max_length=400),
),
]
|
philipempl/mail_watch
|
black_list_all.py
|
import imaplib, base64, os, email, re, configparser
import tkinter as tk
from tkinter import messagebox
from datetime import datetime
from email import generator
from dateutil.parser import parse
def init():
mail = imaplib.IMAP4_SSL(config['SERVER']['Host'],config['SERVER']['Port'])
pwd = str(input("PWD: "))
print(pwd)
mail.login(str(config['ADDRESS']['Email']),pwd )
for dir in config['MAIL_DIRS']:
dir = config['MAIL_DIRS'][dir]
print('\n ########################## ' + dir + ' ##################################\n')
mail.select(dir)
type, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
readAllMails(id_list, mail)
def readAllMails(id_list, mail):
counter = 0
l = len(id_list)
for num in id_list:
typ, data = mail.fetch(num, '(RFC822)' )
raw_email = data[0][1]
# converts byte literal to string removing b''
try:
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
# get sender from mail
except:
continue
sender_name = ''
sender_email = ''
sender_array = email_message['from'].split('<')
if(len(sender_array) > 1):
sender_email = (sender_array[1][:-1]).lower()
sender_name = re.sub(r"[^a-zA-Z0-9]+", ' ',sender_array[0]).strip()
else:
sender_email = (sender_array[0]).lower()
counter = counter + 1
printProgressBar(counter, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
if(isInBlackList(sender_email) == False):
addToBlackList(sender_email)
def isInBlackList(sender):
with open(black_list) as blackList:
if sender in blackList.read():
return True
else:
return False
def addToBlackList(sender):
hs = open("blackList.txt","a")
hs.write(sender + "\n")
hs.close()
init()
|
philipempl/mail_watch
|
mail_watcher.py
|
<gh_stars>0
import imaplib, base64, os, email, re, configparser
import tkinter as tk
from tkinter import messagebox
from datetime import datetime
from email import generator
from dateutil.parser import parse
def init():
mail = imaplib.IMAP4_SSL(config['SERVER']['Host'],config['SERVER']['Port'])
pwd = str(input("PWD: "))
print(pwd)
mail.login(str(config['ADDRESS']['Email']),pwd )
for dir in config['MAIL_DIRS']:
dir = config['MAIL_DIRS'][dir]
print('\n ########################## ' + dir + ' ##################################\n')
mail.select(dir)
type, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
readAllMails(id_list, mail)
def readAllMails(id_list, mail):
counter = 0
l = len(id_list)
for num in id_list:
typ, data = mail.fetch(num, '(RFC822)' )
raw_email = data[0][1]
# converts byte literal to string removing b''
try:
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
# get sender from mail
except:
continue
sender_name = ''
sender_email = ''
sender_array = email_message['from'].split('<')
if(len(sender_array) > 1):
sender_email = (sender_array[1][:-1]).lower()
sender_name = re.sub(r"[^a-zA-Z0-9]+", ' ',sender_array[0]).strip()
else:
sender_email = (sender_array[0]).lower()
counter = counter + 1
printProgressBar(counter, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
if(isInWhiteList(sender_email)):
downloadMail(email_message, sender_email)
elif(isInBlackList(sender_email) == False):
openDialog(sender_email, email_message)
def downloadMail(email_message, sender):
# create directory if not exist
filePath = os.path.join(directoryName, sender)
if not os.path.exists(filePath):
os.makedirs(filePath)
for part in email_message.walk():
# extract and format date
date = email_message['Date']
date_time_obj = ''
try:
date_time_obj = parse(date)
except:
print(date)
# extract subject and dir name
file_storage = str(date_time_obj.year)+ str(date_time_obj.strftime('%m')) + str(date_time_obj.strftime('%d'))
subject = re.sub(r"[^a-zA-Z0-9]+", ' ',email_message['subject']).strip()
file_path_subject = filePath + "/" + file_storage
if not os.path.exists(file_path_subject):
os.makedirs(file_path_subject)
if not os.path.isfile(file_path_subject):
# download email text into eml format
o_file_name = subject + '.eml'
output_file = os.path.join(file_path_subject, o_file_name)
with open(output_file, 'w') as outfile:
try:
gen = generator.Generator(outfile)
gen.flatten(email_message)
except:
continue
# checking if data is available
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
data = part.get_payload(decode=True)
if not data:
continue
if filename is None:
continue
try:
attachment = open(os.path.join(file_path_subject, filename), 'wb')
attachment.write(data)
attachment.close()
except:
continue
def openDialog(sender, email_message):
root = tk.Tk()
root.withdraw()
MsgBox = tk.messagebox.askquestion( sender,sender + ' \n\nWhat should be done with this sender? \n\n [yes] = white list \n [no] = black list' ,icon = 'warning')
if MsgBox == 'yes':
addToWhiteList(sender)
downloadMail(email_message, sender)
else:
addToBlackList(sender)
def isInWhiteList(sender):
with open(white_list) as whiteList:
if sender in whiteList.read():
return True
else:
return False
def isInBlackList(sender):
with open(black_list) as blackList:
if sender in blackList.read():
return True
else:
return False
def addToBlackList(sender):
hs = open("blackList.txt","a")
hs.write(sender + "\n")
hs.close()
def addToWhiteList(sender):
hs = open("whiteList.txt","a")
hs.write(sender + "\n")
hs.close()
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
# Print New Line on Complete
if iteration == total:
print()
config = configparser.ConfigParser()
config.read('config.ini')
directoryName = str(config['DOWNLOAD_DIR']['Download'])
white_list = str(config['FILES']['Whitelist'])
black_list = str(config['FILES']['Blacklist'])
init()
|
ethansimpson285/HEPDash
|
src/hepdash/histograms/design.py
|
# Design config
import mplhep as hep
experiment_labels = {
"ATLAS" : hep.atlas,
"CMS" : hep.cms,
"LHCb2" : hep.lhcb,
"ALICE" : hep.alice
}
HEP_histogram_design_parameters = {
"experiment" : "ATLAS",
"HEP label text" : "Internal"
}
HEP_histogram_design_parameters["HEP experiment label"] = experiment_labels[HEP_histogram_design_parameters["experiment"]]
|
ethansimpson285/HEPDash
|
src/hepdash/funcs/make_premade_comparison_app.py
|
<filename>src/hepdash/funcs/make_premade_comparison_app.py
'''
HEP-Dash
<NAME>
December 10th 2021
Notes:
- Require that the primary function for creating the web-app must be called main()
- How to re-factor this into something more user freindly?
- Just now, the only thing the user is required to do is edit the input dic - this could come from a config file
- Or it could come from a parser but probably complex
'''
# Imports
# Base imports
import sys
from dataclasses import dataclass
# Third-party imports
import streamlit as st
from streamlit import cli as stcli
# Package imports
from hepdash.layouts.BiColumn import PhysOb_Page_TwoColumn, MultiPage
from hepdash.apps.Tree_Apps import Preset
# input_dic = {"file1": {"file_path":"~/Documents/Qualification_Task/TTbar_Samples/ttbar_dec15_particleLevel_even.root" ,"tree_name": "particleLevel_even" , "colour":"blue" },
# "file2": {"file_path":"~/Documents/Qualification_Task/TTbar_Samples/ttbar_dec15_reco_even.root" ,"tree_name": "reco_even" , "colour":"red" }}
import sys
config_file = sys.argv[1]
def main():
# Initialsie the streamlit web-app object
st.set_page_config(layout='wide')
st.title("HEP Dash")
# Import the data
data_object = Preset.make_from_config(config_file)
print("ROOT files loaded")
# Pass list of trees here
muon = PhysOb_Page_TwoColumn(phys_ob="Muon", input_object=data_object, branches2plot=["mu_pt","mu_eta","mu_phi","mu_e"])
electron = PhysOb_Page_TwoColumn(phys_ob="Electron", input_object=data_object, branches2plot=["el_pt","el_eta","el_phi","el_e"])
jet = PhysOb_Page_TwoColumn(phys_ob="Jet", input_object=data_object, branches2plot=["jet_pt","jet_eta","jet_phi","jet_e"])
print("Pages written")
MP = MultiPage()
MP.add_page(muon)
MP.add_page(electron)
MP.add_page(jet)
MP.Build_MultiPage()
if __name__ == '__main__':
if st._is_running_with_streamlit:
# file_name = sys.argv[1]
# tree_name = sys.argv[2]
# branch_name = sys.argv[3]
main()
else:
sys.argv = ["streamlit", "run", sys.argv[0],sys.argv[1]]#,sys.argv[2]]#,sys.argv[3]]
sys.exit(stcli.main())
|
ethansimpson285/HEPDash
|
src/hepdash/funcs/make_general_comparison_app.py
|
'''
HEP-Dash
<NAME>
December 10th 2021
Notes:
- Require that the primary function for creating the web-app must be called main()
- How to re-factor this into something more user freindly?
- Just now, the only thing the user is required to do is edit the input dic - this could come from a config file
- Or it could come from a parser but probably complex
'''
# Imports
# Base imports
import sys
from dataclasses import dataclass
# Third-party imports
import streamlit as st
from streamlit import cli as stcli
# Package imports
from hepdash.layouts.BiColumn import PhysOb_Page_TwoColumn, MultiPage
# from Apps2 import Premade_Tree_Comparison_App
from hepdash.apps.Tree_Apps import General
input_dic = {"file1": {"file_path":"~/Documents/Qualification_Task/TTbar_Samples/ttbar_dec15_particleLevel_even.root" ,"tree_name": "particleLevel_even" , "colour":"blue" },
"file2": {"file_path":"~/Documents/Qualification_Task/TTbar_Samples/ttbar_dec15_reco_even.root" ,"tree_name": "reco_even" , "colour":"red" }}
def main():
# Initialsie the streamlit web-app object
st.set_page_config(layout='wide')
st.title("HEP Dash")
# Import the data
data_object = General(input_dic)
the_page = PhysOb_Page_TwoColumn(phys_ob="All Branches", input_object=data_object, branches2plot=data_object.all_branches)
the_page.Build()
if __name__ == '__main__':
if st._is_running_with_streamlit:
# file_name = sys.argv[1]
# tree_name = sys.argv[2]
# branch_name = sys.argv[3]
main()
else:
sys.argv = ["streamlit", "run", sys.argv[0]]#,sys.argv[1],sys.argv[2]]#,sys.argv[3]]
sys.exit(stcli.main())
|
ethansimpson285/HEPDash
|
src/hepdash/apps/Histogram_Apps.py
|
<gh_stars>0
# Histogram Apps
'''
Histogram apps could have General or Specific varieties
Pull histograms from ROOT file
Compile into app
'''
import streamlit as st
import uproot
import matplotlib.pyplot as plt
import mplhep as hep
import sys
from streamlit import cli as stcli
from hepdash.layouts.BiColumn import import_ROOT_file, PhysOb_Page_TwoColumn, MultiPage
from hepdash.histograms.design import HEP_histogram_design_parameters
def create_input_object(index,name,ROOT_file_path,list_of_hist_names,**kwargs):
"""
Wrapper for creating InputObject with additional (colour if non-specified)
"""
colour=kwargs["colour"] if "colour" in kwargs else default_colours[index]
return InputObject(name=name,
ROOT_file_path=ROOT_file_path,
list_of_hist_names=list_of_hist_names,
colour=colour)
class InputObject:
def __init__(self,name,ROOT_file_path,list_of_hist_names,colour,**kwargs):
"""
A proxy for the ROOT file itself, containing the tree data stored once the ROOT file has been parsed
"""
self.name = name
self.ROOT_file_path = ROOT_file_path
self.list_of_hist_names = list_of_hist_names
self.dic_of_histograms = {}
self.colour = colour
self.label = kwargs["label"] if "label" in kwargs else self.name
def import_hists(self):
file = uproot.open(self.ROOT_file_path)
# If empty list passed, use all the histograms in the file
if not self.list_of_hist_names:
self.list_of_hist_names = file.keys()
# Get the intersection of the list of hists in file and hists asked for
loadable_histogram_names = list(set(file.keys()).intersection(self.list_of_hist_names))
# Get the histograms
for hn in loadable_histogram_names:
self.dic_of_histograms[hn] = file[hn]
class Histogram_App:
def __init__(self,input_dictionary):
# Load input objects which contain the information on the ROOT files
self.list_of_input_objects = []
for i,(k,v) in enumerate(input_dictionary.items()):
io = create_input_object(index=i,name=k,ROOT_file_path=v["file_path"],list_of_hist_names=v["list_of_hist_names"],colour=v["colour"])
io.import_hists()
self.list_of_input_objects.append(io)
self.get_common_hist_names()
def get_common_hist_names(self):
# Get the common histograms in all input_objects
all_names = [list(io.dic_of_histograms.keys()) for io in self.list_of_input_objects]
self.common_histogram_names = set(all_names[0])
for s in all_names[1:]:
self.common_histogram_names.intersection_update(s)
def Build_BiColumn_Page(self):
# Initialsie the streamlit web-app object
st.set_page_config(layout='wide')
st.title("HEP Dash")
col1, col2, col3 = st.columns([2,1,4])
with col1:
hist_name = st.selectbox("Choose an observable",self.common_histogram_names)
with col3:
hep.style.use(HEP_histogram_design_parameters["experiment"])
fig,ax = plt.subplots()
for io in self.list_of_input_objects:
hep.histplot(io.dic_of_histograms[hist_name],color=io.colour)
fig.set_size_inches(6,5)
ax.set_xlabel(hist_name,labelpad=0,fontsize=14)
ax.set_ylabel("Unnormalised Number of Events",fontsize=14)
HEP_histogram_design_parameters["HEP experiment label"].text(HEP_histogram_design_parameters["HEP label text"],ax=ax,loc=1)
st.pyplot(fig)
def main():
input_dic = {"file1": {"file_path":"/home/ethan/Documents/ttZ/MadGraph ttZ SpinCorrelation Studies/nov10_pp2ttZ/output_nov10_pp2ttZ_spinON.root" ,"list_of_hist_names": [] , "colour":"blue" },
"file2": {"file_path":"/home/ethan/Documents/ttZ/MadGraph ttZ SpinCorrelation Studies/nov10_pp2ttZ/output_nov10_pp2ttZ_spinOFF.root" ,"list_of_hist_names": [] , "colour":"red" }}
App1 = Histogram_App(input_dic)
App1.Build_BiColumn_Page()
if __name__ == '__main__':
if st._is_running_with_streamlit:
# file_name = sys.argv[1]
# tree_name = sys.argv[2]
# branch_name = sys.argv[3]
main()
else:
sys.argv = ["streamlit", "run", sys.argv[0]]#,sys.argv[1],sys.argv[2]]#,sys.argv[3]]
sys.exit(stcli.main())
|
ethansimpson285/HEPDash
|
src/hepdash/histograms/Histogram_Classes.py
|
import matplotlib.pyplot as plt
import mplhep as hep
import hist
import numpy as np
from hist.intervals import ratio_uncertainty
import boost_histogram as bh
import uproot
import functools
import operator
import math
class PyHist_Object:
'''
A basic wrapper for storing a boost-histogram and associated bin errors
Also required to contain specific plotting information e.g. colour and legend label
'''
def __init__(self,Histogram,errors,**kwargs):
self.Histogram = Histogram
self.errors_up = errors[1]
self.errors_down = errors[0]
# self.colour "black"
# self.label = ""
self.Set_Features(**kwargs)
def Set_Features(self,**kwargs):
self.colour = kwargs["colour"] if "colour" in kwargs else "black"
self.label = kwargs["label"] if "label" in kwargs else ""
class Histogram_Wrapper:
'''
Larger wrapper for Boost-Histogram object generated from Uproot parsing of ROOT file
Contains methods for extracting histogram from Uproot file and constructing boost-histogram
Stores the above PyHist_Objects for both normalised and unnormalised cases
'''
def __init__(self,df,**kwargs):
# self.TTree = ttree
# self.branch_name = branch_name
self.number_of_bins = 26
self.normalise = kwargs["normalise"] if "normalise" in kwargs else True
self.belongs2 = kwargs["belongs2"] if "belongs2" in kwargs else ""
# Plot features
self.colour = kwargs["colour"] if "colour" in kwargs else None
self.label = kwargs["label"] if "label" in kwargs else None
# Extract histogram for Uproot file TTree
self.df = df
self.Generate_Binning(kwargs)
compute_errors = lambda errors: [np.sqrt(boost_hist.variances()),np.sqrt(boost_hist.variances())]
# Generate boost_histogram, and wrap with errors
boost_hist = bh.Histogram(bh.axis.Variable(self.binning))
boost_hist.fill(self.df)
boost_hist_errors = compute_errors(boost_hist)
self.UnNorm_Hist = PyHist_Object(boost_hist,boost_hist_errors,colour=self.colour,label=self.label)
# Generate normalised histogram, and wrap with errors
if self.normalise:
norm_boost_hist = self.normalise_boost_histogram(boost_hist)
norm_boost_hist_errors = compute_errors(norm_boost_hist)
self.Norm_Hist = PyHist_Object(norm_boost_hist,norm_boost_hist_errors,colour=self.colour,label=self.label)
# self.UnNorm_Hist.colour,self.Norm_Hist.colour = self.colour,self.colour
def Generate_Binning(self,kwargs):
if "binning" in kwargs:
self.AutoBin = False
self.binning = kwargs["binning"]
else:
self.AutoBin = True
num_bins = kwargs["number_of_bins"] if "number_of_bins" in kwargs else self.number_of_bins
maxH,minH = float(math.ceil(df.max())),float(math.floor(df.min()))
self.binning = np.linspace(minH,maxH,num_bins)
def Change_Defaults(self,**kwargs):
self.number_of_bins = kwargs["number_of_bins"] if "number_of_bins" in kwargs else self.number_of_bins
@staticmethod
def normalise_boost_histogram(orig_boost_hist):
''' Recommended method for normalising histogram'''
norm_boost_hist = orig_boost_hist.copy()
area = functools.reduce(operator.mul, norm_boost_hist.axes.widths)
factor = np.sum(norm_boost_hist.view())
view = norm_boost_hist.view() / (factor * area)
for i,x in enumerate(view):
norm_boost_hist[i]=x
print(norm_boost_hist.sum())
return norm_boost_hist
|
ethansimpson285/HEPDash
|
src/hepdash/histograms/Plotting_Histograms.py
|
import matplotlib.pyplot as plt
import mplhep as hep
import hist
import numpy as np
from hist.intervals import ratio_uncertainty
import boost_histogram as bh
import uproot
from matplotlib.lines import Line2D
from hepdash.histograms.Histogram_Classes import Histogram_Wrapper, PyHist_Object
from streamlit import cli as stcli
import streamlit as st
def make_standard_plot():
p = plt(1)
return p
def make_ratio_only_plot():
pass
@st.cache
def make_both_plot(dic_of_hists,divisor):
# Initialise the plot
x = Ratio_Plot("plot1",list_of_histograms=dic_of_hists.values(),divisor=divisor,plot_normalised=True)
x.Initalise_Plot_Design("ATLAS")
# # Returns the plt object so adjustments can be made here
plt = x.Make_Step_Fill_Plot()
print("Plot made")
# print(x.fig)
# input()
x.Add_ATLAS_Label("Internal")
x.Axis_Labels({"x": "pT [GeV]","y1":"Events","y2":"Ratio"})
x.Axis_XTick_Labels([0,50,100,150,200,250])
print("Returning")
return x.fig
class HEP_Plot:
allowed_experiment_styles = ["ATLAS","ALICE","LHCb2","CMS","ATLASTex"]
def Add_ATLAS_Label(self,label_text,**kwargs):
ax = self.axes[0]
if self.plot_design in ["ATLAS","ATLASTex"]:
loc = kwargs["loc"] if "loc" in kwargs else 1
if loc == 1:
yaxis_limits = ax.get_ylim()
ax.set_ylim(yaxis_limits[0],yaxis_limits[1]*1.2)
l1 = hep.atlas.text(label_text,ax=ax,loc=loc)
if "specific_location" in kwargs:
#Defined from first word
x_diff,y_diff = l1[1]._x - l1[0]._x , l1[1]._y - l1[0]._y
l1[0]._x = kwargs["specific_location"][0]
l1[0]._y = kwargs["specific_location"][1]
l1[1]._x = kwargs["specific_location"][0] + x_diff
l1[1]._y = kwargs["specific_location"][1] + y_diff
def Initialise_LHC_Plot(self,experiment):
assert any([experiment == x for x in self.allowed_experiment_styles]), "Experiment style not defined"
hep.style.use(experiment)#, {'xtick.direction': 'out'}])
def Initialise_Seaborn_Plot(self,**kwargs):
import seaborn as sns
if "style" in kwargs:
sns.set_style(kwargs["style"])
else:
sns.set_style("dark")
def Add_Histograms(self,histograms2add: list):
self.list_of_histograms = self.list_of_histograms + histograms2add
def Initalise_Plot_Design(self,design,**kwargs):
self.plot_design = design
allowed_experiment_styles = ["ATLAS","ALICE","LHCb2","CMS","ATLASTex"]
if any([design == x for x in allowed_experiment_styles]):
self.Initialise_LHC_Plot(design)
elif design=="Seaborn":
self.Initialise_Seaborn_Plot(**kwargs)
def Customise_Legend(self):
pass
@staticmethod
def Steps_Filled_Erros(ax,Hist_Ob):#Histogram,error_up,error_down): # Need to pass error up and error down
"""For making a histogram plot with steps, where the errors are filled lighter bars above and below the step """
Histogram = Hist_Ob.Histogram
# print(Histogram)
# input()
# ax.stairs(
# values=Histogram.values() + Hist_Ob.errors_up,
# baseline=Histogram.values() - Hist_Ob.errors_down,
# edges=Histogram.axes[0].edges, fill=True,color=Hist_Ob.colour)
hep.histplot(Histogram.values(), ax=ax, stack=False, histtype='step',color=Hist_Ob.colour,label=Hist_Ob.label,lw=1.0)
def __init__(self,plot_title,**kwargs):
self.plot_title = plot_title
self.list_of_histograms = []
self.plot_Normalised = True
self.fig = None
self.axes = None
if "plot_design" in kwargs:
self.plot_design = kwargs["plot_design"]
self.Initalise_Plot_Design(self.plot_design,**kwargs) # Is there a way to sift a subset of kwargs i.e. **kwargs["seaborn_design_parameters"]
if "list_of_histograms" in kwargs:
self.list_of_histograms = kwargs["list_of_histograms"]
if "plot_normalised" in kwargs and not kwargs["plot_normalised"]:
self.plot_Normalised = False
class Single_Plot(HEP_Plot):
def __init__(self,plot_title,**kwargs):
super().__init__(plot_title,**kwargs)
class Ratio_Plot(HEP_Plot):
'''
The Ratio_Plot inherits from the parent HEP_Plot class
The methods here are:
- the computation of ratio histograms
- the initialistion of the mpl object
- the filling of the plot
'''
def __init__(self,plot_title,**kwargs):
super().__init__(plot_title,**kwargs)
self.divisor = kwargs["divisor"] if "divisor" in kwargs else None
@staticmethod
def Compute_Ratio(hist1,hist2):
ratio_hist = hist1/hist2
ratio_uncertainties = ratio_uncertainty(hist1.view(),hist2.view(),"poisson-ratio")
return PyHist_Object(ratio_hist,ratio_uncertainties)#[0],ratio_uncertainties[1])
def Axis_Labels(self,dic_of_labels):
self.axes[1].set_xlabel(dic_of_labels["x"])
self.axes[1].set_ylabel(dic_of_labels["y2"])
self.axes[0].set_ylabel(dic_of_labels["y1"])
def Axis_XTick_Labels(self,labels,**kwargs):
# print(self.axes[1].get_xticklabels)
# input()
self.axes[1].set_xticklabels(labels)
def Make_Step_Fill_Plot(self):
assert len(self.list_of_histograms) != 0, "No histograms passed to plot"
# Initialise the plot
fig, (ax, rax) = plt.subplots(2, 1, figsize=(6,6), gridspec_kw=dict(height_ratios=[3, 1], hspace=0.1), sharex=True)
self.fig = fig
self.axes = (ax,rax)
# Select whether to do normalisation
legend_elements = []
# print(self.list_of_histograms)
# input()
for Wrapper in self.list_of_histograms:
# print(Wrapper.__dict__)
# print(Wrapper.Norm_Hist.Histogram)
# input()
if not self.plot_Normalised:
self.Steps_Filled_Erros(ax=ax,Hist_Ob=Wrapper.UnNorm_Hist)
ratio_obj = self.Compute_Ratio(Wrapper.UnNorm_Hist.Histogram,self.divisor.UnNorm_Hist.Histogram)
ratio_obj.Set_Features(colour=Wrapper.colour)
self.Steps_Filled_Erros(ax=rax,Hist_Ob=ratio_obj)
elif self.plot_Normalised:
self.Steps_Filled_Erros(ax=ax,Hist_Ob=Wrapper.Norm_Hist)
ratio_obj = self.Compute_Ratio(Wrapper.Norm_Hist.Histogram,self.divisor.Norm_Hist.Histogram)
ratio_obj.Set_Features(colour=Wrapper.colour)
self.Steps_Filled_Erros(ax=rax,Hist_Ob=ratio_obj)
# Do the legend part here
legend_elements.append(Line2D([0],[0],color=Wrapper.colour,lw=2,label=Wrapper.label))
ax.legend(handles=legend_elements)#, loc='center')
return plt
|
ethansimpson285/HEPDash
|
src/hepdash/layouts/BiColumn.py
|
<filename>src/hepdash/layouts/BiColumn.py<gh_stars>0
"""
HEP Dashboard 1
<NAME>
For plotting single histograms in a streamlit web-app, with controls for binning
and histogram range.
Run either through python3 or streamlit commands:
```python3 PlotHist.py <file_name> <tree_name> <branch_name>```
or
```streamlit run <file_name> <tree_name> <branch_name>```
This script is specfically designed to not use ROOT,
but therefore requires a number of third-party dependencies:
- numpy = defining arrays
- matplotlib = pyplot back-end
- streamlit = generates web-app
- uproot = parses ROOT file
- boost_histogram = alternative to ROOT histogram
- mplhep = for plotting
"""
# Standard imports
import sys
import os
import math
import time
import pickle
from collections import namedtuple
import functools
import operator
# Third-party imports
from streamlit import cli as stcli
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import mplhep as hep
import uproot
import boost_histogram as bh
# Own imports
from hepdash.histograms.Histogram_Classes import PyHist_Object, Histogram_Wrapper
from hepdash.histograms.Plotting_Histograms import make_both_plot,make_ratio_only_plot,make_standard_plot
import hepdash.histograms.Plotters as Plotters
def normalise_boost_histogram(boost_hist):
area = functools.reduce(operator.mul, boost_hist.axes.widths)
factor = np.sum(boost_hist.view())
view = boost_hist.view() / (factor * area)
for i,x in enumerate(view):
boost_hist[i]=x
return boost_hist
@st.cache
def Generate_Histogram(num_bins,hist_range,df,normalise):
bins = np.linspace(hist_range[0],hist_range[1],num_bins+1)
h = bh.Histogram(bh.axis.Variable(bins))
h.fill(df)
if normalise:
return normalise_boost_histogram(h)
else:
return h
# @st.cache
def generate_wrapped_histogram(num_bins,hist_range,df,**kwargs):
binning = np.linspace(hist_range[0],hist_range[1],num_bins)
Wrapped_Hist = Histogram_Wrapper(df,binning=binning,colour=kwargs["colour"] ,label=kwargs["label"])
return Wrapped_Hist
# def Get_Extrema(df):
# import math
# return
# #Streamlit suffers from the problem of being slow to generate a slider for histogram extrema which are very large values
# #This is problematic for pT and eta
# def EPT_Histogram(nb,minH,maxH,df,index):
# nearest10k = lambda a: math.ceil(a/10e3)*10e3
# maxH = nearest10k(maxH)
# hist_range = st.slider('Range of histogram',value=[0.0,maxH/1e3],key=index,step=10.0)
# hist_range = tuple([1e3*x for x in hist_range])
# return Generate_Histogram(nb,hist_range,df)
# def Angular_Histogram(nb,minH,maxH,df,index):
# hist_range = st.slider('Range of histogram',value=[minH,maxH],key=index)
# return Generate_Histogram(nb,hist_range,df)
# def Branch2Hist(tree,branch_name,index):
# df = tree[branch_name].array(library="pd")
# nb = st.slider('Number of bins',min_value=1,max_value=100,value=50,key=index)
# maxH,minH = Get_Extrema(df)
# #####
# # Switch statement to select correct histogram based on branch name
# if "_eta" in branch_name or "_phi" in branch_name:
# h = Angular_Histogram(nb,minH,maxH,df,index)
# else:
# h = EPT_Histogram(nb,minH,maxH,df,index)
# return h ,df
def RootHist_2_boosthist(histogram_name):
'''Some converstion through uproot(?) to boost_histogram'''
pass
def Plot_SingleHist(h,branch_name):
fig,ax = plt.subplots()
hep.histplot(h)
plt.xlabel(branch_name)
plt.ylabel("Number of events")
st.pyplot(fig)
def extrema_from_dfs(list_of_dfs):
maxH_list , minH_list = [],[]
# get_extrema = lambda get_extrema df: float(math.ceil(df.max())),float(math.floor(df.min()))
for df in list_of_dfs:
maxH_list.append(float(math.ceil(df.max())))
minH_list.append(float(math.floor(df.min())))
max_HH, min_HH = max(maxH_list),min(minH_list)
Extrema = namedtuple('Extrema','min max')
return Extrema(min_HH,max_HH)
from hist.intervals import ratio_uncertainty
def Compute_Ratio(hist1,hist2):
ratio_hist = hist1/hist2
ratio_uncertainties = ratio_uncertainty(hist1.view(),hist2.view(),"poisson-ratio")
return PyHist_Object(ratio_hist,ratio_uncertainties)#[0],ratio_uncertainties[1])
# class PhysOb_Page:
# def __init__(self,phys_ob,dic_of_trees,branches2plot):
# self.phys_ob = phys_ob
# self.dic_of_trees = dic_of_trees
# self.branches2plot = branches2plot
# self.plot_types = {"ratio only":make_ratio_only_plot,
# "standard":make_standard_plot,
# "standard+ratio":make_both_plot}
# def Build(self):
# st.write("## " + self.phys_ob)
# # Selects obs as the observable in question
# obs = st.selectbox("Choose an observable",self.branches2plot)
# chosen_plot_type = st.selectbox("Plot type:",self.plot_types.keys())
# plot_function = self.plot_types[chosen_plot_type]
# if chosen_plot_type=="ratio only" or chosen_plot_type=="standard+ratio":
# divisor_name = st.selectbox("Histogram divisor" , self.dic_of_trees.keys())
# # divisor = self.dic_of_trees[divisor_name]
# # Initialise list of DataFrames
# dic_of_df = {}
# # Extract TBranches to DF and compute limits
# maxH_list , minH_list = [],[]
# # Automatically compute histogram bounds
# for tree_name,tree in self.dic_of_trees.items():
# df = tree[obs].array(library="pd")
# dic_of_df[tree_name] = df
# extrema = extrema_from_dfs(dic_of_df.values())
# # Bin slider
# index = self.phys_ob+"_"+obs
# nb = st.slider('Number of bins',min_value=1,max_value=100,value=50,key=index)
# # Generate the bin edge slider based on observable type
# if "_eta" in obs or "_phi" in obs:
# hist_range = st.slider('Range of histogram',value=[extrema.min,extrema.max],key=index)
# else:
# # Getting the binning to work well with slider
# nearest10k = lambda a: math.ceil(a/10e3)*10e3
# maxH = nearest10k(exterma.max)
# hist_range = st.slider('Range of histogram',value=[0.0,maxH/1e3],key=index)
# hist_range = tuple([1e3*x for x in hist_range])
# dic_of_hists = {}
# normalise = st.checkbox("Show normalised",value=True)
# # Loop over the dataframes and generate the histograms
# for name,df in dic_of_df.items():
# h = generate_wrapped_histogram(nb,hist_range,df,normalise=normalise,colour=colour,label=label)
# dic_of_hists[name] = h
# # Get the divisor histogram, using the dictionary of histograms and the key specified
# if chosen_plot_type=="ratio only" or chosen_plot_type=="standard+ratio":
# divisor_histogram = dic_of_hists[divisor_name]
# plot_function = make_standard_plot
# # fig = make_standard_plot(dic_of_hists=dic_of_hists,divisor=divisor_histogram)
# fig,ax = plt.subplots()
# [hep.histplot(h.UnNorm_Hist.Histogram,yerr=True) for h in dic_of_hists.values()]
# st.pyplot(fig)
# print("should now be visible")
def get_xaxis_label(obs):
label_dict = {"pt" : r"$p_{T} [GeV]$",
"eta": r"$\eta$",
"phi": r"$\phi$",
"e" : r"$E [GeV]$"}
if "_pt" in obs:
return label_dict["pt"]
elif "_eta" in obs:
return label_dict["eta"]
elif "_phi" in obs:
return label_dict["phi"]
elif "_e" in obs and not "_eta" in obs:
return label_dict["e"]
class PhysOb_Page_TwoColumn:
def __init__(self,phys_ob,input_objects,branches2plot):
self.phys_ob = phys_ob
# self.data_object = input_object
self.list_of_input_objects = input_objects
self.branches2plot = branches2plot
self.plot_types = {"standard":make_standard_plot,
"standard+ratio":make_both_plot,
"ratio only":make_ratio_only_plot}
def Build(self):
col1, col2, col3 = st.columns([2,1,4])
# Page initialised with defaults
page_data = {"observable":self.branches2plot[0],
"plot_type" :make_standard_plot,
"num_bins": 50,
"hist_range":None,
"normalise": False}
with col1:
st.write("## " + self.phys_ob)
# Set page_data with streamlit widgets
page_data["observable"] = st.selectbox("Choose an observable",self.branches2plot)
index = self.phys_ob+"_"+page_data["observable"]
chosen_plot_type = st.selectbox("Plot type:",self.plot_types.keys())
page_data["plot_type"] = self.plot_types[chosen_plot_type]
page_data["normalise"] = st.checkbox("Show normalised",value=True)
page_data["num_bins"] = st.slider('Number of bins',min_value=1,max_value=100,value=50,key=index)
self.dic_of_trees = {io.name : io.tree for io in self.list_of_input_objects}
if chosen_plot_type=="ratio only" or chosen_plot_type=="standard+ratio":
divisor_name = st.selectbox("Histogram divisor" , self.dic_of_trees.keys())
# divisor = self.dic_of_trees[divisor_name]
# Build histograms
# Initialise list of DataFrames
dic_of_df = {}
# Automatically compute histogram bounds
for io in self.list_of_input_objects: # input_trees = {io.name : io.tree for io in data_object.list_of_input_objects}
# for tree_name,tree in self.dic_of_trees.items():
tree_name , tree = io.name , io.tree
cuts = "(el_pt>100000)"
df = tree[page_data["observable"]].array(library="pd") # Pulling
# df2 = tree.arrays("jet_pt",cuts,library="pd")["jet_pt"]
dic_of_df[tree_name] = df
extrema=extrema_from_dfs(dic_of_df.values())
# Generate the bin edge slider based on observable type
if "_eta" in page_data["observable"] or "_phi" in page_data["observable"]:
hist_range = st.slider('Range of histogram',value=[extrema.min,extrema.max],key=index)
else:
# Getting the binning to work well with slider
nearest10k = lambda a: math.ceil(a/10e3)*10e3
maxH = nearest10k(extrema.max)
hist_range = st.slider('Range of histogram',value=[0.0,maxH/1e3],key=index,step=10.0)
hist_range = tuple([1e3*x for x in hist_range])
page_data["hist_range"] = hist_range
dic_of_hists = {}
with col3:
dic_of_hists = {}
for io,df in zip(self.list_of_input_objects,dic_of_df.values()):
h = generate_wrapped_histogram(page_data["num_bins"],page_data["hist_range"],df,
normalise=page_data["normalise"],
colour=io.colour,
label=io.label,
belongs2=io.name)
dic_of_hists[io.name] = h
# Get the divisor histogram, using the dictionary of histograms and the key specified
if chosen_plot_type=="ratio only" or chosen_plot_type=="standard+ratio":
divisor_histogram = dic_of_hists[divisor_name]
label_text = "Internal"
# Access x-axis label
xaxis_label = get_xaxis_label(page_data["observable"])
if chosen_plot_type=="standard":
fig=Plotters.standard_plot(dic_of_hists,page_data["normalise"],xaxis_label=xaxis_label)
if chosen_plot_type=="ratio only":
fig=Plotters.ratio_only_plot(dic_of_hists,page_data["normalise"],divisor_histogram,xaxis_label=xaxis_label)
if chosen_plot_type=="standard+ratio":
fig=Plotters.combined_plot(dic_of_hists,page_data["normalise"],divisor_histogram,xaxis_label=xaxis_label)
st.pyplot(fig)
class MultiPage:
def __init__(self) -> None:
self.dic_of_pages = {}
def add_page(self,page_object):
self.dic_of_pages[page_object.phys_ob] = page_object
def Build_MultiPage(self):
# Build the multipage format and the selection box
list_of_pages = self.dic_of_pages.keys()
page_name = st.sidebar.selectbox("Physics Object Selection",[str(x) for x in self.dic_of_pages])#list(self.dic_of_pages.values()))#,format_func = lambda page: page.phys_ob)
# input()
self.dic_of_pages[page_name].Build()
# @st.cache(allow_output_mutation=True)
# def import_files():
# t2=time.time()
# file1 = uproot.open("~/Documents/Qualification_Task/TTbar_Samples/ttbar_dec15_particleLevel_even.root")
# tree1 = file1["particleLevel_even"]
# file2 = uproot.open("~/Documents/Qualification_Task/TTbar_Samples/ttbar_dec15_reco_even.root")
# tree2 = file2["reco_even"]
# print("here")
# return tree1,tree2
@st.cache(allow_output_mutation=True)
def import_ROOT_file(file_path,tree_name):
return uproot.open(file_path)[tree_name]
# def primary():
# st.set_page_config(layout='wide')
# st.title("HEP Dash")
# # st.write("### Interactive HEP Visualisation!")
# t2 = time.time()
# tree1,tree2 = import_files()
# print(time.time()-t2)
# # input_trees = {}
# # for imp in imported_
# input_trees = {"tree1":tree1,"tree2":tree2}
# # Pass list of trees here
# muon = PhysOb_Page_TwoColumn("Muon",input_trees,["mu_pt","mu_eta","mu_phi","mu_e"])
# electron = PhysOb_Page_TwoColumn("Electron",input_trees,["el_pt","el_eta","el_phi","el_e"])#,"mu_eta"])
# print("Pages written")
# MP = MultiPage()
# MP.add_page(muon)
# MP.add_page(electron)
# MP.Build_MultiPage()
# def main():
# st.set_page_config(layout='wide')
# st.title("HEP Dash")
# # st.write("### Interactive HEP Visualisation!")
# t2 = time.time()
# tree1,tree2 = import_files()
# print(time.time()-t2)
# # input_trees = {}
# # for imp in imported_
# input_trees = {"tree1":tree1,"tree2":tree2}
# # input()
# # Pass list of trees here
# muon = PhysOb_Page_TwoColumn("Muon",input_trees,["mu_pt","mu_eta","mu_phi","mu_e"])
# electron = PhysOb_Page_TwoColumn("Electron",input_trees,["el_pt","el_eta","el_phi","el_e"])#,"mu_eta"])
# print("Pages written")
# MP = MultiPage()
# MP.add_page(muon)
# MP.add_page(electron)
# MP.Build_MultiPage()
if __name__ == '__main__':
if st._is_running_with_streamlit:
# file_name = sys.argv[1]
# tree_name = sys.argv[2]
# branch_name = sys.argv[3]
main()
else:
sys.argv = ["streamlit", "run", sys.argv[0]]#,sys.argv[1],sys.argv[2]]#,sys.argv[3]]
sys.exit(stcli.main())
|
ethansimpson285/HEPDash
|
src/hepdash/apps/Tree_Apps.py
|
<reponame>ethansimpson285/HEPDash
from dataclasses import dataclass
import itertools
import yaml
import os
import matplotlib.pyplot as plt
import streamlit as st
from hepdash.layouts.BiColumn import import_ROOT_file, PhysOb_Page_TwoColumn, MultiPage
default_colours = plt.rcParams['axes.prop_cycle'].by_key()['color']
def parse_config(yaml_file):
assert os.path.isfile(yaml_file), "Config file not found"
with open(yaml_file, 'r') as stream:
data_loaded = yaml.safe_load(stream)
return data_loaded
def create_input_object(index,name,ROOT_file_path,tree_name,**kwargs):
"""
Wrapper for creating InputObject with additional (colour if non-specified)
"""
colour=kwargs["colour"] if "colour" in kwargs else default_colours[index]
return InputObject(name=name,
ROOT_file_path=ROOT_file_path,
tree_name=tree_name,
colour=colour)
class InputObject:
def __init__(self,name,ROOT_file_path,tree_name,colour,**kwargs):
"""
A proxy for the ROOT file itself, containing the tree data stored once the ROOT file has been parsed
"""
self.name = name
self.ROOT_file_path = ROOT_file_path
self.tree_name = tree_name
self.tree = None
self.colour = colour
self.label = kwargs["label"] if "label" in kwargs else self.name
class Tree_Comparison_App:
"""
Base class Tree comparison app
"""
def __init__(self,input_dictionary):
'''
input dictionary should be of the form {name: [ROOT_file_path,tree_name])}
'''
self.list_of_input_objects = []
for i,(k,v) in enumerate(input_dictionary.items()):
io = create_input_object(index=i,name=k,ROOT_file_path=v["file_path"],tree_name=v["tree_name"],colour=v["colour"])
self.list_of_input_objects.append(io)
self.load()
# self.check_trees_for_branches()
def load(self):
for v in self.list_of_input_objects:
v.tree = import_ROOT_file(v.ROOT_file_path,v.tree_name)
def check_trees_for_branches(self):
for io in self.list_of_input_objects:
assert all([branch_name in io.tree.keys() for branch_name in self.all_branches]), "Not all prerequisite branches found in tree"
def make_multipage(self):
MP = MultiPage()
for page in self.object_pages:
MP.add_page(page)
MP.Build_MultiPage()
class Preset(Tree_Comparison_App):
"""
Using preset branches on preset physics objects
"""
physics_objects = ["el","mu","jet"]
observable_branches = ["_pt","_eta","_phi","_e"]
all_branches = [''.join(p) for p in itertools.product(physics_objects, observable_branches)]
def __init__(self,input_dictionary):
super().__init__(input_dictionary)
self.check_trees_for_branches()
@staticmethod
def make_from_config(yaml_file):
data_loaded = parse_config(yaml_file)
return Preset(data_loaded)
# @staticmethod
def add_object_pages(self):
muon = PhysOb_Page_TwoColumn(phys_ob="Muon", input_objects=self.list_of_input_objects, branches2plot=["mu_pt","mu_eta","mu_phi","mu_e"])
electron = PhysOb_Page_TwoColumn(phys_ob="Electron", input_objects=self.list_of_input_objects, branches2plot=["el_pt","el_eta","el_phi","el_e"])
jet = PhysOb_Page_TwoColumn(phys_ob="Jet", input_objects=self.list_of_input_objects, branches2plot=["jet_pt","jet_eta","jet_phi","jet_e"])
self.object_pages = [muon,electron,jet]
# Build MultiPage here
MP = MultiPage()
for page in self.object_pages:
MP.add_page(page)
MP.Build_MultiPage()
class Specific(Tree_Comparison_App):
"""
For specifying particular branches (clustered or non-clustered)
Unclustered branches can be given as a list
"""
def __init__(self,input_dictionary,**kwargs):
self.imported_unclustered_branches = kwargs["unclustered_branches"] if "unclustered_branches" in kwargs and isinstance(kwargs["unclustered_branches"],list) else []
self.imported_clustered_branches = kwargs["clustered_branches"] if "clustered_branches" in kwargs and isinstance(kwargs["clustered_branches"],dict) else {}
self.all_branches = self.imported_unclustered_branches + self.imported_clustered_branches.values()
assert len
super().__init__(input_dictionary)
@staticmethod
def make_from_config(yaml_file):
data_loaded = parse_config(yaml_file)
return Specific(data_loaded)
class General(Tree_Comparison_App):
"""
For taking all branches (non-clustered)
"""
# all_branches = None
def get_all_common_branches(self):
list_of_branches = [io.tree.keys() for io in self.list_of_input_objects]
Output = set(list_of_branches[0])
for l in list_of_branches[1:]:
Output &= set(l)
# Converting to list
self.all_branches = list(Output)
def __init__(self,input_dictionary,**kwargs):
super().__init__(input_dictionary)
self.get_all_common_branches()
@staticmethod
def make_from_config(yaml_file):
data_loaded = parse_config(yaml_file)
return General(data_loaded)
def add_object_pages(self):
the_page = PhysOb_Page_TwoColumn(phys_ob="All Branches", input_objects=self.list_of_input_objects, branches2plot=self.all_branches)
the_page.Build()
|
ethansimpson285/HEPDash
|
src/hepdash/histograms/Plotters.py
|
<reponame>ethansimpson285/HEPDash
# Various plotters
import mplhep as hep
from hist.intervals import ratio_uncertainty
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from hepdash.histograms.Histogram_Classes import PyHist_Object, Histogram_Wrapper
from hepdash.histograms.design import HEP_histogram_design_parameters
def Compute_Ratio(hist1,hist2):
"""
Compute ratio dividies two boost_histogram hists
Computes the ratio_uncertainties through hist.intervals method, though this seems to cause issue
"""
ratio_hist = hist1/hist2
ratio_uncertainties = ratio_uncertainty(hist1.view(),hist2.view(),"poisson-ratio")
return PyHist_Object(ratio_hist,ratio_uncertainties)#[0],ratio_uncertainties[1])
def standard_plot(dic_of_hists,normalise,xaxis_label):
"""
standard_plot() displays the (normalised or unnormalised) histograms
"""
hep.style.use(HEP_histogram_design_parameters["experiment"])
fig,ax = plt.subplots()
fig.set_size_inches(6,6)
HEP_histogram_design_parameters["HEP experiment label"].text(HEP_histogram_design_parameters["HEP label text"],ax=ax,loc=1)
if normalise:
[hep.histplot(h.Norm_Hist.Histogram,yerr=False,color=h.colour) for h in dic_of_hists.values()]
ax.set_ylabel('Number of Events (Normalised)',fontsize=16)
else:
[hep.histplot(h.UnNorm_Hist.Histogram,yerr=True,color=h.colour) for h in dic_of_hists.values()]
ax.set_ylabel('Number of Events (Unnormalised)',fontsize=16)
if any([x in xaxis_label for x in ["p_{T}","E"]]):
ax.set_xlabel(xaxis_label,labelpad=20)
else:
ax.set_xlabel(xaxis_label,labelpad=0)
# Legend
legend_elements = [Line2D([0],[0],color=h.colour,lw=2,label=h.label) for h in dic_of_hists.values()]
ax.legend(handles=legend_elements)#, loc='center')
return fig
def ratio_only_plot(dic_of_hists,normalise,divisor_histogram,xaxis_label):
"""
ratio_only_plot() displays the ratios of any histograms with respect to one of them
"""
hep.style.use(HEP_histogram_design_parameters["experiment"])
fig,ax = plt.subplots()
fig.set_size_inches(6,6)
HEP_histogram_design_parameters["HEP experiment label"].text(HEP_histogram_design_parameters["HEP label text"],ax=ax,loc=1)
legend_elements = []
for n,h in dic_of_hists.items():
if normalise:
ratio_obj = Compute_Ratio(h.Norm_Hist.Histogram,divisor_histogram.Norm_Hist.Histogram)
else:
ratio_obj = Compute_Ratio(h.UnNorm_Hist.Histogram,divisor_histogram.UnNorm_Hist.Histogram)
hep.histplot(ratio_obj.Histogram,yerr=False,ax=ax,color=h.colour)
legend_elements.append(Line2D([0],[0],color=h.colour,lw=2,label=h.label))
ax.legend(handles=legend_elements)#, loc='center')
if any([x in xaxis_label for x in ["p_{T}","E"]]):
ax.set_xlabel(xaxis_label,labelpad=20)
else:
ax.set_xlabel(xaxis_label,labelpad=0)
ax.set_ylabel('Ratio w.r.t. ' + divisor_histogram.belongs2,fontsize=16)
return fig
def combined_plot(dic_of_hists,normalise,divisor_histogram,xaxis_label):
"""
combined_plot() generates a figure made up of two subplots
The top plot shows the histogram,
the bottom plot displays the ratios with respect to a chosen histogram
"""
hep.style.use(HEP_histogram_design_parameters["experiment"])
fig, (ax, rax) = plt.subplots(2, 1, figsize=(6,6), gridspec_kw=dict(height_ratios=[3, 1], hspace=0.1), sharex=True)
fig.set_size_inches(6,6)
HEP_histogram_design_parameters["HEP experiment label"].text(HEP_histogram_design_parameters["HEP label text"],ax=ax,loc=1)
legend_elements = []
for n,h in dic_of_hists.items():
if normalise:
hep.histplot(h.Norm_Hist.Histogram,yerr=False,ax=ax,color=h.colour)
ratio_obj = Compute_Ratio(h.Norm_Hist.Histogram,divisor_histogram.Norm_Hist.Histogram)
hep.histplot(ratio_obj.Histogram,yerr=False,ax=rax,color=h.colour)
ax.set_ylabel('Number of Events (Normalised)',fontsize=14)
else:
hep.histplot(h.UnNorm_Hist.Histogram,yerr=False,ax=ax,color=h.colour)
ratio_obj = Compute_Ratio(h.UnNorm_Hist.Histogram,divisor_histogram.UnNorm_Hist.Histogram)
hep.histplot(ratio_obj.Histogram,yerr=False,ax=rax,color=h.colour)
ax.set_ylabel('Number of Events (Unormalised)',fontsize=14)
legend_elements.append(Line2D([0],[0],color=h.colour,lw=2,label=h.label))
ax.legend(handles=legend_elements)#, loc='center')
if any([x in xaxis_label for x in ["p_{T}","E"]]):
rax.set_xlabel(xaxis_label,labelpad=20)
else:
rax.set_xlabel(xaxis_label,labelpad=0)
rax.set_ylabel('Ratio w.r.t. ' + divisor_histogram.belongs2,fontsize=12)
return fig
|
ethansimpson285/HEPDash
|
src/hepdash/funcs/make_tree.py
|
<filename>src/hepdash/funcs/make_tree.py<gh_stars>0
'''
HEP-Dash
<NAME>
December 10th 2021
Notes:
- Require that the primary function for creating the web-app must be called main()
- How to re-factor this into something more user freindly?
- Just now, the only thing the user is required to do is edit the input dic - this could come from a config file
- Or it could come from a parser but probably complex
'''
# Imports
# Base imports
import sys
from dataclasses import dataclass
# Third-party imports
import streamlit as st
from streamlit import cli as stcli
# Package imports
from hepdash.apps.Tree_Apps import Preset, General
import sys
app_type = sys.argv[1]
config_file = sys.argv[2]
if app_type=="preset":
app_func = Preset
elif app_type=="general":
app_func = General
elif app_type=="specific":
pass
def main():
# Initialsie the streamlit web-app object
st.set_page_config(layout='wide')
st.title("HEP Dash")
# Import the data
App1 = app_func.make_from_config(config_file)
print("ROOT files loaded")
App1.add_object_pages()
print("Pages written")
App1.make_multipage()
print("Construction complete")
if __name__ == '__main__':
if st._is_running_with_streamlit:
# file_name = sys.argv[1]
# tree_name = sys.argv[2]
# branch_name = sys.argv[3]
main()
else:
sys.argv = ["streamlit", "run", sys.argv[0],sys.argv[1],sys.argv[2]]#,sys.argv[3]]
sys.exit(stcli.main())
|
luckyzflQ/py4fix
|
python36/dxa/sn_random_numbers.py
|
import numpy as np
def sn_random_numbers(shape, antithetic=True, moment_matching=True,
fixed_seed=False):
''' Returns an array of shape shape with (pseudo)random numbers
that are standard normally distributed.
Parameters
==========
shape : tuple (o, n, m)
generation of array with shape (o, n, m)
antithetic : Boolean
generation of antithetic variates
moment_matching : Boolean
matching of first and second moments
fixed_seed : Boolean
flag to fix the seed
Results
=======
ran : (o, n, m) array of (pseudo)random numbers
'''
if fixed_seed:
np.random.seed(1000)
if antithetic:
ran = np.random.standard_normal((shape[0], shape[1], int(shape[2] / 2)))
ran = np.concatenate((ran, -ran), axis=2)
else:
ran = np.random.standard_normal(shape)
if moment_matching:
ran = ran - np.mean(ran)
ran = ran / np.std(ran)
if shape[0] == 1:
return ran[0]
else:
return ran
|
luckyzflQ/py4fix
|
python36/dxa/valuation_class.py
|
#
# DX Library Valuation
# valuation_class.py
#
class valuation_class(object):
''' Basic class for single-factor valuation.
Attributes
==========
name : string
name of the object
underlying :
instance of simulation class
mar_env : instance of market_environment
market environment data for valuation
payoff_func : string
derivatives payoff in Python syntax
Example: 'np.maximum(maturity_value - 100, 0)'
where maturity_value is the NumPy vector with
respective values of the underlying
Example: 'np.maximum(instrument_values - 100, 0)'
where instrument_values is the NumPy matrix with
values of the underlying over the whole time/path grid
Methods
=======
update:
updates selected valuation parameters
delta :
returns the Delta of the derivative
vega :
returns the Vega of the derivative
'''
def __init__(self, name, underlying, mar_env, payoff_func=''):
try:
self.name = name
self.pricing_date = mar_env.pricing_date
try:
self.strike = mar_env.get_constant('strike')
# strike is optional
except:
pass
self.maturity = mar_env.get_constant('maturity')
self.currency = mar_env.get_constant('currency')
# simulation parameters and discount curve from simulation object
self.frequency = underlying.frequency
self.paths = underlying.paths
self.discount_curve = underlying.discount_curve
self.payoff_func = payoff_func
self.underlying = underlying
# provide pricing_date and maturity to underlying
self.underlying.special_dates.extend([self.pricing_date,
self.maturity])
except:
print("Error parsing market environment.")
def update(self, initial_value=None, volatility=None,
strike=None, maturity=None):
if initial_value is not None:
self.underlying.update(initial_value=initial_value)
if volatility is not None:
self.underlying.update(volatility=volatility)
if strike is not None:
self.strike = strike
if maturity is not None:
self.maturity = maturity
# add new maturity date if not in time_grid
if not maturity in self.underlying.time_grid:
self.underlying.special_dates.append(maturity)
self.underlying.instrument_values = None
def delta(self, interval=None, accuracy=4):
if interval is None:
interval = self.underlying.initial_value / 50.
# forward-difference approximation
# calculate left value for numerical Delta
value_left = self.present_value(fixed_seed=True)
# numerical underlying value for right value
initial_del = self.underlying.initial_value + interval
self.underlying.update(initial_value=initial_del)
# calculate right value for numerical delta
value_right = self.present_value(fixed_seed=True)
# reset the initial_value of the simulation object
self.underlying.update(initial_value=initial_del - interval)
delta = (value_right - value_left) / interval
# correct for potential numerical errors
if delta < -1.0:
return -1.0
elif delta > 1.0:
return 1.0
else:
return round(delta, accuracy)
def vega(self, interval=0.01, accuracy=4):
if interval < self.underlying.volatility / 50.:
interval = self.underlying.volatility / 50.
# forward-difference approximation
# calculate the left value for numerical Vega
value_left = self.present_value(fixed_seed=True)
# numerical volatility value for right value
vola_del = self.underlying.volatility + interval
# update the simulation object
self.underlying.update(volatility=vola_del)
# calculate the right value for numerical Vega
value_right = self.present_value(fixed_seed=True)
# reset volatility value of simulation object
self.underlying.update(volatility=vola_del - interval)
vega = (value_right - value_left) / interval
return round(vega, accuracy)
|
luckyzflQ/py4fix
|
python36/volservice/vol_pricing_service.py
|
#
# Valuation of European volatility options
# in Gruenbichler-Longstaff (1996) model
# square-root diffusion framework
# -- parameter dictionary & web service function
#
from vol_pricing_formula import calculate_option_value
# model parameters
# http://127.0.0.1:4000/?V0=0.2&kappa=2.0&theta=0.21&sigma=0.02&zeta=0.0&T=1.0&r=0.05&K=0.19
PARAMS = {
'V0': 'current volatility level',
'kappa': 'mean reversion factor',
'theta': 'long-run mean of volatility',
'sigma': 'volatility of volatility',
'zeta': 'factor of the expected volatility risk premium',
'T': 'time horizon in years',
'r': 'risk-free interest rate',
'K': 'strike'
}
# function for web service
def get_option_value(data):
''' A helper function for web service. '''
errorline = 'Missing parameter %s (%s)\n'
errormsg = ''
for para in PARAMS:
if para not in data.keys():
# check if all parameters are provided
errormsg += errorline % (para, PARAMS[para])
if errormsg != '':
return errormsg
else:
result = calculate_option_value(
float(data['V0']),
float(data['kappa']),
float(data['theta']),
float(data['sigma']),
float(data['zeta']),
float(data['T']),
float(data['r']),
float(data['K'])
)
return str(result)
|
luckyzflQ/py4fix
|
python36/dxa/derivatives_position.py
|
#
# DX Library Portfolio
# derivatives_position.py
#
class derivatives_position(object):
''' Class to model a derivatives position.
Attributes
==========
name : string
name of the object
quantity : float
number of assets/derivatives making up the position
underlying : string
name of asset/risk factor for the derivative
mar_env : instance of market_environment
constants, lists, and curves relevant for valuation_class
otype : string
valuation class to use
payoff_func : string
payoff string for the derivative
Methods
=======
get_info :
prints information about the derivative position
'''
def __init__(self, name, quantity, underlying, mar_env, otype, payoff_func):
self.name = name
self.quantity = quantity
self.underlying = underlying
self.mar_env = mar_env
self.otype = otype
self.payoff_func = payoff_func
def get_info(self):
print("NAME")
print(self.name, '\n')
print("QUANTITY")
print(self.quantity, '\n')
print("UNDERLYING")
print(self.underlying, '\n')
print("MARKET ENVIRONMENT")
print("\n**Constants**")
for key, value in self.mar_env.constants.items():
print(key, value)
print("\n**Lists**")
for key, value in self.mar_env.lists.items():
print(key, value)
print("\n**Curves**")
for key in self.mar_env.curves.items():
print(key, value)
print("\nOPTION TYPE")
print(self.otype, '\n')
print("PAYOFF FUNCTION")
print(self.payoff_func)
|
kaist-jisungpark/ros_node_pattern
|
demo/scripts/sender.py
|
#!/usr/bin/env python
import rospy
#from dbw_mkz_msgs.msg import SteeringCmd
from std_msgs.msg import String
def CommandSender():
pub = rospy.Publisher('subscriber', String, queue_size=10)
rospy.init_node('Commands', anonymous=True)
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
hello_str = "Send string message %s" % rospy.get_time()
cmd = String()
cmd.data = "test"
## change this to see the difference
rospy.loginfo(hello_str)
pub.publish(cmd)
rate.sleep()
if __name__ == '__main__':
try:
CommandSender()
except rospy.ROSInterruptException:
pass
|
Dhruva-Ananth/IS1_Telemetry_Decoding
|
Inspire_Telemetry_Decoder_v6.py
|
import csv
import os
from tkinter import filedialog
from tkinter import *
from tkinter import ttk
from satnogs.satnogs import Satnogs
import cubeds
import argparse
LARGE_FONT= ("Verdana", 12)
NORM_FONT= ("Verdana", 10)
SMALL_FONT= ("Verdana", 8)
def restart_program():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
python = sys.executable
os.execl(python, python, * sys.argv)
#Creating a Popup Message to show Conversion is Complete
def popupmsg(title, msg):
popup = Tk()
popup.wm_title(title)
label = ttk.Label(popup, text=msg, font=NORM_FONT)
label.pack(side="top", fill="x", pady=10)
B1 = ttk.Button(popup, text="Okay", command = popup.destroy)
B1.pack()
popup.mainloop()
# This function performs a polynomial conversion on the level 0 data
# Can be extended to do other types of conversions
def performConversion(var,conversion):
if (conversion[0] == ''):
return var
else:
C0 = float(conversion[0])
C1 = float(conversion[1])
C2 = float(conversion[2])
C3 = float(conversion[3])
C4 = float(conversion[4])
convertedVar = C0 + C1 * var + C2 * var * var + C3 * var * var * var + C4 * var * var * var * var
return convertedVar
def performSignedValues(var, type):
variable_type = type[0]
numbits = int(type[1:])
if(variable_type =='I'):
if(var<2**(numbits-1)):
return var
else:
return (var - 2**(numbits))
else:
return var
#OLD Function
# def DecodePacketsUHF():
# # Opening the file containing a list of different packets and their APIDs
# global list_packets
# list_packets = []
# with open("packet_apids.csv", 'r') as f:
# reader = csv.DictReader(f)
# for row in reader:
# list_temp = []
# for key, value in row.items():
# list_temp.append(value)
# # Empty List for level 0 decoded telemetry
# list_temp.append([])
# # Empty List for level 1 decoded telemetry
# list_temp.append([])
# # Empty list for packet definations
# list_temp.append([])
# list_packets.append(list(list_temp))
#
# # Reading the packet definations from the packet_def.csv file
# packets_def = []
# with open("packet_def.csv", 'r') as f:
# reader = csv.DictReader(f)
# for row in reader:
# list_temp = []
# for key, value in row.items():
# list_temp.append(value)
# packets_def.append(list(list_temp))
#
# raw_list = []
# # Opening multiple hydra log files
# root = Tk()
# root.withdraw()
# Path = filedialog.askdirectory()
# Path = Path + "/"
# filelist = os.listdir(Path)
# for i in filelist:
# # print(i[0])
# if (i[0] == 'c'):
# with open(Path + i, 'rb') as f:
# while True:
# byte = f.read(1)
# if not byte:
# break
# raw_list.append(int(ord(byte)))
#
# # Scanning through the list to look for different types of packets
# array_index = 0
# while (array_index < len(raw_list)):
# packet_apid = raw_list[array_index + 1]
# packet_length = 256 * raw_list[array_index + 4] + raw_list[array_index + 5]
# for j in range(0, len(list_packets), 1):
# if (packet_apid == int(list_packets[j][1])):
# list_packets[j][3].append(list(raw_list[array_index:array_index + packet_length + 7]))
# array_index = array_index + packet_length + 7
#
# # creating new level 0 and level 1 folders which would contain the decoded files
# l0_directory = "Level 0 Packets"
# path_new_l0 = os.path.join(Path, l0_directory)
# os.mkdir(path_new_l0)
#
# l1_directory = "Level 1 Packets"
# path_new_l1 = os.path.join(Path, l1_directory)
# os.mkdir(path_new_l1)
#
# # writing the raw different types of packets to level 0 csv files
# for j in range(0, len(list_packets), 1):
# if (len(list_packets[j][3]) > 0):
# name_str = str(list_packets[j][0]) + "_level_0.csv"
# with open(path_new_l0 + "/" + name_str, "w") as f:
# writer = csv.writer(f)
# for row in list_packets[j][2]:
# writer.writerow(row)
#
# # Arranging the definations as an array according to APIDs in the list_packets
# for m in range(0, len(packets_def), 1):
# curr_packet_apid = (int(packets_def[m][1]))
# for n in range(0, len(list_packets), 1):
# if (curr_packet_apid == int(list_packets[n][1])):
# list_packets[n][5].append(list(packets_def[m]))
#
# # Now implementing the level 1 conversions for all level 0 packets read
# for a in range(0, len(list_packets), 1):
# if (len(list_packets[a][3]) > 0):
# # Perform the level 1 conversions first
# cur_packet_decode_apid = int(list_packets[a][1])
# print("current APID is", cur_packet_decode_apid)
# curr_packet_raw_array = list_packets[a][3]
# curr_packet_actual_len = list_packets[a][2]
# curr_packet_def = list_packets[a][5]
#
# curr_packet_decode_number = a
# curr_packet_header_array = []
# curr_packet_decoded_array = []
# curr_decoded_array_index = 0
#
# for i in range(0, len(curr_packet_raw_array), 1):
# for j in range(0, len(curr_packet_def), 1):
# # Implementing decoding - combining bytes
# type = curr_packet_def[j][2]
# conversion = curr_packet_def[j][4:9]
# # print(conversion)
# endian = curr_packet_def[j][3]
# name = curr_packet_def[j][0]
#
# if (type == 'U8' or type == 'D8' or type == 'I8' or type == 'F8' or type == 'I6'):
# var = curr_packet_raw_array[i][curr_decoded_array_index]
# curr_packet_decoded_array.append(performConversion(performSignedValues(var, type), conversion))
# curr_decoded_array_index += 1
# # Collecting the 1st Row which has the variable name
# if (i == 0):
# curr_packet_header_array.append(curr_packet_def[j][0])
#
#
# elif (type == 'U16' or type == 'D16' or type == 'I16' or type == 'F16'):
# if (endian == 'big'):
# var = 256 * curr_packet_raw_array[i][curr_decoded_array_index + 1] + \
# curr_packet_raw_array[i][
# curr_decoded_array_index]
# else:
# var = 256 * curr_packet_raw_array[i][curr_decoded_array_index] + curr_packet_raw_array[i][
# curr_decoded_array_index + 1]
#
# curr_packet_decoded_array.append(performConversion(performSignedValues(var, type), conversion))
# curr_decoded_array_index += 2
# # Collecting the 1st Row which has the variable name
# if (i == 0):
# curr_packet_header_array.append(curr_packet_def[j][0])
#
# elif (type == 'U24' or type == 'D24' or type == 'I24' or type == 'F24'):
#
# if (endian == 'big'):
# var = 256 * 256 * curr_packet_raw_array[i][curr_decoded_array_index + 2] \
# + 256 * curr_packet_raw_array[i][curr_decoded_array_index + 1] \
# + curr_packet_raw_array[i][curr_decoded_array_index]
# else:
# var = 256 * 256 * curr_packet_raw_array[i][curr_decoded_array_index] \
# + 256 * curr_packet_raw_array[i][curr_decoded_array_index + 1] \
# + curr_packet_raw_array[i][curr_decoded_array_index + 2]
#
# curr_packet_decoded_array.append(performConversion(performSignedValues(var, type), conversion))
# curr_decoded_array_index += 3
# # Collecting the 1st Row which has the variable name
# if (i == 0):
# curr_packet_header_array.append(curr_packet_def[j][0])
#
# elif (type == 'U32' or type == 'D32' or type == 'I32' or type == 'F32'):
#
# if (endian == 'big'):
# var = 256 * 256 * 256 * curr_packet_raw_array[i][curr_decoded_array_index + 3] \
# + 256 * 256 * curr_packet_raw_array[i][curr_decoded_array_index + 2] \
# + 256 * curr_packet_raw_array[i][curr_decoded_array_index + 1] \
# + curr_packet_raw_array[i][curr_decoded_array_index]
# else:
# var = 256 * 256 * 256 * curr_packet_raw_array[i][curr_decoded_array_index] \
# + 256 * 256 * curr_packet_raw_array[i][curr_decoded_array_index + 1] \
# + 256 * curr_packet_raw_array[i][curr_decoded_array_index + 2] \
# + curr_packet_raw_array[i][curr_decoded_array_index + 3]
# curr_packet_decoded_array.append(performSignedValues(performConversion(var, conversion), type))
# curr_decoded_array_index += 4
# # Collecting the 1st Row which has the variable name
# if (i == 0):
# curr_packet_header_array.append(curr_packet_def[j][0])
# elif (type == 'U608'):
# for p in range(0, 76, 1):
# # Collecting the 1st Row which has the variable name
# if (i == 0):
# curr_packet_header_array.append(curr_packet_def[j][0])
# var = curr_packet_raw_array[i][curr_decoded_array_index]
# curr_packet_decoded_array.append(var)
# curr_decoded_array_index += 1
#
# elif (type == 'D1600'):
# for p in range(0, 200, 1):
# # Collecting the 1st Row which has the variable name
# if (i == 0):
# curr_packet_header_array.append(curr_packet_def[j][0])
# var = curr_packet_raw_array[i][curr_decoded_array_index]
# curr_packet_decoded_array.append(var)
# curr_decoded_array_index += 1
# elif (type == 'U1024'):
# for p in range(0, 128, 1):
# # Collecting the 1st Row which has the variable name
# if (i == 0):
# curr_packet_header_array.append(curr_packet_def[j][0])
# var = curr_packet_raw_array[i][curr_decoded_array_index]
# curr_packet_decoded_array.append(var)
# curr_decoded_array_index += 1
# elif (type == 'U1280'):
# for p in range(0, 160, 1):
# # Collecting the 1st Row which has the variable name
# if (i == 0):
# curr_packet_header_array.append(curr_packet_def[j][0])
# var = curr_packet_raw_array[i][curr_decoded_array_index]
# curr_packet_decoded_array.append(var)
# curr_decoded_array_index += 1
# elif (type == 'C1920'):
# for p in range(0, 240, 1):
# # Collecting the 1st Row which has the variable name
# if (i == 0):
# curr_packet_header_array.append(curr_packet_def[j][0])
# var = curr_packet_raw_array[i][curr_decoded_array_index]
# curr_packet_decoded_array.append(var)
# curr_decoded_array_index += 1
# elif (type == 'U1672'):
# for p in range(0, 209, 1):
# # Collecting the 1st Row which has the variable name
# if (i == 0):
# curr_packet_header_array.append(curr_packet_def[j][0])
# var = curr_packet_raw_array[i][curr_decoded_array_index]
# curr_packet_decoded_array.append(var)
# curr_decoded_array_index += 1
# elif (type == 'U376'):
# for p in range(0, 23, 1):
# # Collecting the 1st Row which has the variable name
# if (i == 0):
# curr_packet_header_array.append(curr_packet_def[j][0])
# var = curr_packet_raw_array[i][curr_decoded_array_index]
# curr_packet_decoded_array.append(var)
# curr_decoded_array_index += 1
# elif (type == 'U624'):
# for p in range(0, 78, 1):
# # Collecting the 1st Row which has the variable name
# if (i == 0):
# curr_packet_header_array.append(curr_packet_def[j][0])
# var = curr_packet_raw_array[i][curr_decoded_array_index]
# curr_packet_decoded_array.append(var)
# curr_decoded_array_index += 1
#
# list_packets[curr_packet_decode_number][4].append(list(curr_packet_decoded_array))
# curr_decoded_array_index = 0
# curr_packet_decoded_array = []
#
# # Store the level 1 data in CSV files
# name_str_l1 = str(list_packets[curr_packet_decode_number][0]) + "_level_1.csv"
# with open(path_new_l1 + "/" + name_str_l1, "w", newline='') as f:
# writer = csv.writer(f)
# writer.writerow(curr_packet_header_array)
# for row in list_packets[curr_packet_decode_number][4]:
# writer.writerow(row)
#
# popupmsg("Success", "Done! Level 0 and Level 1 Packets Created")
#New Batch decode function
def batchDecodePackets():
# Opening the file containing a list of different packets and their APIDs
list_packets = []
with open("packet_apids.csv", 'r') as f:
reader = csv.DictReader(f)
for row in reader:
list_temp = []
for key, value in row.items():
list_temp.append(value)
# Empty List for level 0 decoded telemetry
list_temp.append([])
# Empty List for level 1 decoded telemetry
list_temp.append([])
# Empty list for packet definations
list_temp.append([])
list_packets.append(list(list_temp))
# Reading the packet definations from the packet_def.csv file
packets_def = []
with open("packet_def.csv", 'r') as f:
reader = csv.DictReader(f)
for row in reader:
list_temp = []
for key, value in row.items():
list_temp.append(value)
packets_def.append(list(list_temp))
raw_list = []
# Opening multiple hydra log files
root = Tk()
root.withdraw()
Path = filedialog.askdirectory()
total_files = 0
for path, subdirs, filelist in os.walk(Path):
for name in filelist:
total_files += 1
with open(path + "/" + name, 'rb') as f:
byte = f.read(1)
while byte:
raw_list.append(int(ord(byte)))
byte = f.read(1)
#If only one raw file is present, add filename as prefix to output
if (total_files==1):
out_file_prefix = filelist[0] + "_"
else:
out_file_prefix = ""
# Scanning through the list to look for different types of packets
array_index = 0
pkt_cnt = 1
actual_pckt_len = 0
check_flag = 0
while (array_index + 5 < len(raw_list)):
packet_header = int(raw_list[array_index])
packet_apid = int(raw_list[array_index + 1])
packet_length = 256 * raw_list[array_index + 4] + raw_list[array_index + 5]
if (packet_header != 8):
array_index += 1
continue
for j in range(0, len(list_packets), 1):
if ( packet_apid == int(list_packets[j][1]) and packet_length == int(list_packets[j][2])):
print("Header", packet_header, " Number", pkt_cnt, "APID", packet_apid, "Length", packet_length)
list_packets[j][3].append(list(raw_list[array_index:array_index + packet_length + 7])) #7
actual_pckt_len = int(list_packets[j][2])
check_flag = 0
break
else:
check_flag = 1
if (check_flag == 1):
array_index += 1
continue
array_index = array_index + actual_pckt_len + 7 # 7
pkt_cnt += 1
# creating new level 0 and level 1 folders which would contain the decoded files
l0_directory = "Level 0 Packets"
path_new_l0 = os.path.join(Path, l0_directory)
os.mkdir(path_new_l0)
l1_directory = "Level 1 Packets"
path_new_l1 = os.path.join(Path, l1_directory)
os.mkdir(path_new_l1)
# writing the raw different types of packets to level 0 csv files
for j in range(0, len(list_packets), 1):
if (len(list_packets[j][3]) > 0):
name_str = out_file_prefix + str(list_packets[j][0]) + "_level_0.csv"
with open(path_new_l0 +"/"+ name_str, "w") as f:
writer = csv.writer(f)
for row in list_packets[j][3]:
writer.writerow(row)
# Arranging the definations as an array according to APIDs in the list_packets
for m in range(0, len(packets_def), 1):
#print((packets_def[m][0]))
#print((packets_def[m][1]))
curr_packet_apid = (int(packets_def[m][1]))
for n in range(0, len(list_packets), 1):
if (curr_packet_apid == int(list_packets[n][1])):
list_packets[n][5].append(list(packets_def[m]))
# Now implementing the level 1 conversions for all level 0 packets read
for a in range(0, len(list_packets), 1):
if (len(list_packets[a][3]) > 0):
# Perform the level 1 conversions first
cur_packet_decode_apid = int(list_packets[a][1])
print("current APID is", cur_packet_decode_apid)
curr_packet_actual_len = int(list_packets[a][2])+7
curr_packet_raw_array = list_packets[a][3]
curr_packet_def = list_packets[a][5]
curr_packet_decode_number = a
curr_packet_header_array = []
curr_packet_decoded_array = []
curr_decoded_array_index = 0
for i in range(0, len(curr_packet_raw_array), 1):
if (len(curr_packet_raw_array[i]) != curr_packet_actual_len):
continue
for j in range(0, len(curr_packet_def), 1):
# Implementing decoding - combining bytes
type = curr_packet_def[j][2]
conversion = curr_packet_def[j][4:9]
#print(conversion)
endian = curr_packet_def[j][3]
if (type == 'U8' or type == 'D8' or type == 'I8' or type == 'F8' or type =='I6'):
var = curr_packet_raw_array[i][curr_decoded_array_index]
curr_packet_decoded_array.append(performConversion( performSignedValues(var,type ),conversion))
curr_decoded_array_index += 1
# Collecting the 1st Row which has the variable name
if (i == 0):
curr_packet_header_array.append(curr_packet_def[j][0])
elif (type == 'U16' or type == 'D16' or type == 'I16' or type == 'F16'):
if (endian == 'big'):
var = 256 * curr_packet_raw_array[i][curr_decoded_array_index + 1] + \
curr_packet_raw_array[i][
curr_decoded_array_index]
else:
var = 256 * curr_packet_raw_array[i][curr_decoded_array_index] + curr_packet_raw_array[i][
curr_decoded_array_index + 1]
curr_packet_decoded_array.append(performConversion( performSignedValues(var,type ),conversion))
curr_decoded_array_index += 2
# Collecting the 1st Row which has the variable name
if (i == 0):
curr_packet_header_array.append(curr_packet_def[j][0])
elif (type == 'U24' or type == 'D24' or type == 'I24' or type == 'F24'):
if (endian == 'big'):
var = 256 * 256 * curr_packet_raw_array[i][curr_decoded_array_index + 2] \
+ 256 * curr_packet_raw_array[i][curr_decoded_array_index + 1] \
+ curr_packet_raw_array[i][curr_decoded_array_index]
else:
var = 256 * 256 * curr_packet_raw_array[i][curr_decoded_array_index] \
+ 256 * curr_packet_raw_array[i][curr_decoded_array_index + 1] \
+ curr_packet_raw_array[i][curr_decoded_array_index + 2]
curr_packet_decoded_array.append(performConversion( performSignedValues(var,type ),conversion))
curr_decoded_array_index += 3
# Collecting the 1st Row which has the variable name
if (i == 0):
curr_packet_header_array.append(curr_packet_def[j][0])
elif (type == 'U32' or type == 'D32' or type == 'I32' or type == 'F32'):
if (endian == 'big'):
var = 256 * 256 * 256 * curr_packet_raw_array[i][curr_decoded_array_index + 3] \
+ 256 * 256 * curr_packet_raw_array[i][curr_decoded_array_index + 2] \
+ 256 * curr_packet_raw_array[i][curr_decoded_array_index + 1] \
+ curr_packet_raw_array[i][curr_decoded_array_index]
else:
var = 256 * 256 * 256 * curr_packet_raw_array[i][curr_decoded_array_index] \
+ 256 * 256 * curr_packet_raw_array[i][curr_decoded_array_index + 1] \
+ 256 * curr_packet_raw_array[i][curr_decoded_array_index + 2] \
+ curr_packet_raw_array[i][curr_decoded_array_index + 3]
#curr_packet_decoded_array.append(performSignedValues(performConversion(var, conversion),type))
#Corrected code
curr_packet_decoded_array.append(performConversion(performSignedValues(var, type),conversion))
curr_decoded_array_index += 4
# Collecting the 1st Row which has the variable name
if (i == 0):
curr_packet_header_array.append(curr_packet_def[j][0])
elif (type == 'U608'):
for p in range(0, 76, 1):
# Collecting the 1st Row which has the variable name
if (i == 0):
curr_packet_header_array.append(curr_packet_def[j][0])
var = curr_packet_raw_array[i][curr_decoded_array_index]
curr_packet_decoded_array.append(var)
curr_decoded_array_index += 1
elif (type == 'D1600'):
for p in range(0, 200, 1):
# Collecting the 1st Row which has the variable name
if (i == 0):
curr_packet_header_array.append(curr_packet_def[j][0])
var = curr_packet_raw_array[i][curr_decoded_array_index]
curr_packet_decoded_array.append(var)
curr_decoded_array_index += 1
elif (type == 'U1024'):
for p in range(0, 128, 1):
# Collecting the 1st Row which has the variable name
if (i == 0):
curr_packet_header_array.append(curr_packet_def[j][0])
var = curr_packet_raw_array[i][curr_decoded_array_index]
curr_packet_decoded_array.append(var)
curr_decoded_array_index += 1
elif (type == 'U1280'):
for p in range(0, 160, 1):
# Collecting the 1st Row which has the variable name
if (i == 0):
curr_packet_header_array.append(curr_packet_def[j][0])
var = curr_packet_raw_array[i][curr_decoded_array_index]
curr_packet_decoded_array.append(var)
curr_decoded_array_index += 1
elif (type == 'C1920'):
for p in range(0, 240, 1):
# Collecting the 1st Row which has the variable name
if (i == 0):
curr_packet_header_array.append(curr_packet_def[j][0])
var = curr_packet_raw_array[i][curr_decoded_array_index]
curr_packet_decoded_array.append(var)
curr_decoded_array_index += 1
elif (type == 'U1672'):
for p in range(0, 209, 1):
# Collecting the 1st Row which has the variable name
if (i == 0):
curr_packet_header_array.append(curr_packet_def[j][0])
var = curr_packet_raw_array[i][curr_decoded_array_index]
curr_packet_decoded_array.append(var)
curr_decoded_array_index += 1
elif (type == 'U376'):
for p in range(0, 23, 1):
# Collecting the 1st Row which has the variable name
if (i == 0):
curr_packet_header_array.append(curr_packet_def[j][0])
var = curr_packet_raw_array[i][curr_decoded_array_index]
curr_packet_decoded_array.append(var)
curr_decoded_array_index += 1
elif (type == 'U624'):
for p in range(0, 78, 1):
# Collecting the 1st Row which has the variable name
if (i == 0):
curr_packet_header_array.append(curr_packet_def[j][0])
var = curr_packet_raw_array[i][curr_decoded_array_index]
curr_packet_decoded_array.append(var)
curr_decoded_array_index += 1
list_packets[curr_packet_decode_number][4].append(list(curr_packet_decoded_array))
curr_decoded_array_index = 0
curr_packet_decoded_array = []
# Store the level 1 data in CSV files
name_str_l1 = out_file_prefix + str(list_packets[curr_packet_decode_number][0]) + "_level_1.csv"
with open(path_new_l1 +"/"+ name_str_l1, "w", newline='') as f:
writer = csv.writer(f)
writer.writerow(curr_packet_header_array)
for row in list_packets[curr_packet_decode_number][4]:
writer.writerow(row)
popupmsg("Success","Done! Level 0 and Level 1 Packets Created")
# -------------- HELPER FUNCTIONS FOR THIS SATNOGS DOWNLOAD FUNCTION----------------------------------------------------
def parse_command_line_args():
# Parsing command line arguments
parser = argparse.ArgumentParser(description='Command Line Parser')
parser.add_argument('-t', '--test', action="store_true", help="If present, program will be run in test mode")
parser.add_argument('-d', '--debug', action="store_true", help="If present, program will be run in debug mode")
parser.add_argument('-v', '--verbose', action="store_true", help="If present, program will be run in verbose mode")
parser.add_argument('-m', '--mission', type=str, help="Specify specific mission using this parameter")
parser.add_argument('-c', '--config', type=str,
help="Specifies what config file to use. If absent, cfg/example.cfg will be used")
args = parser.parse_args() # test bool will be stored in args.test
return args
#Adding Support for downloading data from satnogs
def downloadSatnogsFile():
args = parse_command_line_args()
# Check if user set the config file command line argument. If so, extract it. This argument should
# really always be used, unless "example.cfg" is changed to be something else.
if args.config:
config_file = args.config # user specified config file
else:
config_file = 'cfg/default_config.yml' # example config file
# Load the config info from the file specified. Will get exception if file does not exist.
config = cubeds.config.Config(file=config_file)
# SETUP runtime parameters.
if int(config.config['runtime']['verbose']):
verbose = True
elif args.verbose:
verbose = True
else:
verbose = False
if int(config.config['runtime']['test']):
test = True
elif args.test:
test = True
else:
test = False
if int(config.config['runtime']['debug']):
debug = True
elif args.debug:
debug = True
else:
debug = False
nogs = Satnogs(config)
nogs.save_satnogs_data()
popupmsg("Success", "Satnogs Data Downloaded")
def About():
popupmsg("About","INSPIRE Telemetry Decoder Version 6, Created by: Anant "
"\nSource Code: https://github.com/anant-infinity/IS1_Temeletry_Decoding.git")
root = Tk()
root.iconbitmap(default='inspire_logo_icon.ico')
root.title("INSPIRE Telemetry Decoder v6")
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="Decode", menu=filemenu)
filemenu.add_command(label="Select Folder and Decode Files", command=batchDecodePackets)
downloadmenu = Menu(menu)
menu.add_cascade(label="Download Raw Files", menu=downloadmenu)
downloadmenu.add_command(label="Download Satnogs Raw File", command=downloadSatnogsFile)
helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About...", command=About)
text1 = Text(root, height=30, width=75)
photo = PhotoImage(file='./INSPIRE_logo.png')
text1.insert(END, '\n')
text1.image_create(END, image=photo)
text1.pack(side=LEFT)
text2 = Text(root, height=30, width=70)
scroll = Scrollbar(root, command=text2.yview)
text2.configure(yscrollcommand=scroll.set)
text2.tag_configure('bold_italics', font=('Verdana', 12, 'bold', 'italic'))
text2.tag_configure('big', font=('Verdana', 16, 'bold'))
text2.tag_configure('color',
foreground='#476042',
font=('Verdana', 12, 'bold'))
text2.tag_bind('follow',
'<1>',
lambda e, t=text2: t.insert(END, "Not now, maybe later!"))
text2.insert(END,'\nHow to Run\n', 'big')
quote = """
This application can be used to generate
Level 0 and Level 1 telemetry.Follow the
following steps to decode the raw data files:
1. Click Decode-> Select Folder and Decode Packets
2. Open the folder (/directory) containing the Raw Log files
Done! Decoded Level 0 and Level 1 Packets will be
created in the same folder (as the raw files)
NOTE 1: The "packet_apids.csv" and the
"beacon_pckt_def.csv" must be present in the
folder containing the decoder application.
Further instructions of setting up are
provided in the ReadMe.
"""
text2.insert(END, quote, 'color')
text2.pack(side=LEFT)
scroll.pack(side=RIGHT, fill=Y)
mainloop()
|
jamesrr39/public-ip-logger
|
log-ip.py
|
#!/usr/bin/python
import subprocess
__author__ = 'james'
import urllib2
from BeautifulSoup import BeautifulSoup
from gi.repository import Notify
import time
from datetime import datetime
import os
def get_ip():
req = urllib2.Request("http://checkip.dyndns.org/")
webpage = urllib2.urlopen(req).read()
webpage_text = (BeautifulSoup(webpage)).find('body').text
return webpage_text.split("Current IP Address: ")[1]
def notify(ip_address, ssid):
notify_message = "Current ip address: {0} from {1}".format(ip_address, ssid)
Notify.init("ip address notification")
notification = Notify.Notification.new(notify_message)
notification.show()
def log(ip_address, ssid):
log_file_name = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'logs', 'ip_address.log')
file = open(log_file_name, 'a+')
timestamp = int(time.time())
file.write("{0}|{1}|{2}|{3}\n".format(datetime.fromtimestamp(timestamp), str(timestamp), ip_address, ssid))
def get_ssid():
try:
return subprocess.check_output(["iwgetid", "-r"]).replace("\n", "")
except subprocess.CalledProcessError, e:
return None
ip_address = get_ip()
ssid = get_ssid()
log(ip_address, ssid)
notify(ip_address, ssid)
|
chucknthem/Data-structures-algorithms
|
algorithms/edit_dist.py
|
# The edit distance or Levenshteien distance between two strings is the
# minimum number of insertion, deletion, and substitution operations it takes
# to transfer one string into another.
# http://en.wikipedia.org/wiki/Levenshtein_distance
# This algorithm uses a bottom up dynamic programming approach to calculate
# the edit distance. Using a 2D array d of size [m + 1][n + 1] where m and n
# are the length of strings a and b respectively. d[i][j] represents the
# edit distance of the substrings a[0:i] and b[0:j]
def edit_dist(str1, str2):
w = len(str1) + 1
h = len(str2) + 1
d = [[0 for i in xrange(w)] for j in xrange(h)]
# The edit distance of str1 and the empty string is i.
for i in xrange(w):
d[0][i] = i
# The edit distance of str2 and the empty string is j.
for j in xrange(h):
d[j][0] = j
for j in xrange(1, h):
for i in xrange(1, w):
if str1[i - 1] == str2[j - 1]:
d[j][i] = d[j - 1][i - 1] # No change.
else:
d[j][i] = min(
d[j - 1][i] + 1, # Deletion
d[j][i - 1] + 1, # Insertion
d[j - 1][i - 1] + 1 # Substitution
)
return d[len(str2)][len(str1)]
if __name__ == '__main__':
print edit_dist('medic', 'edit')
|
andrewguy9/safeoutput
|
safeoutput/__init__.py
|
<gh_stars>1-10
import argparse
import logging
import sys
from builtins import object
from os import rename
from os.path import abspath, dirname
from tempfile import NamedTemporaryFile
LOG = logging.getLogger(__name__)
def open(dst=None, mode="w"):
if dst:
fd = NamedTemporaryFile(dir=dirname(abspath(dst)), mode=mode)
else:
if mode == "w":
fd = sys.stdout
else:
try:
fd = sys.stdout.buffer
except AttributeError:
fd = sys.stdout
return _SafeOutputWrapper(fd, dst)
class _SafeOutputWrapper(object):
def __init__(self, fd, dst):
self.fd = fd
self.dst = dst
def __enter__(self):
if self.dst:
self.fd.__enter__()
return self
def __getattr__(self, name):
# Attribute lookups are delegated to the underlying tempfile
fd = self.__dict__['fd']
a = getattr(fd, name)
return a
def close(self, commit=True):
if self.dst:
if commit == True:
LOG.debug(u"renaming %s to %s", self.fd.name, self.dst)
self.fd.flush()
rename(self.fd.name, self.dst)
# self.fd.delete = False # doesn't work in python3...?
try:
LOG.debug(u"closed %s", self.fd.name)
self.fd.close()
except EnvironmentError: # aka FileNotFoundError in Python 3
pass
def __exit__(self, exc_type, exc_value, traceback):
self.close(exc_value is None)
if self.dst:
return self.fd.__exit__(exc_type, exc_value, traceback)
else:
return exc_type == None
def __del__(self):
# If we get to __del__ and have not already committed,
# we don't know that the output is safe. Allow
# tempfile to delete the file.
self.close(False)
def main(args=None):
"""Buffer stdin and flush, and avoid incomplete files."""
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument('--binary',
dest='mode',
action='store_const',
const="wb",
default="w",
help='write in binary mode')
parser.add_argument('output',
metavar='FILE',
type=unicode,
help='Output file')
logging.basicConfig(
level=logging.DEBUG,
stream=sys.stderr,
format='[%(levelname)s elapsed=%(relativeCreated)dms] %(message)s')
args = parser.parse_args(args or sys.argv[1:])
with open(args.output, args.mode) as fd:
for line in sys.stdin:
fd.write(line)
|
andrewguy9/safeoutput
|
tests/test_safeoutput.py
|
<filename>tests/test_safeoutput.py
import inspect
from os import remove
from os.path import isfile
import pytest
import safeoutput
def _filename():
return u"testfile_" + inspect.stack()[1][3]
def ensure_file_absent(path):
try:
remove(path)
except OSError:
pass
def expected_file(path, expected, cleanup=True):
if isinstance(expected, str):
mode = "r"
else:
mode = "rb"
try:
if expected is not None:
with open(path, mode) as f:
content = f.read()
return content == expected
else:
return False == isfile(path)
finally:
if cleanup:
ensure_file_absent(path)
def test_file_with_success_str():
file_data = u"testoutput"
mode = "w"
expect_success(file_data, mode)
def test_file_with_success_bytes():
file_data = u"testoutput".encode('utf-8')
mode = "wb"
expect_success(file_data, mode)
def expect_success(file_data, mode):
file_name = _filename()
ensure_file_absent(file_name)
with safeoutput.open(file_name, mode) as f:
f.write(file_data)
assert expected_file(file_name, file_data)
def test_with_exception():
file_name = _filename()
file_data = u"testoutput"
ensure_file_absent(file_name)
try:
with safeoutput.open(file_name) as f:
f.write(file_data)
raise ValueError(u"We eff'ed up")
except ValueError:
pass
assert expected_file(file_name, None)
def test_close_success():
file_name = _filename()
file_data = u"testoutput"
ensure_file_absent(file_name)
f = safeoutput.open(file_name)
f.write(file_data)
f.close()
assert expected_file(file_name, file_data)
def test_close_exception():
file_name = _filename()
file_data = u"testoutput"
ensure_file_absent(file_name)
def write():
f = safeoutput.open(file_name)
f.write(file_data)
raise ValueError(u"We eff'ed up")
try:
write()
except ValueError:
pass
assert expected_file(file_name, None)
def test_write_after_close():
file_name = _filename()
file_data = u"testoutput"
ensure_file_absent(file_name)
f = safeoutput.open(file_name)
f.write(file_data)
f.close()
assert expected_file(file_name, file_data, False)
with pytest.raises(ValueError):
f.write(file_data)
assert expected_file(file_name, file_data)
def test_write_stdout_after_close(capsys):
file_data = u"testoutput"
f = safeoutput.open(None)
f.write(file_data)
f.close()
f.write(file_data)
out,err = capsys.readouterr()
assert out == file_data + file_data
assert err == ""
def test_stdout_with_success_str(capsys):
file_data = u"testoutput"
mode = "w"
with safeoutput.open(None, mode) as f:
f.write(file_data)
out,err = capsys.readouterr()
assert out == file_data
assert err == ""
|
andrewguy9/safeoutput
|
setup.py
|
from setuptools import setup
tests_require = ['tox', 'pytest']
setup(
name='safeoutput',
version='2.0',
description='Tempfile wrapper to ensure output files are either complete, or empty. Also handles stdout, which gives no truncation guarantees.',
long_description='Tool to facilitate console script output redirection. When scripts run, often they have an output file option. If no output option is specified, its common to write to stdout. Its common to use tempfiles as output, and then rename the tempfile to the output name as the last step of the program so that the flip of output is atomic and partial/truncated/corrupt output is not confused as successful output. This is especially true when dealing with make, as exiting with error will stop make, but subsequent runs will assume that partial output files left in the workspace are complete. Writing to stdout gives no guarantees about partial results due to truncation.',
url='http://github.com/andrewguy9/safeoutput',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['safeoutput'],
install_requires=['future'],
tests_require=tests_require,
extras_require={'test': tests_require},
entry_points={'console_scripts': ['safeoutput = safeoutput:main']},
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Libraries',
'Topic :: System :: Filesystems',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 2.7',
],
zip_safe=True)
|
iamavx/AI_Sudoku_Solver
|
main.py
|
print('This is a opencv project created by <NAME> ')
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # To avoid the warning and log message
from utlis import *
import sudukoSolver
pathImage = "Resources/1.jpeg" # path of image
heightImg = 450
widthImg = 450
model = intializePredectionModel() # LOAD THE CNN MODEL
#### 1. Preprocessing of the image
img = cv2.imread(pathImage) # imread method is used to read the input image
img = cv2.resize(img, (widthImg, heightImg)) # Resize yhe image and make it as square because sudoku is 9*9 matrix
imgBlank = np.zeros((heightImg, widthImg, 3), np.uint8) # create a blank image for testing and debugging of image
imgThreshold = preProcess(img) # preprocessing the image where u have to convert it into grayscale so that we can find countour easily
# 2. Find All the Countour i.e contours are a useful tool for shape analysis and object detection
imgContours = img.copy() # we are going to copy that image for displaying image
imgBigContour = img.copy() # we are going to copy that image for displaying image
contours, hierarchy = cv2.findContours(imgThreshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # find all the contours
cv2.drawContours(imgContours, contours, -1, (0, 255, 0), 3) # actually it will draw all the contours
# 3.find the biggest contours which u can consider as sudoku
biggest, maxArea = biggestContour(contours) # Find the biggest contours
print(biggest)
if biggest.size != 0:
biggest = reorder(biggest) # when we are checking for differnt image their width and height order changes
print(biggest)
cv2.drawContours(imgBigContour, biggest, -1, (0, 0, 255), 25) # Draw the biggest contours
pts1 = np.float32(biggest) #prepare the point for warp perspective
pts2 = np.float32([[0, 0],[widthImg, 0], [0, heightImg],[widthImg, heightImg]]) # prepare the poin for wrap
matrix = cv2.getPerspectiveTransform(pts1, pts2) # GER
imgWarpColored = cv2.warpPerspective(img, matrix, (widthImg, heightImg))
imgDetectedDigits = imgBlank.copy() # take the image of black image
imgWarpColored = cv2.cvtColor(imgWarpColored,cv2.COLOR_BGR2GRAY) # It will convert into greyscale
# 4. Split the image and find each digit available
imgSolvedDigits = imgBlank.copy() # It will take blank image
boxes = splitBoxes(imgWarpColored)
print(len(boxes))
numbers = getPredection(boxes, model)
print(numbers)
imgDetectedDigits = displayNumbers(imgDetectedDigits, numbers, color=(255, 0, 255))
numbers = np.asarray(numbers)
posArray = np.where(numbers > 0, 0, 1)
print(posArray)
# 5. Find the solution of board
board = np.array_split(numbers,9)
print(board)
try:
sudukoSolver.solve(board)
except:
pass
print(board)
flatList = []
for sublist in board:
for item in sublist:
flatList.append(item)
solvedNumbers =flatList*posArray
imgSolvedDigits= displayNumbers(imgSolvedDigits,solvedNumbers)
# 6. Solution
pts2 = np.float32(biggest) # PREPARE POINTS FOR WARP
pts1 = np.float32([[0, 0],[widthImg, 0], [0, heightImg],[widthImg, heightImg]]) # PREPARE POINTS FOR WARP
matrix = cv2.getPerspectiveTransform(pts1, pts2) # GER
imgInvWarpColored = img.copy()
imgInvWarpColored = cv2.warpPerspective(imgSolvedDigits, matrix, (widthImg, heightImg))
inv_perspective = cv2.addWeighted(imgInvWarpColored, 1, img, 0.5, 1)
imgDetectedDigits = drawGrid(imgDetectedDigits)
imgSolvedDigits = drawGrid(imgSolvedDigits)
imageArray = ([img,imgThreshold,imgContours, imgBigContour],
[imgDetectedDigits, imgSolvedDigits,imgInvWarpColored,inv_perspective])
stackedImage = stackImages(imageArray, 1)
cv2.imshow('Final Stacked Image created by <NAME>', stackedImage)
else:
print("No Sudoku Found")
cv2.waitKey(0)
|
yasuit21/EarthScienceExperiment
|
winpy.py
|
<reponame>yasuit21/EarthScienceExperiment
## winpy.py - Manipulate WIN files
## Sample code to outout csv files of WIN data
## Apr 05, 2021 <NAME>
import sys
import os
from pathlib import Path
import argparse
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
import obspy as ob
class WinTools():
"""Manipulate WIN files.
Usage:
------
>>> from winpy import WinTools
>>> wt = WinTools()
>>> st = wt.read('sample.win')
>>> wt.write('out.csv','CSV',decimate=10)
Note:
This program was coded by <NAME>.
The original program was coded by Dr. <NAME>.
"""
def __init__(self):
self.stream = None
def read(
self, filepath, IDs=None,
respAD=5.11745*10**-8, sensitivity=70.,
):
"""Read an WIN file to create obspy.Stream object.
Parameters:
-----------
filepath : str or pathlib.Path
A filename to save data
IDs : list, default to None
Select channel IDs to load.
If None, all channels will be loaded.
respAD : float
Voltage per digit [V/counts].
If None, will be 1.
sensitivity : float
Sensitivity of seismometers [V/(m/s)].
Unit will be [nm] when attached the sensitivity.
If None, no sensitivity will be fixed.
"""
if IDs:
IDs = [s.lower() for s in IDs]
self.respAD = respAD if respAD else 1.
if sensitivity:
self.sensitivity = sensitivity
self.nanometer = 10**9
else:
self.sensitivity = self.nanometer = 1.
self.filepath = Path(filepath)
## Load all data as `._buffer`
with self.filepath.open('rb') as f:
self._buffer = f.read()
self._offset = 0
iteration = 0
final_iteration = defaultdict(lambda: 0)
self.output_data = defaultdict(lambda: dict(data=None, sampling_rate=None))
while self._offset < len(self._buffer):
starttime = self._load_header_second()
if iteration == 0:
self._starttime = starttime
iteration += 1
fixed_bulk = self._blocksize + self._offset - 10
while self._offset < fixed_bulk:
chID = self._load_header_channel()
self._calc_bytes_in_sample()
if IDs and (not chID in IDs):
self._offset += self._total_bytes_wav
continue
## Waveforms
self._wav_buffer = self._buffer[self._offset:self._offset+self._total_bytes_wav]
self._convert_buffer_to_wav()
self._offset += self._total_bytes_wav
## output
if (chID in self.output_data) or (iteration != 0) :
dt = iteration - final_iteration[chID] - 1
if dt > 0:
nanarray = np.empty(dt*self.sample_rate) * np.nan
self._wavdata = np.hstack([nanarray, self._wavdata])
if chID in self.output_data:
self.output_data[chID]['data'] = np.hstack([
self.output_data[chID]['data'], self._wavdata
])
else:
self.output_data[chID]['data'] = self._wavdata
self.output_data[chID]['sampling_rate'] = self.sample_rate
final_iteration[chID] = iteration
self._create_stream()
self._clean()
return self.stream
def _load_header_second(self):
self._blocksize = int.from_bytes(
self._buffer[self._offset:self._offset+4], byteorder='big'
)
self._offset += 4
buffer_date = self._buffer[self._offset:self._offset+6]
self._offset += 6
## Output starttime
return ob.UTCDateTime(
int(f'20'+buffer_date[:1].hex()),
*[int(f'{b:x}') for b in buffer_date[1:6]]
)
def _load_header_channel(self):
buffer_channel = self._buffer[self._offset:self._offset+4]
self._offset += 4
chID = buffer_channel[:2].hex()
_tmp = buffer_channel[2:].hex()
self.sample_size = int(_tmp[0], 16)
self.sample_rate = int(_tmp[1:], 16)
return chID
def _calc_bytes_in_sample(self):
bytes_per_sample = self._load_data_byte(self.sample_size)
## Total bytes in waveform - Round up to int
self._total_bytes_wav = 4 + -int((-bytes_per_sample*(self.sample_rate-1))//1)
def _load_data_byte(self, size):
if size == 0:
bytes_per_sample = 0.5
elif size == 5:
bytes_per_sample = 4
else:
bytes_per_sample = size
return bytes_per_sample
def _convert_buffer_to_wav(self):
#sys.stdout.write(f'{self.sample_size}')
if self.sample_size == 5:
wav_data = np.frombuffer(
self._wav_buffer, dtype='>i4', count=self.sample_rate-1, offset=0
)
else: ## not 5
## Load initial value separately
if self.sample_size == 3:
initial_value = np.frombuffer(
self._wav_buffer[:4],
dtype='>i4', count=1, offset=0
)
else:
initial_value = np.frombuffer(
self._wav_buffer,
dtype='>i4', count=1, offset=0
)
## Wave data
if self.sample_size == 0:
_tmp = np.frombuffer(
self._wav_buffer,
dtype='>i1',
count=-((1-self.sample_rate)//2), offset=4,
)
wav_data = np.vstack([_tmp>>4,_tmp<<4>>4]).T.reshape(-1,)
elif self.sample_size == 3:
wav_data = np.array([
int.from_bytes(self._wav_buffer[3*i+4:3*i+7],'big',signed=True)
for i in range(self.sample_rate-1)
])
else: # [1,2,4]
wav_data = np.frombuffer(
self._wav_buffer,
dtype=f'>i{self.sample_size}',
count=self.sample_rate-1, offset=4,
)
self._wavdata = np.cumsum(
np.hstack([initial_value, wav_data])
)
def _create_stream(self):
self.stream = ob.Stream()
for (k, v) in self.output_data.items():
tr = ob.Trace(
data=v['data']*self.respAD/self.sensitivity*self.nanometer
)
tr.stats.update(dict(
channel=k, sampling_rate=v['sampling_rate'],
starttime=self._starttime
))
self.stream += tr
def write(self, filename, format='CSV', decimate=None, **kwargs):
"""Save stream as a file in various formats.
Parameters:
-----------
filename : str or pathlib.Path
A filename to save data
format : str, default to 'CSV'
'CSV' or other formats ('WAV','SAC','pickle'...)
For details, see https://docs.obspy.org/packages/autogen/obspy.core.stream.Stream.write.html
decimate : int, default to None
If integer from 2 to 16, decimate output file.
"Decimation" means number of data reducing by 1/n.
"""
try:
if format.upper() == 'CSV':
save_as_csv(filename, self.stream, decimate)
else:
self.stream.write(filename, format=format, **kwargs)
except NameError:
raise Exception('No stream found. Call `.read()` first.')
def _clean(self):
try:
del (
self._blocksize, self._buffer, self._offset,
self._total_bytes_wav, self._wav_buffer,
self.sample_size, self.sample_rate,
self._wavdata, self._starttime
)
except NameError:
pass
def save_as_csv(filename, stream, decimate=None):
st = stream.copy()
if decimate:
st.decimate(factor=decimate)
with open(filename, 'w') as f:
f.write(
f"# STATION {st[0].stats.station}\n"+
f"# START_TIME {str(st[0].stats.starttime)}\n"+
f"# SAMPING_FREQ {st[0].stats.sampling_rate:.1f}\n"+
f"# NDAT {st[0].stats.npts}\n"
)
np.savetxt(
f, np.vstack([st[0].times()]+[tr.data for tr in st]).T,
delimiter=',', #comments='#'
header='time [s],'+','.join([tr.stats.channel for tr in st])
)
__author__ = '<NAME>'
__status__ = "production"
__date__ = "Apr 05, 2021"
__version__ = "0.1.0"
if __name__ == '__main__':
## Parser
parser = argparse.ArgumentParser(description='Creating CSV files of selected WIN files.')
parser.add_argument('files', nargs='*', help='File names or paths to manipulate')
parser.add_argument('-o', '--outpath', default='./output', help='Directory path for output files.')
args = parser.parse_args()
filepaths = [Path(p) for p in args.files]
outpath = Path(args.outpath)
## Main
wt = WinTools()
for p in filepaths:
## Read a file
sys.stdout.write(f'\nNow loading {str(p)} ...\n')
wt.read(p)
## Write as CSV
sys.stdout.write(f'Creating CSV file for {str(p)} under "{str(outpath)}"\n')
wt.write(outpath/f'{p.name}.csv', decimate=10)
|
decopificador/OpenHAB
|
configurations/scripts/jsr223_demo.py
|
class TestRule(Rule):
def __init__(self):
self.logger = oh.getLogger("TestRule")
def getEventTrigger(self):
return [
StartupTrigger(),
ChangedEventTrigger("Heating_FF_Child", None, None),
TimerTrigger("0/50 * * * * ?")
]
def execute(self, event):
self.logger.debug("event received {}", event)
oh.logInfo("TestRule", str(ItemRegistry.getItem("Heating_GF_Corridor")))
action = oh.getActions()
oh.logInfo("TestRule", "available actions: " + str(action.keySet()))
ping = oh.getAction("Ping")
oh.logInfo("TestRule", "internet reachable: " + ("yes" if ping.checkVitality("google.com", 80, 100) else "no"))
def whoop():
print "yeah"
oh.createTimer(DateTime.now().plusSeconds(10), whoop)
def getRules():
return RuleSet([
TestRule()
])
|
alankan886/SuperMemo2
|
supermemo2/__init__.py
|
from .sm_two import *
|
alankan886/SuperMemo2
|
supermemo2/sm_two.py
|
<reponame>alankan886/SuperMemo2
from math import ceil
from datetime import date, datetime, timedelta
from typing import Optional, Union, Dict
import attr
year_mon_day = "%Y-%m-%d"
mon_day_year = "%m-%d-%Y"
day_mon_year = "%d-%m-%Y"
@attr.s
class SMTwo:
easiness = attr.ib(validator=attr.validators.instance_of(float))
interval = attr.ib(validator=attr.validators.instance_of(int))
repetitions = attr.ib(validator=attr.validators.instance_of(int))
review_date = attr.ib(init=False)
@staticmethod
def first_review(
quality: int,
review_date: Optional[Union[date, str]] = None,
date_fmt: Optional[str] = None,
) -> "SMTwo":
if not review_date:
review_date = date.today()
if not date_fmt:
date_fmt = year_mon_day
return SMTwo(2.5, 0, 0).review(quality, review_date, date_fmt)
def review(
self,
quality: int,
review_date: Optional[Union[date, str]] = None,
date_fmt: Optional[str] = None,
) -> "SMTwo":
if not review_date:
review_date = date.today()
if not date_fmt:
date_fmt = year_mon_day
if isinstance(review_date, str):
review_date = datetime.strptime(review_date, date_fmt).date()
if quality < 3:
self.interval = 1
self.repetitions = 0
else:
if self.repetitions == 0:
self.interval = 1
elif self.repetitions == 1:
self.interval = 6
else:
self.interval = ceil(self.interval * self.easiness)
self.repetitions = self.repetitions + 1
self.easiness += 0.1 - (5 - quality) * (0.08 + (5 - quality) * 0.02)
if self.easiness < 1.3:
self.easiness = 1.3
review_date += timedelta(days=self.interval)
self.review_date = review_date
return self
|
alankan886/SuperMemo2
|
tests/test_sm_two.py
|
from datetime import date, timedelta
import pytest
from supermemo2 import SMTwo, year_mon_day, mon_day_year, day_mon_year
@pytest.mark.parametrize(
"quality, expected_easiness, expected_interval, expected_repetitions, expected_review_date",
[
(0, 1.7000000000000002, 1, 0, date.today() + timedelta(days=1)),
(1, 1.96, 1, 0, date.today() + timedelta(days=1)),
(2, 2.1799999999999997, 1, 0, date.today() + timedelta(days=1)),
(3, 2.36, 1, 1, date.today() + timedelta(days=1)),
(4, 2.5, 1, 1, date.today() + timedelta(days=1)),
(5, 2.6, 1, 1, date.today() + timedelta(days=1)),
],
)
def test_first_review(
quality,
expected_easiness,
expected_interval,
expected_repetitions,
expected_review_date,
):
reviewed = SMTwo.first_review(quality)
assert reviewed.easiness == expected_easiness
assert reviewed.interval == expected_interval
assert reviewed.repetitions == expected_repetitions
assert reviewed.review_date == expected_review_date
@pytest.mark.parametrize(
"quality, review_date, expected_easiness, expected_interval, expected_repetitions, expected_review_date",
[
(0, date.today(), 1.7000000000000002, 1, 0, date.today() + timedelta(days=1)),
(1, date.today(), 1.96, 1, 0, date.today() + timedelta(days=1)),
(2, date.today(), 2.1799999999999997, 1, 0, date.today() + timedelta(days=1)),
(3, date.today(), 2.36, 1, 1, date.today() + timedelta(days=1)),
(4, date.today(), 2.5, 1, 1, date.today() + timedelta(days=1)),
(5, date.today(), 2.6, 1, 1, date.today() + timedelta(days=1)),
],
)
def test_first_review_given_date(
quality,
review_date,
expected_easiness,
expected_interval,
expected_repetitions,
expected_review_date,
):
reviewed = SMTwo.first_review(quality, review_date)
assert reviewed.easiness == expected_easiness
assert reviewed.interval == expected_interval
assert reviewed.repetitions == expected_repetitions
assert reviewed.review_date == expected_review_date
@pytest.mark.parametrize(
"str_date, date_fmt",
[
("2021-12-01", None),
("2021-12-01", year_mon_day),
("12-01-2021", mon_day_year),
("01-12-2021", day_mon_year),
],
)
def test_first_review_given_date_in_str(str_date, date_fmt):
reviewed = SMTwo.first_review(3, str_date, date_fmt)
assert reviewed.easiness == 2.36
assert reviewed.interval == 1
assert reviewed.repetitions == 1
assert reviewed.review_date == date(2021, 12, 1) + timedelta(days=1)
@pytest.mark.parametrize(
"quality, easiness, interval, repetitions, expected_easiness, expected_interval, expected_repetitions, expected_review_date",
[
(0, 2.3, 12, 3, 1.5, 1, 0, date.today() + timedelta(days=1)),
(1, 2.3, 12, 3, 1.7599999999999998, 1, 0, date.today() + timedelta(days=1)),
(2, 2.3, 12, 3, 1.9799999999999998, 1, 0, date.today() + timedelta(days=1)),
(3, 2.3, 12, 3, 2.1599999999999997, 28, 4, date.today() + timedelta(days=28)),
(4, 2.3, 12, 3, 2.3, 28, 4, date.today() + timedelta(days=28)),
(5, 2.3, 12, 3, 2.4, 28, 4, date.today() + timedelta(days=28)),
],
)
def test_review(
quality,
easiness,
interval,
repetitions,
expected_easiness,
expected_interval,
expected_repetitions,
expected_review_date,
):
sm = SMTwo(easiness, interval, repetitions)
reviewed = sm.review(quality)
assert reviewed.easiness == expected_easiness
assert reviewed.interval == expected_interval
assert reviewed.repetitions == expected_repetitions
assert reviewed.review_date == expected_review_date
@pytest.mark.parametrize(
"quality, easiness, interval, repetitions, review_date, expected_easiness, expected_interval, expected_repetitions, expected_review_date",
[
(
0,
2.3,
12,
3,
date.today(),
1.5,
1,
0,
date.today() + timedelta(days=1),
),
(
1,
2.3,
12,
3,
date.today(),
1.7599999999999998,
1,
0,
date.today() + timedelta(days=1),
),
(
2,
2.3,
12,
3,
date.today(),
1.9799999999999998,
1,
0,
date.today() + timedelta(days=1),
),
(
3,
2.3,
12,
3,
date.today(),
2.1599999999999997,
28,
4,
date.today() + timedelta(days=28),
),
(
4,
2.3,
12,
3,
date.today(),
2.3,
28,
4,
date.today() + timedelta(days=28),
),
(5, 2.3, 12, 3, date.today(), 2.4, 28, 4, date.today() + timedelta(days=28)),
# test case for when easiness drops lower than 1.3
(0, 1.3, 12, 3, date.today(), 1.3, 1, 0, date.today() + timedelta(days=1)),
# test case for for repetitions equals to 2
(4, 2.5, 1, 1, date.today(), 2.5, 6, 2, date.today() + timedelta(days=6)),
],
)
def test_review_given_date(
quality,
easiness,
interval,
repetitions,
review_date,
expected_easiness,
expected_interval,
expected_repetitions,
expected_review_date,
):
sm = SMTwo(easiness, interval, repetitions)
reviewed = sm.review(quality, review_date)
assert reviewed.easiness == expected_easiness
assert reviewed.interval == expected_interval
assert reviewed.repetitions == expected_repetitions
assert reviewed.review_date == expected_review_date
|
marcosorive/reddit-ns-wiki-scrapper
|
src/Utils/scrapper.py
|
<reponame>marcosorive/reddit-ns-wiki-scrapper
import bs4
import re
from Model.Game import Game
from Utils import request_maker
def get_name_link(element):
anchor = element.find("a")
if anchor:
name = element.find("a").text
link = element.find("a").attrs["href"]
else:
name = element.text
link = ""
return name, link
def get_dev_pub(input):
splitted = input.text.split("/")
if len(splitted) == 1:
dev = publisher = splitted[0]
else:
dev = splitted[0]
publisher = splitted[1]
return dev, publisher
def get_dates(input):
dates = input.text
result = dict()
'''
Date types:
January 3, 2019 (NA), December 27, 2018 (EU), September 6, 2018 (JP)
Spring 2019/Early 2019/April 2019
TBD
'''
one_date_pattern = r"(\w+ \d+, \d+)"
multiple_date_pattern = r"(\w+ \d+, \d+ )(\(\w+\)|\(\w+, \w+\))"
season_year_pattern = r"(\w+) (\d+)"
if re.match(multiple_date_pattern,dates):
dates = re.findall(multiple_date_pattern,dates)
for regional_date in dates:
result[regional_date[1].strip("(").strip(")")] = regional_date[0].rstrip().lstrip()
elif re.match(one_date_pattern,dates):
result["ALL"] = re.findall(one_date_pattern,dates)[0]
elif re.match(season_year_pattern,dates):
result["ALL"] = re.findall(season_year_pattern,dates)[0][1]
else:
result["ALL"] = "TBD"
return result
def get_trailer_link(element):
if element.find("a"):
return element.find("a").attrs["href"] or ""
return ""
'''Function that given a <tr> elements extracts the data of the game.
Parameters:
row (bs4.element.Tag): a <tr> element.
Returns:
'''
def get_data_from_table_row(row):
row_data = list(filter(lambda x: x!="\n" , row.contents))
if len(row_data) != 4:
return None
game = Game()
game.name, game.link = get_name_link(row_data[0])
game.dev, game.publisher = get_dev_pub(row_data[1])
game.dates = get_dates(row_data[2])
game.trailer_link = get_trailer_link(row_data[3])
return game
'''Function that iterates every row in a table.
'''
def iterate_table(table):
all_games = list()
for child in table.children:
if isinstance(child, bs4.element.Tag):
all_games.append(get_data_from_table_row(child))
return all_games
|
marcosorive/reddit-ns-wiki-scrapper
|
src/main.py
|
<reponame>marcosorive/reddit-ns-wiki-scrapper
import bs4
from Utils.request_maker import get_test_file
from Utils.scrapper import iterate_table
html = get_test_file()
#response = get_text_body_from_url("https://www.reddit.com/r/NintendoSwitch/wiki/games")
soup = bs4.BeautifulSoup(html, 'html.parser', from_encoding="utf-8")
released_table_body = soup.find("h2",id="wiki_released").findNext('table').findNext("tbody")
iterate_table(released_table_body)
planned_table_body = soup.find("h2",id="wiki_planned").findNext('table').findNext("tbody")
table = iterate_table(planned_table_body)
for i in table:
print(i)
table = iterate_table(released_table_body)
for i in table:
print(i)
|
marcosorive/reddit-ns-wiki-scrapper
|
src/Utils/request_maker.py
|
import os
import requests
from fake_useragent import UserAgent
NINTENDO_SWITCH_WIKI_URL = "https://reddit.com/r/nintendoswitch/wiki/games"
TEST_DATA_DIR = "./test_data"
TEST_DATA_FILE = TEST_DATA_DIR+"/test_data.html"
def get_text_body_from_url(url):
ua = UserAgent()
headers = {
'User-Agent': ua.random
}
r = requests.get(url, headers=headers)
return r.text
def get_test_file():
if os.path.isdir(TEST_DATA_DIR):
file = open(TEST_DATA_FILE,"r",encoding='utf-8')
text = file.read()
file.close()
return text
else:
os.mkdir(TEST_DATA_DIR)
file = open(TEST_DATA_FILE,"w",encoding='utf-8')
text = get_text_body_from_url(NINTENDO_SWITCH_WIKI_URL)
file.write(text)
file.close()
return text
|
marcosorive/reddit-ns-wiki-scrapper
|
src/Model/Game.py
|
<reponame>marcosorive/reddit-ns-wiki-scrapper
class Game:
def __init__(self, name = None):
self.name = ""
self.link = ""
self.dev = ""
self.publisher = ""
self.dates = dict()
self.trailer_link = ""
def __str__(self):
return (
"Name: " + self.name + "\n" +
"Link: " + self.link + "\n" +
"Dev: " + self.dev +"\n" +
"Publisher: " + self.publisher + "\n" +
"Dates: " + str(self.dates) + "\n"
"Tailer link: " + self.trailer_link + "\n"
)
|
kunz07/fyp2017
|
Ubidots-RoomIOT.py
|
<reponame>kunz07/fyp2017
# FYP2017
# Program to send room temperature and humidity to ThingSpeak
# Author: <NAME>
# License: Public Domain
import time
import serial
import sys
from ubidots import ApiClient
f = open('Ubidots_APIkey.txt', 'r')
apikey = f.readline().strip()
f.close()
api = ApiClient(token = apikey)
try:
roomtemp = api.get_variable("58d763b8762542260a851bd1")
roomhumidity = api.get_variable("58d763c57625422609b8d088")
except ValueError:
print('Unable to obtain variable')
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
def sendData():
if ser.isOpen():
ser.close()
ser.open()
ser.isOpen()
ser.write('s'.encode())
time.sleep(2)
response = ser.readline().strip().decode()
hum = float(response[:5])
temp = float(response[5:])
try:
roomtemp.save_value({'value': temp})
roomhumidity.save_value({'value': hum})
print('Value',temp,'and',hum, 'sent')
time.sleep(2)
except:
print('Value not sent')
if __name__ == "__main__":
while True:
sendData()
time.sleep(5)
|
kunz07/fyp2017
|
BatteryIOT.py
|
# FYP2017
# Program to send battery status to ThingSpeak channel
# Author: <NAME>
# License: Public Domain
import time
import sys
import urllib.request
import urllib.parse
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
# Hardware SPI configuration:
SPI_PORT = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
# Main program loop.
def sendBattery():
time.sleep(3)
value = mcp.read_adc(0)
volts = ((value*3.3)) / float(1023) #voltage divider voltage
volts = volts * 5.7 #actual voltage
volts = round(volts,2)
if (volts >=13.6):
batt = 100
time.sleep(1)
f = open('TS_APIkey.txt','r')
api_key = f.read()
params = urllib.parse.urlencode({'key': api_key ,
'field3': batt ,
})
params = params.encode('utf-8')
fh = urllib.request.urlopen("https://api.thingspeak.com/update", data=params)
fh.close()
else:
batt = round ((volts))
time.sleep(1)
f = open('TS_APIkey.txt','r')
api_key = f.read()
params = urllib.parse.urlencode({'key': api_key ,
'field3': batt ,
})
params = params.encode('utf-8')
fh = urllib.request.urlopen("https://api.thingspeak.com/update", data=params)
fh.close()
print("Value Sent", batt)
if __name__ == "__main__":
while True:
sendBattery()
time.sleep(900)
|
kunz07/fyp2017
|
Fuzzy.py
|
<reponame>kunz07/fyp2017
# FYP2017
# Program to determine economy level of system using fuzzy logic
# Author: <NAME>
# License: Public Domain
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import Weather
import Battery
# New Antecedent/Consequent objects hold universe variables and membership
# functions
batt_percent = ctrl.Antecedent(np.arange(0, 100, 1), 'Battery_percentage')
temp = ctrl.Antecedent(np.arange(15, 30, 1), 'Temperature')
cloud_cover = ctrl.Antecedent(np.arange(0, 1, 0.01), 'Cloud_cover')
eco_level = ctrl.Consequent(np.arange(1, 4, 0.01), 'Economy_level')
# Battery membership function population
batt_percent['Low_battery'] = fuzz.trapmf(batt_percent.universe, [0, 0, 20, 30])
batt_percent['Medium_battery'] = fuzz.trapmf(batt_percent.universe, [20, 25, 75, 80])
batt_percent['High_battery'] = fuzz.trapmf(batt_percent.universe, [75, 80, 100, 100])
# Temperature membership function population
temp['Low_temperature'] = fuzz.trapmf(temp.universe, [0, 0, 18, 20])
temp['Medium_temperature'] = fuzz.trapmf(temp.universe, [18, 20, 24, 26])
temp['High_temperature'] = fuzz.trapmf(temp.universe, [24 , 26, 30, 30])
# Cloud_cover membership function population
cloud_cover['Minimum_clouds'] = fuzz.trapmf(cloud_cover.universe, [0, 0, 0.20, 0.25])
cloud_cover['Medium_clouds'] = fuzz.trapmf(cloud_cover.universe, [0.20, 0.25, 0.65, 0.70])
cloud_cover['High_clouds'] = fuzz.trapmf(cloud_cover.universe, [0.65, 0.70, 1, 1])
# Custom membership functions can be built interactively with a familiar,
# Pythonic API
eco_level['Critical'] = fuzz.trimf(eco_level.universe, [0, 1.0, 2.0])
eco_level['Alert'] = fuzz.trimf(eco_level.universe, [1.75, 2.25, 2.75])
eco_level['Normal'] = fuzz.trimf(eco_level.universe, [2.5, 3.0, 3.5])
eco_level['Economyless'] = fuzz.trimf(eco_level.universe, [3.25, 4.0, 5.0])
# Rules
rule1 = ctrl.Rule(batt_percent['Low_battery'] &
(~temp['High_temperature']),
eco_level['Critical'])
rule2 = ctrl.Rule(batt_percent['Low_battery'] &
temp['High_temperature'] &
cloud_cover['High_clouds'],
eco_level['Critical'])
rule3 = ctrl.Rule(batt_percent['Low_battery'] &
temp['High_temperature'] &
(~cloud_cover['High_clouds']),
eco_level['Alert'])
rule4 = ctrl.Rule(batt_percent['Medium_battery'] &
temp['Low_temperature'] &
(~cloud_cover['High_clouds']),
eco_level['Alert'])
rule5 = ctrl.Rule(batt_percent['Medium_battery'] &
temp['Low_temperature'] &
cloud_cover['High_clouds'],
eco_level['Critical'])
rule6 = ctrl.Rule(batt_percent['Medium_battery'] &
(~temp['Low_temperature']) &
(~cloud_cover['High_clouds']),
eco_level['Normal'])
rule7 = ctrl.Rule(batt_percent['Medium_battery'] &
(~temp['Low_temperature']) &
cloud_cover['High_clouds'],
eco_level['Alert'])
rule8 = ctrl.Rule(batt_percent['High_battery'] &
temp['Low_temperature'] &
(~cloud_cover['High_clouds']),
eco_level['Normal'])
rule9 = ctrl.Rule(batt_percent['High_battery'] &
temp['Low_temperature'] &
cloud_cover['High_clouds'],
eco_level['Alert'])
rule10 = ctrl.Rule(batt_percent['High_battery'] &
(~temp['Low_temperature']) &
(~cloud_cover['High_clouds']),
eco_level['Economyless'])
rule11 = ctrl.Rule(batt_percent['High_battery'] &
(~temp['Low_temperature']) &
cloud_cover['High_clouds'],
eco_level['Normal'])
eco_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4,
rule5, rule6, rule7, rule8,
rule9, rule10, rule11])
eco_mode = ctrl.ControlSystemSimulation(eco_ctrl)
# Pass inputs to the ControlSystem using Antecedent labels with Pythonic API
# Note: if you like passing many inputs all at once, use .inputs(dict_of_data)
eco_mode.input['Temperature'] = Weather.tempc
eco_mode.input['Cloud_cover'] = Weather.clouds
eco_mode.input['Battery_percentage'] = Battery.batt
# Crunch the numbers
eco_mode.compute()
level = round(eco_mode.output['Economy_level'], 0)
|
kunz07/fyp2017
|
GUI/system_rc.py
|
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.8.0)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x02\xec\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00\x00\x00\x20\x08\x03\x00\x00\x00\x44\xa4\x8a\xc6\
\x00\x00\x00\x03\x73\x42\x49\x54\x08\x08\x08\xdb\xe1\x4f\xe0\x00\
\x00\x00\x09\x70\x48\x59\x73\x00\x00\x00\xdd\x00\x00\x00\xdd\x01\
\x70\x53\xa2\x07\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\x74\
\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\
\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x00\xf6\x50\x4c\x54\
\x45\xff\xff\xff\xb6\xdb\x49\xbf\xdf\x60\xbf\xd5\x55\xc2\xd6\x52\
\xb4\xcb\x4b\xb5\xc9\x4a\xb4\xc7\x44\xc1\xd2\x55\xaa\xc2\x42\xc0\
\xd2\x54\xad\xc2\x47\xb0\xc3\x47\xac\xc0\x46\xc1\xd3\x53\xc1\xd3\
\x54\xc1\xd3\x54\xae\xc0\x44\xb1\xc5\x48\xaa\xbe\x43\xc1\xd3\x55\
\xac\xc0\x45\xc1\xd2\x54\xaa\xbd\x42\xaa\xbd\x42\xb3\xc6\x4b\xc1\
\xd3\x54\xc1\xd3\x54\xa7\xbb\x40\xa7\xba\x3f\xc1\xd3\x54\xc1\xd3\
\x54\xc1\xd3\x54\xa3\xb7\x3c\xa1\xb4\x3b\xa2\xb6\x3c\x34\x49\x5e\
\x37\x4a\x5d\x46\x4f\x5a\x4d\x52\x58\x53\x70\x8a\x5b\x56\x55\x5b\
\x70\x50\x60\x75\x54\x71\x5e\x50\x88\x65\x4b\x9d\x6d\x47\x9d\xb1\
\x38\x9e\xb2\x39\xa4\x8f\x3e\xa9\xad\x37\xaa\x71\x44\xab\x96\x43\
\xb3\xc6\x49\xb4\x86\x3e\xb6\xc9\x4c\xb7\xc9\x4c\xbb\x77\x40\xbc\
\x93\x6b\xc0\xc2\x49\xc0\xd1\x59\xc1\xbe\x47\xc1\xd3\x54\xc2\xd3\
\x5b\xc6\xc3\x4a\xd4\x9d\x34\xda\x9b\x34\xda\xe2\xaa\xdf\xa0\x37\
\xdf\xa0\x38\xe0\x83\x38\xe1\x9e\x37\xe1\xa0\x3e\xe2\x9e\x37\xe3\
\xa2\x40\xe6\xa5\x53\xe9\xbd\x79\xee\x88\x35\xf0\xa6\x5a\xf3\x8a\
\x34\xff\x8e\x31\xff\xa6\x6a\x88\xfb\xb7\x60\x00\x00\x00\x24\x74\
\x52\x4e\x53\x00\x07\x08\x18\x19\x22\x26\x29\x2d\x36\x49\x4b\x6b\
\x75\x84\x97\x98\xb3\xb8\xbb\xc1\xc5\xc8\xcc\xce\xd4\xda\xe3\xec\
\xed\xf2\xf3\xf5\xfa\xfc\xfd\x76\x5f\x96\x6e\x00\x00\x01\x38\x49\
\x44\x41\x54\x38\xcb\x75\xd3\xd9\x42\x83\x30\x10\x05\xd0\x40\xab\
\x56\x54\x40\x45\xd4\x54\xa1\x5a\x71\x57\x70\xa9\x8a\x0b\x2e\x75\
\xab\x56\x1b\xff\xff\x67\x84\x86\x0c\x99\x90\xde\x37\x98\x03\x24\
\x43\x86\x10\x88\x61\xb9\x1e\x0d\x43\xea\xb9\x96\x41\xea\x69\x3a\
\x41\x06\x09\x9c\xa6\x52\x36\xed\x4e\x86\xd2\xb1\x4d\xb9\xde\xf0\
\xb3\x5a\xfc\x46\x55\x6f\xb5\x33\x4d\xda\x2d\x78\x5e\x5b\xcf\x45\
\xf9\x0e\xd3\xcf\x26\xc4\xe7\xeb\xb0\xa5\x5b\x8f\xfd\xfe\xbd\x74\
\x69\x8f\xf7\x07\xeb\x7f\xfa\x1d\x7c\x0d\x87\x9f\x83\x8f\x07\xd8\
\x4b\xb1\x5b\x07\xfc\xdb\x1f\x63\x69\xca\x18\x7b\xe9\x89\x5b\x4e\
\xde\xbf\xaa\x3f\xaf\x39\x18\x8d\x0a\x10\x0b\x11\x18\xc4\xaa\xbe\
\x78\xb4\xbf\xc3\x73\x18\x83\xb0\x88\xab\x07\x42\xb8\xc4\xc3\x20\
\x12\xa0\x14\x1e\xa1\x18\x1c\x00\xe0\x82\x92\x10\x83\x93\x0a\x8c\
\x45\xa8\x82\xf4\x22\x02\x50\x88\x50\xfd\xc4\xcf\x7b\xf5\x86\x42\
\x50\x65\x91\xd1\xde\xa9\x0c\xe2\x9e\x57\xdb\xe6\x31\x02\xf1\x52\
\xad\x51\xbb\x18\x2c\xc8\xad\x46\x8d\xe2\xe9\x1a\xf2\xcf\xd2\x80\
\x15\xf4\xbb\x2f\x6f\xaf\x78\xce\x44\x3d\x99\x41\x07\xe6\xee\xfb\
\x99\xe7\x5c\x80\x65\xe5\xc8\xdd\x24\x31\xca\x86\xa9\x1e\x5a\x2c\
\xb6\xa6\xea\xc7\x5e\x16\xdb\x73\xba\xc1\xb9\x06\xb1\x39\xad\x1f\
\xbd\x52\x24\x8b\xe6\xa4\xe1\x2d\x44\x77\x75\x56\x33\xdf\x62\xfc\
\xd7\xd7\xe6\xa5\xf1\xff\x07\x4f\x35\xa6\x95\x72\x9f\xb6\xbd\x00\
\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
\x00\x00\x04\x73\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00\x00\x00\x20\x08\x03\x00\x00\x00\x44\xa4\x8a\xc6\
\x00\x00\x00\x03\x73\x42\x49\x54\x08\x08\x08\xdb\xe1\x4f\xe0\x00\
\x00\x00\x09\x70\x48\x59\x73\x00\x00\x00\xf0\x00\x00\x00\xf0\x01\
\xeb\x4b\xee\x00\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\x74\
\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\
\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x01\xda\x50\x4c\x54\
\x45\xff\xff\xff\x00\xff\x80\x00\xaa\xaa\x00\xbf\x80\x40\xbf\x80\
\x00\xaa\x80\x24\xb6\x6d\x24\xb6\x92\x1c\xaa\x8e\x1a\xb3\x80\x24\
\xc8\x80\x28\xbc\x86\x0d\xb3\x80\x0c\x97\x74\x17\xae\x74\x23\xae\
\x80\x23\xc5\x80\x0b\x9b\x7a\x21\xb1\x7a\x21\xbc\x85\x20\xaa\x80\
\x20\xbf\x80\x0a\x99\x7a\x1f\xad\x85\x09\x97\x7b\x1b\xad\x80\x18\
\xaf\x80\x1d\xa8\x7c\x1c\xac\x7c\x20\xbf\x80\x19\xb4\x83\x18\xad\
\x7d\x17\xac\x7d\x0e\x9b\x7b\x24\xbf\x80\x24\xbf\x80\x23\xc1\x80\
\x17\xad\x7c\x24\xc1\x80\x24\xc2\x81\x10\x9e\x7b\x0c\x9b\x79\x0c\
\x9a\x7a\x17\xab\x7d\x17\xad\x7d\x19\xaf\x7d\x1a\xb1\x7d\x22\xc1\
\x82\x16\xab\x7c\x19\xb0\x7e\x17\xab\x7c\x17\xab\x7b\x22\xc2\x82\
\x17\xae\x7c\x0d\x9a\x78\x17\xac\x7d\x24\xc2\x81\x0c\x9b\x78\x1b\
\xb1\x7d\x0e\x9b\x7a\x24\xc1\x81\x23\xc2\x80\x1a\xb3\x7e\x1a\xb0\
\x7e\x23\xc2\x81\x23\xc1\x80\x24\xc2\x81\x16\xab\x7d\x15\xa9\x7c\
\x23\xc1\x81\x16\xa9\x7c\x16\xa7\x7b\x16\xa9\x7c\x15\xa8\x7c\x22\
\xc0\x82\x16\xaa\x7b\x23\xc1\x81\x15\xaa\x7c\x1a\xb3\x7d\x14\xa7\
\x7b\x0f\x9e\x7a\x14\xa8\x7b\x14\xa8\x7c\x23\xc2\x82\x22\xc1\x81\
\x14\xa7\x7c\x1c\xb4\x7e\x14\xa7\x7c\x0d\x9c\x79\x22\xc1\x81\x24\
\xc1\x81\x14\xa6\x7b\x23\xc1\x81\x15\xa8\x7b\x15\xa8\x7c\x13\xa5\
\x7b\x13\xa6\x7b\x1d\xb6\x80\x0d\x9b\x79\x13\xa5\x7b\x23\xc0\x81\
\x0d\x9b\x79\x0f\x9f\x7a\x13\xa6\x7b\x1d\xb7\x7f\x22\xc1\x81\x1d\
\xb7\x7f\x23\xc2\x81\x12\xa4\x7c\x12\xa5\x7b\x23\xc1\x81\x12\xa4\
\x7a\x1d\xb8\x7f\x23\xc1\x81\x23\xc1\x81\x12\xa4\x7a\x13\xa4\x7a\
\x1b\xb2\x7e\x12\xa3\x7b\x23\xc1\x81\x11\xa2\x7a\x12\xa3\x7b\x12\
\xa5\x7b\x11\xa3\x7b\x11\xa3\x7a\x11\xa2\x7b\x23\xc1\x81\x23\xc1\
\x81\x23\xc1\x81\x1b\xb5\x7e\x1f\xbb\x80\x22\xc1\x81\x11\xa1\x7b\
\x1f\xbb\x80\x11\xa1\x7a\x11\xa1\x7a\x10\xa0\x7a\x10\xa1\x7a\x0f\
\x9f\x79\x0f\xa0\x7a\x0f\xa0\x7a\x0f\x9f\x79\x0f\x9e\x7a\x10\xa1\
\x7a\x0e\x9e\x79\x0f\x9e\x79\x0f\x9f\x79\x22\xbf\x81\x0d\x9b\x79\
\x0d\x9c\x79\x0e\x9c\x79\x0e\x9d\x79\x14\xa7\x7b\x18\xaf\x7d\x20\
\xbb\x80\x22\xc0\x81\x23\xc0\x81\x23\xc1\x81\xcf\x85\xa9\x44\x00\
\x00\x00\x94\x74\x52\x4e\x53\x00\x02\x03\x04\x04\x06\x07\x07\x09\
\x0a\x0e\x13\x14\x16\x16\x16\x16\x17\x17\x17\x18\x18\x19\x19\x1b\
\x1c\x20\x23\x25\x28\x29\x35\x37\x38\x38\x40\x42\x44\x46\x47\x4f\
\x52\x58\x58\x5a\x5c\x62\x62\x67\x67\x6d\x70\x70\x71\x77\x78\x79\
\x7b\x7c\x80\x80\x89\x8c\x92\x92\x93\x96\x97\x9e\xa0\xa3\xa6\xa6\
\xa8\xab\xb0\xb8\xb9\xb9\xbd\xbe\xbe\xbf\xbf\xc1\xc2\xc2\xc3\xc8\
\xc8\xc9\xcb\xcb\xd1\xd2\xd5\xd5\xd6\xd7\xd8\xd8\xd9\xd9\xd9\xdb\
\xde\xdf\xe0\xe1\xe2\xe2\xe3\xe3\xe3\xe4\xe5\xe5\xe5\xe6\xe9\xec\
\xec\xed\xef\xf0\xf1\xf1\xf2\xf3\xf4\xf4\xf4\xf5\xf5\xf6\xf7\xf8\
\xf8\xfa\xfa\xfb\xfc\xfd\xfd\xfe\xfe\xfe\xfe\x79\x25\xf4\x1b\x00\
\x00\x01\x6b\x49\x44\x41\x54\x38\x4f\x7d\x8e\xf5\x5b\x02\x41\x10\
\x86\x07\x0c\x6c\xec\xee\xee\xc0\x56\xec\xee\xee\xee\xee\xee\x06\
\x95\x10\x65\x05\x6b\xff\x57\x39\xd9\xbd\x63\x1f\x38\xbf\x1f\xee\
\x66\xe6\x7d\xe7\xe6\x00\xf8\x48\x13\x2a\x5a\x47\x0b\x40\x2c\x41\
\xd5\x47\xd8\x12\xa5\x08\x96\x95\x5c\x61\xfc\x8f\xe0\x3b\x82\xb1\
\xbd\x50\xe8\x42\xab\xa8\x15\xec\x40\x28\xfa\x5a\x75\x22\xfb\x3b\
\xd8\x81\x50\xfa\x81\xf1\xb2\x84\xab\x9c\xfb\x05\x2e\x08\xe5\xe8\
\x26\xeb\x16\xcf\x70\x86\xd2\x86\xf3\x42\xda\x70\x77\x0c\x44\x3e\
\x18\x07\x01\x02\xee\x04\xbc\xd6\x10\x0f\x76\xa9\xe1\xf1\x6e\x22\
\x03\xbc\x0f\xb2\xb9\x97\xec\x9a\xf2\x76\x4f\x86\xfb\x2d\x7e\x1b\
\x39\x23\x85\xf2\x4d\x0f\x86\x07\xcf\x7e\x6e\xff\x70\x06\x7f\x21\
\x99\xe1\xa1\x0b\xa6\x4e\xa8\xc4\x16\xa3\x8f\xf0\x71\x86\x43\x5c\
\x7a\xaa\xe5\x99\x57\x55\x06\xf3\x44\xa8\x05\x91\x5c\x12\x21\x47\
\x4c\x78\x31\x9b\x4d\xa6\x77\x84\xea\xd9\x71\x9d\xc1\x1a\x1d\x3c\
\x21\x6b\xa6\x58\x61\x9a\x8c\x1f\xe1\x94\x54\xf7\xac\xa0\x22\xe3\
\x63\x98\x24\x15\xca\xb7\xe5\x0a\x3a\x1d\x83\x62\x5a\x6a\x43\x04\
\xee\xaf\xa1\xd3\x5c\x70\x7f\xa3\xf5\x3e\x6f\x78\xad\xd3\x99\x5e\
\x0a\x30\x41\x1b\xa4\x25\x57\x14\xfc\x3e\x1a\xb0\xb4\xd1\x06\xbe\
\x45\xaa\xa5\x96\xe6\x39\x95\xd0\xeb\x03\xb9\x85\x0e\x24\x9a\xa6\
\xbf\x2f\xba\x9d\x89\xf1\x43\xa9\xf5\x66\x84\x70\x93\x89\x5a\x4e\
\xff\x3a\xc9\xa1\xa1\x8e\x05\x3e\xe1\x27\xf6\x7c\x4f\x0e\x36\x71\
\x6d\x7b\x65\xb1\xbe\x51\x02\x6c\xc2\x86\x74\x02\xd6\x76\xf9\x80\
\x83\x64\xf6\x6c\x9c\x3f\x6b\x2e\xb6\x7a\x33\x6c\x86\xbf\x1a\x97\
\x1f\xf1\x41\xea\xba\xd5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\
\x60\x82\
\x00\x00\x03\x5c\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00\x00\x00\x20\x08\x03\x00\x00\x00\x44\xa4\x8a\xc6\
\x00\x00\x00\x03\x73\x42\x49\x54\x08\x08\x08\xdb\xe1\x4f\xe0\x00\
\x00\x00\x09\x70\x48\x59\x73\x00\x00\x00\xdd\x00\x00\x00\xdd\x01\
\x70\x53\xa2\x07\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\x74\
\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\
\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x01\x47\x50\x4c\x54\
\x45\xff\xff\xff\xff\x92\x24\xff\x80\x40\xff\x8a\x35\xff\x8f\x33\
\xf7\x83\x2e\xf2\x83\x2e\xf9\x80\x31\xff\x8e\x33\xf5\x82\x2d\xf8\
\x81\x2f\xff\x8f\x31\xf8\x83\x2c\xf6\x82\x2b\xff\x8f\x30\xff\x8e\
\x31\xff\x8f\x31\xf9\x85\x2d\xf5\x80\x2a\xf4\x7f\x2a\xff\x8d\x31\
\xf6\x80\x2a\xff\x8e\x30\xf4\x7e\x29\xf3\x7c\x28\xff\x8e\x31\xfe\
\x8c\x31\xff\x8e\x31\xf2\x7c\x28\xf3\x7b\x28\xf2\x7b\x28\xff\x8e\
\x32\xff\x8e\x31\xff\x8e\x31\xf0\x78\x27\xef\x76\x26\xf0\x78\x26\
\xf0\x78\x27\xee\x75\x26\x03\x62\x8a\x03\x63\x8b\x05\x64\x8c\x05\
\x7a\xac\x06\x84\xba\x13\x83\xb2\x15\x89\xbb\x16\x6a\x8c\x19\x84\
\xb3\x1d\x8d\xbc\x2e\x83\xa2\x30\x82\x9f\x30\x94\xbf\x3d\x82\x98\
\x44\x6f\x79\x46\x80\x91\x48\x75\x81\x4b\x81\x8f\x5b\x7e\x83\x5e\
\x82\x85\x5f\xa9\xc8\x61\x82\x83\x63\x82\x82\x69\x82\x7e\x6f\xa6\
\xbd\x7d\x83\x73\x81\xb1\xc5\x89\xb4\xc6\x8d\xbe\xd4\x8f\x71\x55\
\x9b\x7e\x5d\x9d\x84\x61\xaf\x85\x58\xbf\x74\x3d\xbf\x87\x50\xc1\
\x87\x4f\xc6\xa9\x8e\xcd\xb9\xa8\xce\x88\x49\xd0\x88\x48\xe5\x74\
\x29\xe5\x8a\x3e\xe8\x8c\x3d\xeb\xf3\xf6\xed\x74\x25\xed\x75\x25\
\xed\x75\x27\xee\x75\x25\xf1\x7a\x28\xf2\x9d\x65\xf2\xf7\xf9\xf5\
\xac\x7b\xf5\xaf\x82\xf8\xc5\xa3\xf9\xfb\xfc\xfa\x87\x2e\xfa\x8c\
\x37\xfa\xd6\xbe\xfb\x97\x49\xfb\xa6\x66\xfb\xb9\x88\xfb\xcb\xa9\
\xfd\x8d\x31\xfd\x94\x3e\xfe\x8d\x30\xfe\x8e\x32\xfe\xf5\xf0\xfe\
\xfa\xf6\xff\x8e\x31\xff\xff\xff\xba\xbe\x31\x70\x00\x00\x00\x27\
\x74\x52\x4e\x53\x00\x07\x08\x18\x19\x21\x27\x2a\x2d\x33\x47\x49\
\x69\x76\x84\x97\x98\xb0\xb1\xbd\xc1\xc3\xc8\xcb\xd0\xda\xdc\xe3\
\xe9\xec\xed\xf2\xf3\xf5\xfa\xfc\xfd\xfd\xfe\xd9\x78\x62\x18\x00\
\x00\x01\x54\x49\x44\x41\x54\x38\xcb\x7d\x93\xd7\x42\x84\x30\x10\
\x45\x03\xbb\xea\x2a\x0a\xa8\x88\xe2\xaa\x80\x5d\x63\xef\xbd\xf7\
\xae\xd8\x7b\x6f\xe1\xff\x9f\x0d\x90\x40\x36\x04\xcf\xe3\xdc\x43\
\x48\x26\x19\x00\x62\x24\x45\x37\x2c\xc7\xb1\x0c\x5d\x91\x40\x9a\
\xbc\x66\xa3\x18\x5b\xcb\x73\xb1\xac\xba\xa8\x04\x57\x95\xd9\x3c\
\x67\xa2\x14\x66\x2e\xc9\x0b\x45\x24\xa0\x58\x88\xbf\x17\xe6\xd8\
\x20\x6b\xc8\x26\xca\xc0\x8c\xf6\xa1\xa2\x4c\xd4\xf0\x7c\x6e\xb6\
\xe0\x06\xa7\xd5\xd0\x3f\x68\xb8\x7f\x36\x5b\x38\xd9\x3b\x45\xe8\
\xf5\xfd\xed\x93\x76\x4c\x02\x0a\x13\x1f\x4d\x40\x08\x47\xf7\x7d\
\xdf\xff\x79\x22\x25\x05\xe8\x49\x7e\x38\x80\xf3\xf1\xf5\x33\x2c\
\xf8\xb7\x8f\x51\x4d\x07\x46\x22\x8c\xe1\x7c\xe4\xc1\x0f\xf9\x7d\
\x7e\x09\x6b\x06\xb0\x48\xba\xbb\xb2\x80\x73\x38\xef\x53\xee\xc3\
\x35\x2c\xe0\x44\xf9\x12\x8c\x18\xbc\xa1\xc2\xdd\x65\x60\x38\x44\
\xd8\x86\x94\xe1\xe5\x55\xcc\xda\xc1\xf5\x85\x17\x18\x0e\xf9\xc5\
\x62\x2c\xc0\xfe\xde\x1e\xcc\x90\x87\xc1\x86\x45\x36\x39\x07\x79\
\x63\x27\x32\x0c\x72\xcc\x2d\xc8\x19\x7d\xc7\x5e\x68\xd4\x92\x46\
\x7d\xcf\x70\xc6\xa4\x17\x51\x43\x5b\xfd\xb1\x39\x3b\x95\x30\xbd\
\x41\xf2\x2e\x29\xbe\xac\xaf\x2b\x4f\x40\x03\x73\xdd\x22\xe3\xbc\
\x9c\x7d\x30\x02\xa3\xbe\xf4\xc9\xa5\x8c\x56\x99\x7b\xb4\x9c\xd1\
\x5e\x96\x7a\xf6\x25\x46\x47\x95\x60\x70\x18\xa3\xad\x42\x38\x7a\
\xd4\xe8\xae\x93\x33\x86\x37\x34\x3a\x9b\x2a\x05\xf3\x4d\xc6\xbf\
\xb9\xa5\xb1\x9a\x19\xff\x3f\x73\xaa\x0a\x6a\x7e\x4f\x3a\xa7\x00\
\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
\x00\x00\x02\x9c\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00\x00\x00\x20\x08\x03\x00\x00\x00\x44\xa4\x8a\xc6\
\x00\x00\x00\x03\x73\x42\x49\x54\x08\x08\x08\xdb\xe1\x4f\xe0\x00\
\x00\x00\x09\x70\x48\x59\x73\x00\x00\x00\xe1\x00\x00\x00\xe1\x01\
\x70\x18\x1c\x2e\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\x74\
\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\
\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x00\xf6\x50\x4c\x54\
\x45\xff\xff\xff\xff\xcc\x66\xef\xc8\x5f\xef\xc6\x5e\xcd\x55\x4c\
\xce\x57\x4e\xd8\x53\x49\xd8\x76\x6e\xd9\x80\x78\xda\x5d\x53\xdd\
\xb8\x56\xde\x55\x4b\xe1\x64\x5a\xe2\x57\x4c\xe2\x58\x4d\xe3\x5f\
\x54\xe3\xbd\x59\xe5\x68\x5d\xe5\x68\x5e\xe5\x6a\x60\xe5\x6e\x64\
\xe5\x73\x6a\xe6\x73\x6a\xe6\x74\x6b\xe6\x75\x6c\xe6\x7e\x76\xe7\
\x8a\x82\xe8\x8c\x84\xe8\x8d\x86\xe9\x94\x8c\xe9\xc2\x5b\xeb\xb2\
\xac\xeb\xc4\x5c\xed\xc0\xbb\xed\xc5\x5d\xee\xc6\x5e\xef\xc7\x5e\
\xef\xc9\x65\xef\xc9\x66\xef\xca\x68\xef\xcb\x6b\xef\xcc\x6e\xef\
\xcc\x70\xef\xd4\xd0\xf0\xcf\x78\xf0\xcf\x79\xf0\xcf\x7a\xf0\xcf\
\x7b\xf0\xd0\x7c\xf0\xd0\x7d\xf0\xd1\x82\xf0\xd2\x82\xf0\xd5\x8d\
\xf0\xd6\x91\xf0\xda\x9e\xf0\xda\xd5\xf0\xdb\xa2\xf0\xe2\xdf\xf0\
\xe4\xe0\xf1\xcd\x6f\xf1\xde\xac\xf1\xe2\xba\xf1\xe2\xbb\xf1\xe3\
\xbd\xf1\xe3\xbf\xf1\xe3\xe0\xf1\xe8\xd0\xf1\xe8\xd1\xf1\xe8\xe6\
\xf1\xe9\xe6\xf1\xea\xd7\xf1\xea\xe6\xf1\xec\xea\xf2\xe8\xe0\xf2\
\xeb\xe2\xf2\xeb\xe9\xf2\xee\xeb\xf2\xf0\xec\xf2\xf1\xed\xf2\xf1\
\xef\xf3\xd7\x8c\xf4\xdb\x98\x62\x86\x9b\xc5\x00\x00\x00\x04\x74\
\x52\x4e\x53\x00\x05\x61\xcb\xc5\x08\xe5\xaf\x00\x00\x01\x08\x49\
\x44\x41\x54\x38\xcb\x9d\xd3\x67\x53\xc2\x40\x10\x06\xe0\x90\xa8\
\x40\x34\x10\x62\x45\x20\xb4\x28\x0a\x22\x2a\x45\xe9\xa1\x17\x85\
\x83\xff\xff\x67\xb8\x62\x32\xe3\xdc\x2e\x30\xbe\x1f\x32\xb9\x9b\
\x27\xbb\xfb\x21\xab\x28\x34\x01\x55\x73\xa4\x68\x6a\x40\xf1\xa2\
\x3a\x60\x54\x1f\x00\xdf\xb7\xdb\xb4\x86\x0f\xe8\xc5\x66\xc3\xef\
\x8b\x9d\x4e\x91\xbf\x6c\xb7\xf4\x21\x83\xea\x9a\x90\x75\xd5\xab\
\xf0\x07\x88\xb8\x84\xc6\xf5\x8f\x32\x58\x31\xb0\xda\x03\x08\x0f\
\x06\x32\xba\x4e\x42\xa7\x27\x41\xa2\xeb\x19\x10\xe4\x6d\x9b\x9c\
\x9f\x85\x2f\x88\x6d\xe7\xd1\x16\x86\x61\x59\x68\x0b\x56\x81\x03\
\xac\x02\x9b\x81\x03\x6c\x86\x83\x2d\x0e\x82\x9c\x69\x0a\x60\x9a\
\xb9\xff\x81\x23\x66\x78\x11\xa0\x8c\x82\xee\x9c\x81\x71\x1f\x03\
\xef\xb3\x38\x03\x57\xad\x0f\x04\x0c\x13\x06\x03\xd6\xed\x14\x06\
\x0f\x3f\x51\x01\x62\xdf\x05\x10\xbc\x96\x0c\x01\xac\x6c\x05\xae\
\x30\x89\xfc\x82\xe6\x23\x3c\xc3\xe8\x5e\x80\x9b\x11\x32\xe4\xdb\
\xe0\x9a\x81\xcb\xcf\x0a\x00\xf8\x6f\x5f\x5f\xa6\x93\x77\xa9\x45\
\xcd\x3b\xcb\x7b\xf1\xf4\xd5\x73\x1b\xcf\x8e\x04\x34\x78\x37\xb5\
\xe3\x97\x77\xdf\xfa\xef\x00\xfe\x4f\x6c\xf6\x31\x97\x85\x05\x00\
\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
"
qt_resource_name = b"\
\x00\x05\
\x00\x6f\xa6\x53\
\x00\x69\
\x00\x63\x00\x6f\x00\x6e\x00\x73\
\x00\x05\
\x00\x4f\xa6\x53\
\x00\x49\
\x00\x63\x00\x6f\x00\x6e\x00\x73\
\x00\x0b\
\x0c\x4d\x40\x07\
\x00\x62\
\x00\x61\x00\x74\x00\x74\x00\x65\x00\x72\x00\x79\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x0a\
\x08\xab\x7a\x07\
\x00\x72\
\x00\x6f\x00\x74\x00\x61\x00\x74\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x0a\
\x0b\xb9\x11\x87\
\x00\x63\
\x00\x6c\x00\x6f\x00\x75\x00\x64\x00\x79\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x0f\
\x03\xec\xfb\x67\
\x00\x74\
\x00\x68\x00\x65\x00\x72\x00\x6d\x00\x6f\x00\x6d\x00\x65\x00\x74\x00\x65\x00\x72\x00\x2e\x00\x70\x00\x6e\x00\x67\
"
qt_resource_struct = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\
\x00\x00\x00\x10\x00\x02\x00\x00\x00\x04\x00\x00\x00\x03\
\x00\x00\x00\x70\x00\x00\x00\x00\x00\x01\x00\x00\x0a\xc7\
\x00\x00\x00\x3c\x00\x00\x00\x00\x00\x01\x00\x00\x02\xf0\
\x00\x00\x00\x56\x00\x00\x00\x00\x00\x01\x00\x00\x07\x67\
\x00\x00\x00\x20\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
"
def qInitResources():
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()
|
kunz07/fyp2017
|
Ubidots-Forecast.py
|
<filename>Ubidots-Forecast.py
# FYP2017
# Program to send average forecastof temperature and cloud cover to ThingSpeak
# Author: <NAME>
# License: Public Domain
from forecastiopy import *
import datetime
import sys
from ubidots import ApiClient
import time
hour = 3600
f = open('Ubidots_APIkey.txt', 'r')
apikey = f.readline().strip()
f.close()
api = ApiClient(token = apikey)
try:
temp = api.get_variable("58d76383762542260cf36d8f")
cloud_cover = api.get_variable("58d76394762542260a851a05")
except ValueError:
print('Unable to obtain variable')
def sendForecast():
f = open('DS_APIkey.txt','r')
apikey = f.read()
f.close()
Bangalore = [12.9716, 77.5946]
fio = ForecastIO.ForecastIO(apikey,
units=ForecastIO.ForecastIO.UNITS_SI,
lang=ForecastIO.ForecastIO.LANG_ENGLISH,
latitude=Bangalore[0], longitude=Bangalore[1],
)
tempc = 0
clouds = 0
if fio.has_hourly() is True:
hourly = FIOHourly.FIOHourly(fio)
for hour in range(0, 48):
tempc = tempc + float(str(hourly.get_hour(hour)['temperature']))
clouds = clouds + float(str(hourly.get_hour(hour)['cloudCover']))
else:
print('No Hourly data')
tempc = round(tempc / 48, 2)
clouds = round(clouds / 48, 2)
try:
temp.save_value({'value': tempc})
cloud_cover.save_value({'value': clouds})
print('Value',tempc,'and',clouds, 'sent')
time.sleep(2)
except:
print('Value not sent')
return(tempc, clouds)
if __name__ == "__main__":
while True:
temp, clouds = sendForecast()
time.sleep(5)
|
kunz07/fyp2017
|
Fuzzytest.py
|
<filename>Fuzzytest.py
# FYP2017
# Program to determine economy level of system using fuzzy logic (TESTING)
# Author: <NAME>
# License: Public Domain
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
# New Antecedent/Consequent objects hold universe variables and membership
# functions
batt_percent = ctrl.Antecedent(np.arange(0, 101, 1), 'Battery_percentage')
temp = ctrl.Antecedent(np.arange(15, 35, 1), 'Temperature')
cloud_cover = ctrl.Antecedent(np.arange(0, 1, 0.01), 'Cloud_cover')
eco_level = ctrl.Consequent(np.arange(1, 4, 0.01), 'Economy_level')
# Battery membership function population
batt_percent['Low_battery'] = fuzz.trapmf(batt_percent.universe, [0, 0, 20, 30])
batt_percent['Medium_battery'] = fuzz.trapmf(batt_percent.universe, [20, 25, 75, 80])
batt_percent['High_battery'] = fuzz.trapmf(batt_percent.universe, [75, 80, 100, 100])
# Temperature membership function population
temp['Low_temperature'] = fuzz.trapmf(temp.universe, [0, 0, 20, 22])
temp['Medium_temperature'] = fuzz.trapmf(temp.universe, [20, 23, 27, 30])
temp['High_temperature'] = fuzz.trapmf(temp.universe, [28 , 30, 35, 35])
# Cloud_cover membership function population
cloud_cover['Minimum_clouds'] = fuzz.trapmf(cloud_cover.universe, [0, 0, 0.20, 0.25])
cloud_cover['Medium_clouds'] = fuzz.trapmf(cloud_cover.universe, [0.20, 0.25, 0.65, 0.70])
cloud_cover['High_clouds'] = fuzz.trapmf(cloud_cover.universe, [0.65, 0.70, 1, 1])
# Custom membership functions can be built interactively with a familiar,
# Pythonic API
eco_level['Critical'] = fuzz.trimf(eco_level.universe, [0, 1.0, 2.0])
eco_level['Alert'] = fuzz.trimf(eco_level.universe, [1.75, 2.25, 2.75])
eco_level['Normal'] = fuzz.trimf(eco_level.universe, [2.5, 3.0, 3.5])
eco_level['Economyless'] = fuzz.trimf(eco_level.universe, [3.25, 4.0, 5.0])
batt_percent.view()
temp.view()
cloud_cover.view()
eco_level.view()
# Rules
rule1 = ctrl.Rule(batt_percent['Low_battery'] &
(~temp['High_temperature']),
eco_level['Critical'])
rule2 = ctrl.Rule(batt_percent['Low_battery'] &
temp['High_temperature'] &
cloud_cover['High_clouds'],
eco_level['Critical'])
rule3 = ctrl.Rule(batt_percent['Low_battery'] &
temp['High_temperature'] &
(~cloud_cover['High_clouds']),
eco_level['Alert'])
rule4 = ctrl.Rule(batt_percent['Medium_battery'] &
temp['Low_temperature'] &
(~cloud_cover['High_clouds']),
eco_level['Alert'])
rule5 = ctrl.Rule(batt_percent['Medium_battery'] &
temp['Low_temperature'] &
cloud_cover['High_clouds'],
eco_level['Critical'])
rule6 = ctrl.Rule(batt_percent['Medium_battery'] &
(~temp['Low_temperature']) &
(~cloud_cover['High_clouds']),
eco_level['Normal'])
rule7 = ctrl.Rule(batt_percent['Medium_battery'] &
(~temp['Low_temperature']) &
cloud_cover['High_clouds'],
eco_level['Alert'])
rule8 = ctrl.Rule(batt_percent['High_battery'] &
temp['Low_temperature'] &
(~cloud_cover['High_clouds']),
eco_level['Normal'])
rule9 = ctrl.Rule(batt_percent['High_battery'] &
temp['Low_temperature'] &
cloud_cover['High_clouds'],
eco_level['Alert'])
rule10 = ctrl.Rule(batt_percent['High_battery'] &
(~temp['Low_temperature']) &
(~cloud_cover['High_clouds']),
eco_level['Economyless'])
rule11 = ctrl.Rule(batt_percent['High_battery'] &
(~temp['Low_temperature']) &
cloud_cover['High_clouds'],
eco_level['Normal'])
eco_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4,
rule5, rule6, rule7, rule8,
rule9, rule10, rule11])
eco_mode = ctrl.ControlSystemSimulation(eco_ctrl)
# Pass inputs to the ControlSystem using Antecedent labels with Pythonic API
# Note: if you like passing many inputs all at once, use .inputs(dict_of_data)
eco_mode.input['Temperature'] = 50
eco_mode.input['Cloud_cover'] = 0.5
eco_mode.input['Battery_percentage'] = 50
# Crunch the numbers
eco_mode.compute()
print (eco_mode.output['Economy_level'])
eco_level.view(sim=eco_mode)
|
kunz07/fyp2017
|
test.py
|
<reponame>kunz07/fyp2017
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
import pyqtgraph as pg
data = np.array([
[0.0, 0.5, 0.0],
[0.5, 1.0, 0.5],
[0.0, 0.5, 0.0]
])
pg.plot(data)
|
kunz07/fyp2017
|
WeatherIOT.py
|
<gh_stars>1-10
# FYP2017
# Program to send average forecastof temperature and cloud cover to ThingSpeak
# Author: <NAME>
# License: Public Domain
from forecastiopy import *
import datetime
import sys
import urllib.request
import urllib.parse
import time
hour = 3600
def sendForecast():
f = open('DS_APIkey.txt','r')
apikey = f.read()
f.close()
Bangalore = [12.9716, 77.5946]
fio = ForecastIO.ForecastIO(apikey,
units=ForecastIO.ForecastIO.UNITS_SI,
lang=ForecastIO.ForecastIO.LANG_ENGLISH,
latitude=Bangalore[0], longitude=Bangalore[1],
)
tempc = 0
clouds = 0
if fio.has_hourly() is True:
hourly = FIOHourly.FIOHourly(fio)
for hour in range(0, 48):
tempc = tempc + float(str(hourly.get_hour(hour)['temperature']))
clouds = clouds + float(str(hourly.get_hour(hour)['cloudCover']))
else:
print('No Hourly data')
tempc = round(tempc / 48, 2)
clouds = round(clouds / 48, 2)
#Send Data to ThingSpeak
fl = open('TS_APIkey.txt','r')
api_key = fl.read()
params = urllib.parse.urlencode({'key': api_key ,
'field1': tempc ,
'field2': clouds
})
params = params.encode('utf-8')
fh = urllib.request.urlopen("https://api.thingspeak.com/update", data=params)
fh.close()
if __name__ == "__main__":
while True:
sendForecast()
time.sleep(hour * 24)
|
kunz07/fyp2017
|
ZigBee.py
|
# FYP2017
# Program to establish ZigBee communication between raspberry Pi and arduino
# Complete control of HVAC elements based on commands sent from the Pi
# Author: <NAME>
# License: Public Domain
import time
import serial
hour = 3600
PORT = '/dev/ttyUSB1'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
def getSensorData():
ser.close()
ser.open()
ser.write('s'.encode())
time.sleep(2)
response = ser.readline().strip().decode()
hum = 50
temp = 30
print(hum, temp)
return (hum, temp)
def level_1():
h, t = getSensorData()
if (t > 35):
ser.write('c'.encode())
if (t < 15):
ser.write('f'.encode())
if (h < 25):
ser.write('h'.encode())
if (h > 80):
ser.write('e'.encode())
time.sleep(300)
def level_2():
h, t = getSensorData()
if (t > 32):
ser.write('c'.encode())
if (t < 18):
ser.write('f'.encode())
if (h < 30):
ser.write('h'.encode())
if (h > 70):
ser.write('e'.encode())
time.sleep(300)
def level_3():
h, t = getSensorData()
if (t > 30):
ser.write('c'.encode())
if (t < 20):
ser.write('f'.encode())
if (h < 40):
ser.write('h'.encode())
if (h > 60):
ser.write('e'.encode())
time.sleep(300)
def level_4():
h, t = getSensorData()
if (t > 27):
ser.write('c'.encode())
if (t < 22):
ser.write('f'.encode())
if (h < 25):
ser.write('h'.encode())
if (h > 50):
ser.write('e'.encode())
time.sleep(300)
def getLevel():
return 1
if __name__ == "__main__":
level = getLevel()
while True:
if (level == 1):
level_1()
elif (level == 2):
level_2()
elif (level == 3):
level_3()
elif (level == 4):
level_4()
else:
ser.write('x'.encode())
break
|
kunz07/fyp2017
|
Battery.py
|
<filename>Battery.py
# FYP2017
# Program to read battery voltage and display it on OLED
# Author: <NAME>
# License: Public Domain
import time
# OLED modules
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
# Raspberry Pi pin configuration:
RST = 32
# 128x32 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
# Initialize library.
disp.begin()
time.sleep(10)
width = disp.width
height = disp.height
# Clear display.
disp.clear()
disp.display()
image = Image.new('1', (width, height))
# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)
# Load default font.
font = ImageFont.load_default()
# Alternatively load a TTF font. Make sure the .ttf font file is in the same directory as the python script!
# Some other nice fonts to try: http://www.dafont.com/bitmap.php
#font = ImageFont.truetype('Minecraftia.ttf', 8)
# Hardware SPI configuration:
SPI_PORT = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
# Main program loop.
time.sleep(3)
# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)
value = mcp.read_adc(0)
volts = ((value*3.3)) / float(1023) #voltage divider voltage
volts = volts * 5.7 #actual voltage
volts = round(volts,2)
if (volts >=13.6):
batt = 100
print('100% Battery')
draw.text((0, 0), 'Battery percent at: ',font=font, fill = 255)
draw.text((50, 20),str(batt) , font=font, fill = 255)
disp.image(image)
disp.display()
time.sleep(1)
elif (volts > 11.6):
batt = round ((volts - 11.6) * 50,1)
print(batt,'% Battery')
draw.text((10, 0), 'Battery percent at: ',font=font, fill = 255)
draw.text((45, 20),str(batt) , font=font, fill = 255)
disp.image(image)
disp.display()
time.sleep(1)
else:
print('Connection Error')
draw.text((55, 10),':(' , font=font, fill = 255)
disp.image(image)
disp.display()
# Print the ADC values.
# Pause time.
time.sleep(1)
|
kunz07/fyp2017
|
GUI/lockscreen_rc.py
|
<reponame>kunz07/fyp2017
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.8.0)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x04\x31\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00\x00\x00\x20\x08\x03\x00\x00\x00\x44\xa4\x8a\xc6\
\x00\x00\x00\x03\x73\x42\x49\x54\x08\x08\x08\xdb\xe1\x4f\xe0\x00\
\x00\x00\x09\x70\x48\x59\x73\x00\x00\x00\xdd\x00\x00\x00\xdd\x01\
\x70\x53\xa2\x07\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\x74\
\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\
\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x01\xdd\x50\x4c\x54\
\x45\xff\xff\xff\xff\xff\x00\xff\xff\x80\xff\xff\xff\xff\xcc\x66\
\xff\xdb\x49\xff\xbf\x60\xff\xb3\x4d\xff\xd1\x5d\xff\xc4\x4e\xed\
\xed\xed\xff\xb6\x49\xff\xc8\x5b\xdf\xef\xef\xff\xcf\x50\xff\xd2\
\x5a\xf2\xbf\x40\xf4\xbf\x40\xe2\xeb\xeb\xff\xd0\x55\xe4\xed\xed\
\xe5\xe5\xed\xff\xca\x58\xff\xcc\x55\xf8\xb8\x40\xff\xcd\x55\xff\
\xcc\x53\xe7\xe7\xed\xff\xcc\x55\xe3\xe9\xee\xf4\xb8\x41\xff\xce\
\x51\xff\xcc\x53\xf6\xbc\x43\xf6\xba\x41\xff\xce\x55\xf7\xbb\x44\
\xf7\xbc\x43\xf8\xbc\x43\xff\xcd\x55\xe7\xea\xee\xf5\xbd\x42\xe7\
\xea\xee\xf5\xb9\x42\xf6\xbb\x41\xf6\xbb\x41\xf6\xbb\x41\xe5\xea\
\xed\xe6\xe8\xed\xf5\xbc\x41\xf5\xba\x42\xf6\xbb\x42\xff\xce\x54\
\xe7\xe9\xed\xf5\xbb\x42\xff\xce\x54\xf6\xbb\x42\xf6\xbc\x42\xe8\
\xe9\xed\xf6\xbc\x42\xff\xcd\x53\xe5\xe9\xec\xf5\xba\x41\xe6\xe9\
\xec\xff\xce\x54\xe7\xea\xed\xff\xce\x53\xe7\xea\xef\xf6\xbc\x42\
\xff\xce\x54\xf7\xbc\x43\xf7\xbb\x43\xe7\xe9\xed\xe6\xe8\xec\xff\
\xcd\x55\xf7\xbd\x42\xff\xcf\x54\xe7\xe9\xee\xf6\xbb\x43\xff\xce\
\x55\xff\xcd\x55\xe6\xe9\xed\xf6\xbc\x42\xe7\xe9\xee\xe6\xe9\xed\
\xe7\xea\xed\xff\xce\x54\xe7\xe9\xed\xf6\xbc\x42\xe6\xe9\xed\xf6\
\xbb\x42\xf6\xbb\x42\xff\xce\x54\xf7\xbb\x43\xe7\xe9\xed\xe6\xe9\
\xed\xf6\xbb\x42\xf6\xbb\x42\xe8\xeb\xf0\xe8\xea\xee\xe8\xeb\xef\
\xe7\xea\xee\xeb\xed\xf1\xf8\xbe\x45\xf7\xbd\x44\xe7\xea\xee\xeb\
\xee\xf1\xf6\xbb\x43\xe6\xe9\xed\xea\xed\xf0\xf6\xbb\x42\xf7\xbe\
\x44\xf8\xc0\x46\xc6\xca\xce\xd3\xd6\xdb\xda\x44\x53\xdb\x46\x55\
\xdb\x4b\x5a\xdb\x4e\x5c\xdc\x48\x57\xdf\x65\x72\xe6\x93\x9d\xe6\
\x95\x9e\xe6\xe9\xed\xe7\x4f\x5e\xeb\xed\xf1\xeb\xee\xf1\xec\xb9\
\xc0\xec\xbd\xc4\xec\xef\xf2\xed\xc4\xcb\xed\xf0\xf3\xee\xf0\xf3\
\xee\xf1\xf4\xef\xce\xd4\xef\xf1\xf5\xf0\xd6\xdb\xf0\xf2\xf5\xf0\
\xf2\xf6\xf1\xf3\xf7\xf1\xf4\xf7\xf2\xe3\xe7\xf4\xef\xf2\xf4\xf6\
\xf9\xf5\xf5\xf8\xf5\xf6\xf9\xf5\xf7\xfa\xf6\xbb\x42\xf9\xc0\x47\
\xf9\xc1\x48\xf9\xc2\x49\xfa\xc3\x49\xfb\xc5\x4b\xfb\xc6\x4d\xfc\
\xc8\x4e\xfd\xc9\x4f\xfd\xca\x50\xfd\xca\x51\xff\xce\x54\x04\x23\
\x9d\x11\x00\x00\x00\x71\x74\x52\x4e\x53\x00\x01\x02\x02\x05\x07\
\x08\x0a\x0b\x0d\x0e\x0e\x0e\x10\x10\x11\x14\x18\x1a\x1b\x1c\x1d\
\x1d\x1e\x24\x24\x28\x2b\x2d\x2e\x2f\x2f\x37\x39\x3b\x3f\x40\x41\
\x45\x48\x49\x49\x4a\x4d\x52\x53\x56\x62\x64\x66\x68\x6d\x7d\x7e\
\x80\x83\x8b\x8c\x8e\x90\x90\x95\xa0\xa5\xa6\xa8\xa8\xaa\xae\xb1\
\xb6\xb8\xbd\xbe\xbe\xc0\xc3\xc8\xcb\xcd\xd3\xd8\xd8\xdb\xde\xe6\
\xe7\xe8\xe8\xe9\xea\xed\xf0\xf1\xf2\xf5\xf5\xf7\xf8\xfa\xfa\xfb\
\xfb\xfb\xfc\xfd\xfd\xfd\xfe\xfe\xfe\xfe\xfe\x22\xeb\xe2\xf5\x00\
\x00\x01\x49\x49\x44\x41\x54\x38\xcb\x63\x60\x00\x03\x59\x8f\xf8\
\x40\x03\x06\xdc\x40\x24\x2e\xa9\x35\x2d\x13\x8f\x0a\xd3\xd4\xfe\
\x49\x93\xd2\x02\x71\x2b\xb0\xcf\x9a\x34\x69\x52\x67\x0e\x6e\x05\
\x8e\x75\x40\x05\x5d\xd5\x94\x29\xe8\x25\xa4\xa0\xac\x89\x80\x82\
\xe2\x7a\x84\x02\x01\x42\x0a\xa2\xd5\x70\x2b\xe0\xe7\x03\x12\x09\
\xda\x0c\x0c\x2c\xc2\xd8\x15\x98\x87\x49\x32\x30\x48\x30\x30\x30\
\xba\x06\x60\x57\xc0\xe3\xa4\xae\xe8\x16\xe1\x67\xcc\xe6\xa5\x80\
\xa2\xa0\xa8\xa5\xb8\xbe\x10\xe2\x06\xbd\xbc\xfc\x19\x53\x26\xbb\
\xa0\xb9\x01\xa1\x80\x3d\x76\xea\xbc\x79\xf3\x66\x4d\xd6\xc4\xea\
\x48\x39\x3b\x43\xa5\xc9\x73\x80\x0a\xe6\x65\x58\x00\xd9\x98\x0a\
\x54\xdd\xcd\x54\x26\xcf\x05\x29\x48\xb7\x06\xb2\xb1\x86\x03\x77\
\xe2\x74\xa0\xfc\xec\xc9\xba\x38\x03\xca\x68\x72\xc1\xcc\x69\xd9\
\xde\x8c\x38\x14\xb0\xda\x28\xeb\x04\x65\x47\x59\x72\x3a\x48\x61\
\x57\x60\x12\x23\xc3\xc0\x20\xc8\xc0\xc0\xe4\xe3\x8f\x5d\x81\x98\
\x38\x34\x2e\x38\xe4\xf1\x44\x16\x28\x2e\xf0\xc6\xa6\x04\xba\x3c\
\x6f\x64\x23\x50\x41\x77\xb5\x16\xae\xf4\x62\x9b\xd3\xdf\x51\x5c\
\x39\x21\x37\x9c\x19\x87\x82\x90\xda\xbe\xd2\x92\xe2\x86\xae\x6a\
\x69\x1c\x0a\xe2\xdb\xdb\x8a\x6b\xca\xab\xfa\xab\x35\x70\x28\xf0\
\x6d\x9c\x58\x51\x5c\xda\xd1\x5d\x2d\x84\x43\x81\x7e\x66\xcf\xc4\
\xb6\xbe\xfe\x14\x4f\x9c\xa9\xda\x39\xb3\xb1\xbd\x39\x39\x54\x14\
\x77\xba\xd7\xf7\x8d\x0f\xb6\xe2\xc2\x26\x03\x00\x8f\xb4\x8c\xb5\
\x70\xac\xb2\xb2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
\
\x00\x00\x02\x24\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00\x00\x00\x20\x08\x03\x00\x00\x00\x44\xa4\x8a\xc6\
\x00\x00\x00\x03\x73\x42\x49\x54\x08\x08\x08\xdb\xe1\x4f\xe0\x00\
\x00\x00\x09\x70\x48\x59\x73\x00\x00\x07\xa3\x00\x00\x07\xa3\x01\
\x30\x2f\xb2\xc5\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\x74\
\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\
\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x00\xa2\x50\x4c\x54\
\x45\xff\xff\xff\x28\x38\x4d\x28\x37\x4d\x87\x39\x4f\x6b\x39\x4e\
\xfc\x38\x52\xef\xd5\xc9\x78\x38\x4e\x8a\x39\x4f\x94\x39\x4e\xfc\
\x39\x52\xef\xd8\xcd\xcd\x39\x51\xd6\x39\x51\xed\xea\xda\xfc\x39\
\x52\x26\xb9\x9a\x28\x38\x4c\x4f\xc2\xa6\x8c\xca\xb0\x91\xca\xb1\
\x9c\xcb\xb1\x9f\xcb\xb1\xc5\xca\xb0\xca\xca\xae\xcb\xca\xaf\xce\
\xc9\xae\xce\xc9\xaf\xcf\xca\xaf\xcf\xca\xb0\xd0\xcb\xb1\xd1\xcc\
\xb2\xd2\xcd\xb3\xd7\xd2\xba\xd7\xd3\xbb\xd8\xd3\xbc\xd8\xd4\xbc\
\xd9\xd4\xbd\xd9\xd5\xbd\xd9\xd5\xbe\xda\xd5\xbe\xda\xd6\xbf\xdb\
\xd6\xc0\xdb\xd7\xc1\xdc\xd8\xc3\xde\xda\xc5\xe0\xdc\xc8\xe5\xe2\
\xcf\xe6\xe3\xd0\xe7\xe4\xd2\xe9\xe6\xd4\xeb\xe8\xd7\xed\xea\xda\
\xfc\x39\x52\x19\x34\xb7\x9d\x00\x00\x00\x10\x74\x52\x4e\x53\x00\
\x60\x78\xae\xb0\xb5\xbd\xc0\xc2\xc4\xc8\xcc\xd8\xdf\xe8\xe8\x79\
\xe2\xaf\xf9\x00\x00\x00\xd8\x49\x44\x41\x54\x38\x4f\xad\x90\xc9\
\x0e\x82\x40\x10\x05\x01\x51\x16\x95\xcd\x05\x97\x01\x14\x11\x50\
\x76\x95\xff\xff\x35\x9f\xc6\x43\x93\x00\x26\x84\x3a\xd4\xcc\x74\
\x2a\xa1\x03\xc7\x7d\x10\x4c\xd3\xe4\x39\x02\x8f\x81\x40\xde\xbd\
\xc1\x54\x55\x55\x11\xef\x89\x4a\x98\x60\x20\xe2\x9c\x22\xd0\xeb\
\xba\x96\xf0\x56\x6a\x82\x82\x81\x84\x53\xff\x05\x0b\x59\x96\x97\
\x34\x58\x62\xb0\x20\x41\x27\xe3\x04\xb3\x79\x0f\x33\x04\xda\xab\
\x07\x6d\xb4\x20\x3f\xb5\x90\x93\x20\x3b\x17\x45\x11\xfa\x50\x10\
\x40\x7e\x08\x9d\x33\x1a\xc4\x50\x7a\x87\x92\x04\xba\xa7\x50\x3c\
\x72\xc0\x3c\xcf\x73\x9c\x86\x58\x23\xf0\xcb\xb2\x8c\x2e\xd0\x75\
\x63\x59\xd6\x36\xc2\xcd\xef\xf8\xc4\xca\x30\x8c\x75\xdf\x0e\x43\
\x03\xe6\xba\x2e\xfb\x6a\x67\xdb\xf6\xfe\x7b\x6b\x2e\x59\x55\xd5\
\x2d\x80\xa2\x08\x0a\x6e\x50\xd7\x92\x43\x7f\xd4\xdf\xe0\xc0\x18\
\x3b\x1e\x1b\x3a\xd0\xe0\xf9\x68\xe1\x49\x82\x4e\xc6\x08\xde\xa7\
\x27\x93\xce\xcf\x54\x3a\x2a\x00\x00\x00\x00\x49\x45\x4e\x44\xae\
\x42\x60\x82\
\x00\x00\x02\xb4\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00\x00\x00\x20\x08\x03\x00\x00\x00\x44\xa4\x8a\xc6\
\x00\x00\x00\x03\x73\x42\x49\x54\x08\x08\x08\xdb\xe1\x4f\xe0\x00\
\x00\x00\x09\x70\x48\x59\x73\x00\x00\x00\xdd\x00\x00\x00\xdd\x01\
\x70\x53\xa2\x07\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\x74\
\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\
\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x00\xd8\x50\x4c\x54\
\x45\xff\xff\xff\xff\xff\x00\xff\xbf\x80\xff\xdb\x6d\xff\xdf\x80\
\xff\xd1\x74\xff\xd8\x76\xff\xd9\x73\xff\xd5\x75\xff\xd5\x77\xff\
\xd7\x78\xff\xd7\x79\xff\xd5\x79\xfa\xd5\x75\xfa\xd5\x78\xfa\xd6\
\x76\xfb\xd7\x79\xfb\xd3\x78\xfb\xd5\x78\xed\xc4\x6f\xed\xc5\x6d\
\xfc\xd6\x79\xeb\xc2\x6d\xec\xc6\x70\xfc\xd5\x76\xfc\xd6\x78\xfd\
\xd6\x77\xfd\xd4\x77\xfd\xd6\x77\xfd\xd5\x76\xfb\xd5\x78\xfb\xd4\
\x77\xfc\xd5\x78\xfc\xd5\x77\xfc\xd5\x77\xfc\xd5\x77\xfc\xd5\x78\
\xfc\xd5\x77\xfc\xd5\x77\xfb\xd5\x77\xfc\xd5\x77\xed\xc5\x6f\xfc\
\xd5\x77\xed\xc6\x6f\xfc\xd5\x77\xfc\xd5\x77\xfc\xd5\x77\xfc\xd5\
\x77\xfc\xd5\x77\xfc\xd5\x77\xf2\xcc\x72\xfc\xd5\x77\xf3\xcc\x72\
\xf3\xcc\x73\xfc\xd5\x77\xf3\xcd\x72\xfc\xd5\x77\xf3\xcb\x72\xfc\
\xd5\x77\xfc\xd5\x77\xfc\xd5\x77\xfc\xd5\x77\xfc\xd5\x77\xea\xc3\
\x6e\xf2\xcb\x72\xf3\xcc\x72\xf4\xcd\x73\xf9\xd2\x76\xfa\xd3\x76\
\xfb\xd4\x76\xfb\xd4\x77\xfc\xd5\x77\xec\x0a\x60\x8f\x00\x00\x00\
\x3f\x74\x52\x4e\x53\x00\x01\x04\x07\x08\x0b\x0d\x14\x18\x1e\x20\
\x26\x2a\x30\x31\x38\x39\x40\x42\x45\x46\x4a\x4b\x50\x5b\x64\x69\
\x6b\x7c\x7f\x80\x89\x93\x9f\xaa\xb0\xb1\xbd\xc7\xd6\xdb\xdd\xdd\
\xdf\xe4\xe5\xe7\xe8\xec\xee\xf0\xf0\xf1\xf2\xf2\xf3\xf4\xf5\xf5\
\xf6\xf9\xfa\xfc\x92\x18\x52\x21\x00\x00\x01\x03\x49\x44\x41\x54\
\x38\x4f\x8d\xce\xd7\x5a\xc2\x40\x14\x45\xe1\x03\x58\x00\x05\x44\
\x90\x26\x52\x34\x88\x88\x28\x22\xc5\x12\x08\x84\xc9\xac\xf7\x7f\
\x23\x2f\xb0\xf0\x4d\x12\xc7\x7d\xbb\xfe\x8b\x2d\xb2\xb7\x7c\xd3\
\x19\x8d\x9c\x66\x5e\xa2\x97\x6a\xaf\x00\x60\xd5\x4e\x45\xf5\x4c\
\x9f\x9f\xf5\x33\xe1\x9e\xe8\x01\xa8\xc9\x44\x01\xf4\x12\x21\xd0\
\x00\x08\x06\xe5\xf2\x20\x00\x68\x98\x3d\x39\x07\x98\x96\x44\x4a\
\x53\x80\x79\xd2\x00\x39\x00\x16\x15\x91\xca\x02\x80\x9c\x01\xea\
\x00\x04\xc3\x6a\x75\x18\x00\x50\x37\x40\x67\x77\x3f\x98\xcd\x76\
\x9d\x8e\x01\x5a\x18\x6b\x19\xa0\x06\xa0\x95\x52\x4a\x29\x0d\x50\
\x33\x40\xda\x05\xd6\x9e\xe7\x79\x9e\xb7\x06\xdc\xb4\x01\xa4\x0b\
\xa0\xb5\xd6\x5a\x03\x74\xcd\x2e\xd9\xf1\xfe\x83\x71\x36\x04\xa4\
\xb8\xfc\xed\xcb\x62\xb8\x8b\x9c\xdd\x7f\xf7\xbb\x42\x54\x17\x39\
\x7a\x65\xbb\x05\x9e\x0f\xa3\xbb\xc8\x0b\x1b\x1f\x78\x8a\xeb\xff\
\x06\xb7\x16\xf0\x71\x6a\x01\x97\xb1\xfd\x0b\x5c\xd8\xc0\xe3\xb1\
\x05\x70\x6d\x03\x57\x16\xf0\x70\x60\x01\xee\x89\x05\xe0\x58\xc0\
\xfb\x79\x2c\xb8\x61\xe3\xff\xd5\x45\x6a\x6f\xbe\xd9\x3f\x01\xf5\
\xde\x54\x7e\xca\xf7\x18\x1d\x00\x00\x00\x00\x49\x45\x4e\x44\xae\
\x42\x60\x82\
\x00\x00\x03\x2c\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00\x00\x00\x20\x08\x03\x00\x00\x00\x44\xa4\x8a\xc6\
\x00\x00\x00\x03\x73\x42\x49\x54\x08\x08\x08\xdb\xe1\x4f\xe0\x00\
\x00\x00\x09\x70\x48\x59\x73\x00\x00\x00\xe7\x00\x00\x00\xe7\x01\
\xf0\x1b\x58\xb5\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\x74\
\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\
\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x00\xf0\x50\x4c\x54\
\x45\xff\xff\xff\x6d\x6d\x92\x60\x80\x80\x60\x75\x8a\x66\x7a\x8f\
\x66\x77\x88\x65\x7a\x8c\x64\x7a\x89\x64\x7a\x8a\x65\x79\x8a\x64\
\x7a\x89\x63\x79\x8a\x63\x78\x8a\x64\x79\x8a\x64\x79\x8a\x64\x79\
\x8b\x64\x79\x8a\x64\x79\x8a\x65\x7a\x8a\x66\x7b\x8c\x68\x7d\x8d\
\x74\x87\x96\x79\x8b\x9a\x7f\x91\x9e\x85\x95\xa3\x85\x96\xa3\x87\
\x97\xa5\x90\x9f\xab\x91\x9f\xab\x92\xa0\xac\x93\xa0\xab\x98\xa5\
\xb1\x98\xa6\xb2\xa0\xab\xb5\xa1\xae\xb8\xa3\xaf\xb9\xa5\xb1\xbb\
\xb4\xb5\xbc\xb4\xbe\xc6\xb5\xbf\xc7\xb9\xc2\xca\xbb\xc4\xcc\xbd\
\xc6\xcd\xbe\xc7\xce\xca\xd2\xd7\xcb\xd3\xd8\xcd\xd4\xd9\xd8\xdd\
\xe2\xd9\xde\xe2\xdb\xe0\xe4\xdc\xe1\xe5\xdd\xe2\xe5\xdf\xe4\xe7\
\xe0\xe5\xe8\xe6\xea\xed\xe7\xeb\xed\xe9\xec\xee\xea\xdd\xdd\xeb\
\xe9\xea\xeb\xee\xf0\xec\xef\xf1\xee\x9b\x91\xee\xf0\xf2\xef\xf2\
\xf4\xf0\xf2\xf4\xf2\xb1\xa9\xf3\xf4\xf6\xf4\xf6\xf7\xf5\xf7\xf8\
\xf8\xf9\xfa\xf9\xfa\xfb\xfb\xfc\xfc\xfc\xeb\xe9\xfd\xfe\xfe\xfe\
\xf6\xf6\xfe\xf8\xf7\xfe\xfe\xfe\xfe\xff\xff\xff\xfe\xfe\xff\xff\
\xff\x7d\x02\xb4\x15\x00\x00\x00\x11\x74\x52\x4e\x53\x00\x07\x08\
\x18\x19\x2d\x49\x84\x97\x98\xc1\xc8\xda\xe3\xf2\xf3\xf5\xd5\xa8\
\x31\x5b\x00\x00\x01\x91\x49\x44\x41\x54\x38\xcb\x85\x53\xe9\x5a\
\x82\x50\x10\xbd\xee\x82\x0a\x8e\x9a\x6b\x8b\x95\xa9\xa4\x52\x02\
\x2e\xe5\x46\x29\x9a\x85\xdd\xf7\x7f\x9b\xe6\x82\x20\x20\x7e\xcd\
\x0f\xc4\x39\x87\x59\xcf\x10\xe2\x5a\x24\xc9\xf1\x59\x51\xcc\xf2\
\x5c\x32\x42\xce\x2d\x9e\x16\xc0\x35\x21\x1d\x0f\xc0\xd1\x54\xde\
\x86\x4a\x25\xfb\x37\x9f\x8a\x7a\xf1\x58\x06\x7d\x85\xe6\x60\x34\
\x9e\xcd\x27\x5a\xbf\x59\xc0\xbf\x99\xd8\x09\x4f\xe4\xd0\x51\xd7\
\x96\x06\xa5\xb2\x4c\xe9\x7e\xa3\xd6\xd1\x91\x4b\xb8\xdf\x23\x5e\
\xe8\x8d\xb7\x14\x4d\x51\xd8\x93\xea\x12\x06\xc9\x1d\x63\x44\x31\
\x7e\x45\x5b\x99\xd4\x6b\x3b\xa5\x82\x59\xec\x3a\x52\xf8\xbd\x66\
\x1c\x81\xe9\xd4\xa1\x0c\x31\x46\xca\xea\x0f\xeb\xef\xad\x1c\xb7\
\x24\x39\x6f\x66\x07\x7b\x61\xdd\xa6\xb1\xbe\xb1\x79\x4e\xa0\xeb\
\x1a\x40\x1a\xe7\x27\x60\x82\x2d\x0d\x21\xb0\x24\x42\x84\x24\x01\
\x9a\x4b\x1a\x4a\x38\x34\x00\x92\x84\x03\x18\x18\xe1\x04\xda\x05\
\xe0\x08\x0f\x30\x72\x3d\xbf\xdf\x3e\x82\x0a\xc0\x93\x2c\xc0\xf8\
\x44\x58\x3c\x75\x3c\x04\x1d\x20\x4b\x44\x28\xcd\x64\x36\xbe\xe7\
\x47\xb4\xfb\xdb\x1b\x77\x10\x8a\x6c\x16\x41\x64\x84\xf9\x89\xf0\
\x70\x77\xfd\x16\x20\x60\x8a\x89\x27\xea\xe7\xfb\xe2\xcb\x9f\x02\
\x8b\xd4\x7c\x5b\xf8\x39\x31\xac\x22\xb1\xcd\xfe\xfe\x02\xa3\xcd\
\xda\x64\x83\xda\xd0\x70\x46\x95\x0d\x8a\x8d\x5a\xa5\xa1\x8c\x57\
\x6b\xd4\xd6\xb2\xf4\x20\xe3\x03\x1f\x46\xd9\x5a\x96\xb5\x6e\x69\
\x47\xcf\xad\x75\x5c\xb7\x25\x18\xe5\x1c\x7f\x71\x04\x63\x4b\x6e\
\x68\x06\xf1\x2b\x57\x72\xb6\x68\x3b\x6b\xea\x11\xad\xd1\xf2\x88\
\xf6\x28\xfb\xda\xf0\x40\x6d\xd9\x63\xfd\x65\x9f\xec\x9d\xc3\x69\
\x74\x55\xdd\x34\x75\xb5\x5d\x0d\x1e\x8e\xe7\xf4\x8a\xc5\xd0\xd3\
\xfb\xff\x78\x2f\x9f\xff\x1f\x2f\x83\xa9\x23\xd5\xf0\x7d\x09\x00\
\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
\x00\x00\x04\x0a\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00\x00\x00\x20\x08\x03\x00\x00\x00\x44\xa4\x8a\xc6\
\x00\x00\x00\x03\x73\x42\x49\x54\x08\x08\x08\xdb\xe1\x4f\xe0\x00\
\x00\x00\x09\x70\x48\x59\x73\x00\x00\x08\x5b\x00\x00\x08\x5b\x01\
\xe8\x9f\x75\xd0\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\x74\
\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\
\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x01\x83\x50\x4c\x54\
\x45\xff\xff\xff\x55\x55\xaa\x40\x80\x80\x66\x66\x99\xff\xff\xff\
\x49\x6d\x92\xdb\xdb\xff\x55\x55\x8e\xe6\xe6\xe6\xea\xea\xea\x51\
\x5d\x80\x59\x64\x85\x55\x60\x80\x52\x5c\x85\x55\x5e\x84\x58\x61\
\x84\x9e\xa7\xb9\x80\x88\x99\x52\x63\x84\x58\x60\x80\x57\x63\x80\
\x55\x60\x81\x54\x5f\x80\x54\x5e\x81\xe7\xee\xee\xe7\xea\xee\xe8\
\xeb\xee\xe8\xeb\xeb\x56\x5f\x80\xe6\xed\xed\x56\x61\x80\xe8\xec\
\xee\x56\x60\x81\x54\x60\x80\x55\x60\x80\xe6\xec\xed\x55\x5f\x80\
\xe7\xec\xee\x56\x60\x80\x56\x60\x80\x55\x5f\x80\xe4\xea\xeb\xe8\
\xec\xed\x55\x60\x80\x78\x82\x9a\x78\x82\x9b\x84\x8e\xa3\x86\x8f\
\xa4\x74\x7e\x97\x9a\xa3\xb3\x77\x80\x99\x78\x81\x99\x55\x60\x80\
\x9a\xa2\xb3\x55\x60\x80\x74\x7d\x97\xa3\xaa\xba\xa4\xac\xbb\x6b\
\x76\x91\x76\x80\x99\xa3\xac\xba\xa7\xaf\xbe\x6b\x75\x90\xe7\xec\
\xed\x67\x71\x8e\x55\x60\x80\x55\x5f\x80\x63\x6f\x8b\x62\x6c\x89\
\xb6\xbd\xc9\x55\x60\x80\x63\x6c\x8a\xb9\xc0\xcb\xba\xc0\xca\xba\
\xc2\xcc\x5e\x68\x86\x5f\x6a\x87\x5d\x67\x86\x5e\x69\x87\x55\x60\
\x80\x5d\x67\x86\x55\x61\x80\x5b\x65\x84\x5d\x68\x87\xc5\xcc\xd4\
\xc6\xcd\xd4\x55\x60\x80\xe7\xec\xed\xc8\xcf\xd6\x55\x5f\x80\xc9\
\xcf\xd6\xcb\xd0\xd7\xe7\xec\xec\x55\x60\x80\x55\x60\x80\xe7\xeb\
\xed\xce\xd4\xda\xcf\xd6\xdc\x55\x60\x80\x55\x60\x80\xd2\xd8\xdd\
\x55\x60\x80\xd6\xda\xe0\x55\x60\x80\x55\x60\x80\xd9\xde\xe3\x55\
\x60\x80\x55\x60\x80\xe8\xec\xed\x55\x60\x80\x56\x60\x80\x55\x5f\
\x80\xe7\xec\xed\x55\x60\x80\x56\x60\x80\xe1\xe6\xe9\xe7\xec\xed\
\x55\x60\x80\x55\x60\x80\x55\x60\x80\x55\x61\x80\x55\x60\x80\xe6\
\xeb\xec\xe6\xeb\xed\x55\x60\x80\x55\x60\x81\xe6\xeb\xed\x55\x60\
\x80\xe7\xec\xed\x3f\x91\xdf\xa4\x00\x00\x00\x7f\x74\x52\x4e\x53\
\x00\x03\x04\x05\x05\x07\x07\x09\x0a\x0c\x16\x17\x18\x19\x1b\x1d\
\x1d\x1e\x1f\x20\x2c\x45\x46\x49\x49\x4a\x4d\x4e\x6e\x71\x74\x78\
\x7d\x82\x90\x91\x93\x93\x95\x98\xb3\xb5\xb9\xbd\xbd\xbd\xbf\xbf\
\xc0\xc0\xc1\xc1\xc2\xc3\xc4\xc4\xc4\xc4\xc5\xc5\xc5\xc5\xc6\xc7\
\xc8\xca\xcb\xcb\xce\xce\xcf\xcf\xcf\xd0\xd0\xd1\xd1\xd4\xd4\xd5\
\xd5\xd6\xd6\xd6\xd7\xd7\xd8\xd8\xda\xdb\xdb\xdb\xdc\xdd\xde\xde\
\xdf\xdf\xe1\xe2\xe4\xe6\xe6\xe8\xe9\xea\xed\xee\xef\xf1\xf1\xf3\
\xf3\xf4\xf4\xf4\xf4\xf5\xf6\xf7\xfb\xfd\xfd\xfd\xfe\xfe\xfe\xe0\
\xf4\x89\xca\x00\x00\x01\x6e\x49\x44\x41\x54\x18\x19\x65\xc1\x09\
\x43\x4c\x61\x14\x06\xe0\x77\x4c\x89\x5c\x5b\x1a\xd9\xab\x4b\x0d\
\x06\xa1\xc5\x12\x5a\xc8\x92\x29\xfb\x90\xad\xe4\x96\x65\xd2\x14\
\x91\xed\xf6\x9e\x9f\x5e\xf3\xdd\xf3\x9d\xee\x34\xcf\x83\x4d\x8d\
\xb9\xb0\xaf\x54\x5e\x9d\x2a\xe4\xdb\xb2\xa8\xd7\x1c\x56\x68\xca\
\xdd\x01\x6a\x65\x3b\x97\x59\xa3\xd2\xd1\x84\x94\x60\x80\x75\x46\
\x02\x98\xd6\x39\x7a\x8b\x8b\xf4\x66\x5b\xa1\x82\x59\x3a\xff\x2f\
\x5e\x9b\x59\x5b\x9b\xb9\x71\x85\x89\xb9\x00\x4e\xd3\x08\x9d\xf8\
\x92\xa8\xfe\x98\xce\x40\x16\x55\x1d\x4c\xf4\x8a\xe9\x65\xa2\x13\
\x1b\x82\x0a\x13\xe3\x62\xc6\x99\x58\x6e\x06\xd0\x4d\x15\x89\x89\
\xa8\x42\x20\x5b\xa6\x8a\xc4\x44\x54\x95\x46\xb4\xd1\x8b\xc4\x44\
\xf4\x72\xc8\xd3\x9b\x17\x33\x4f\x2f\x44\x81\xea\xa1\xa4\x3c\xa3\
\xea\xc3\x14\xd5\x79\x49\x19\xa4\x2a\x61\x95\xea\x9c\xa4\x0c\x52\
\x95\xf1\x95\xea\xe9\x3f\xd9\x74\x8f\xea\x17\x1e\xd1\xbb\x29\xe6\
\x42\x4c\xf5\x04\x05\x7a\x45\xf1\x5e\xc7\xf4\x4e\x23\x4f\xf3\x4a\
\xd4\x2d\x9a\x10\x39\x9a\xeb\x92\x78\xf3\x87\xe6\x20\x32\x9f\x69\
\x9e\x8b\x73\x9b\xe6\x53\x06\x38\x45\xf3\x40\x9c\x49\x9a\x10\xc0\
\xee\x6f\xf4\x5e\x88\x73\x87\xde\xcf\x16\x6c\x38\x46\x35\xf1\x57\
\x9c\xab\x31\xd5\x09\x54\x65\x46\x59\xf5\xbd\xe7\x87\xa8\xfb\x45\
\x3a\x77\xb7\xc1\xd9\x55\x22\x7f\x5f\xfe\x22\x29\x63\x45\x92\xef\
\xf7\x42\xed\x79\x37\xfc\x41\xb6\x18\x7b\xfc\xf1\x00\xcc\xbe\xb3\
\x52\xe7\xcc\x7e\xa4\x1d\x7d\x2b\x35\x5e\x1e\xc6\x16\xdb\xdb\x97\
\xc4\x2c\x1c\x6f\x40\xbd\x9d\x47\xba\x86\xa6\x57\x56\xa6\x87\x4e\
\x1e\xda\x01\xb3\x0e\x29\x11\x78\xcc\x11\x55\x71\x85\x00\x00\x00\
\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
\x00\x00\x02\xb6\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\
\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\
\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0b\x0e\x00\x00\x0b\x0e\
\x01\x40\xbe\xe1\x41\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\
\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\
\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x02\x33\x49\x44\
\x41\x54\x58\x85\xed\xd7\xdb\x8b\x4d\x51\x1c\x07\xf0\xcf\x3a\x33\
\x19\x1a\x73\x89\xc4\x0c\x43\x9a\x1a\x0f\x83\x44\xae\x29\x4a\x22\
\x92\xc4\xbc\xa9\x89\xe4\x92\x9a\x27\xa5\x44\xfe\x01\x79\xf3\xe0\
\xc1\xa5\x5c\x1e\x14\x4f\x3c\x08\xa1\x30\x72\x09\x45\x29\x93\x48\
\x9e\x64\xc4\x18\x4f\xb4\x3c\xec\x3d\x9a\xc6\x39\xce\x3e\x33\x73\
\x3a\x1e\x66\xd5\xaa\xbd\xd6\xef\xfb\x5b\xdf\xef\x5e\xbf\xb5\xbe\
\xbb\x1d\x62\x8c\x2a\xd9\x72\x15\x65\x1f\x13\xf0\x3f\x08\xa8\x1e\
\x49\x72\x08\x61\x0d\xd6\xa2\x1d\x4d\xf8\x88\x57\x38\x1d\x63\xec\
\xc9\xb4\x48\x8c\xb1\xe4\x8e\x85\xb8\x89\x53\x58\x87\x19\xa8\xc2\
\x6c\x74\xe0\x16\x2e\xa2\xbe\xe8\x5a\xc3\x20\x5f\x89\x07\x68\x2f\
\x82\xdb\x8a\xa7\x98\x39\x6a\x02\x30\x0f\xcf\x31\x2d\x23\x7e\x05\
\xee\xa0\x6a\xb4\x04\x5c\xc1\x82\x12\xf0\x0d\x38\x8f\x1e\x3c\xc4\
\x71\xcc\x1d\x8c\xc9\x7c\x0b\x42\x08\x73\xd0\x88\xaa\x10\x42\x5b\
\x08\xa1\xa6\x08\x7e\x03\x6e\xe0\x0d\x8e\xe1\x02\x5a\xd1\x1d\x42\
\xb8\x18\x42\xc8\x65\x3a\x84\xa8\xc5\x11\xbc\xc3\x13\x9c\xc0\x39\
\x74\xe3\x1a\xd6\xe7\xc9\xd9\x84\x4b\x68\xc8\x13\xab\xc7\x33\xdc\
\x2b\x5a\x02\xac\xc2\x0b\xec\xcb\x57\x47\xb4\xe1\x34\xce\x62\x7c\
\x09\xa5\xc9\xe1\x33\x3a\x8b\x1d\xa0\x47\x98\x9c\x61\xc1\xdd\xb8\
\x8e\x5c\x09\x22\xb6\xa3\xa7\x50\xb0\x3e\x7d\xf3\x96\x12\x16\x3c\
\x8a\xc3\xa8\xcd\x88\x1f\x87\xfe\x42\xc1\x83\xd8\x5d\x02\x79\x3b\
\xce\xa4\xdb\xfa\x1d\xfd\x78\x8b\x35\x45\xf2\x7e\x0c\x9d\x68\xc2\
\x16\x89\x9d\x4e\xc8\x48\xbe\x0b\xf7\xb1\x64\xe0\x9c\x48\x2c\x7e\
\x0f\xfa\x24\xb6\x9c\x2f\xaf\x05\x5f\x06\x06\x75\x12\x5b\xbd\x81\
\x43\x58\x94\x91\x3c\xe0\x00\x6a\x0a\xc4\x27\xe2\x13\x76\xe6\x89\
\x9d\x4c\x85\xab\xc2\x5d\x74\x64\xdd\xf2\x52\x3a\x96\xa2\x6f\xc8\
\xdc\xfc\xb4\x4c\xd3\xa1\x0b\x87\xcb\x41\x3e\x88\xf0\x03\x56\xa4\
\xcf\x5d\x29\xf9\xde\x74\xec\x76\x3e\xc3\x18\x65\x01\xdd\xe8\xc5\
\x37\xbc\x37\xc8\x8e\x73\x68\x8c\x31\x7e\x55\xde\x16\x71\x15\x93\
\x62\x8c\xb3\x62\x8c\x2f\x07\x02\xd5\xf8\x15\x42\xa8\x8e\x31\xfe\
\x2c\xa3\x80\x56\xc9\x41\xfc\x8b\x23\x27\xf9\xbc\xae\x2e\x17\x73\
\x08\xa1\x53\xe2\x90\xaf\x0b\x61\x5a\x24\x96\x5b\x57\x86\xda\x2f\
\x97\x18\xd3\xb2\x82\x98\x14\xb8\x11\x8f\xb1\x0d\x53\x47\x48\x3a\
\x0e\x9b\x71\x39\x25\xdf\xf1\x2f\x7c\x18\xb8\x0a\x21\x84\x29\xd8\
\x8f\xc5\x68\x96\x98\xcc\x70\x5a\xb3\xc4\x01\x9f\x60\x5f\x8c\xb1\
\xf7\x5f\xe0\x3f\x02\x2a\xd5\x2a\xfe\x5f\x30\x26\xa0\xe2\x02\x7e\
\x03\xb7\x39\xbc\xed\x20\x33\xf3\x9f\x00\x00\x00\x00\x49\x45\x4e\
\x44\xae\x42\x60\x82\
"
qt_resource_name = b"\
\x00\x05\
\x00\x6f\xa6\x53\
\x00\x69\
\x00\x63\x00\x6f\x00\x6e\x00\x73\
\x00\x05\
\x00\x4f\xa6\x53\
\x00\x49\
\x00\x63\x00\x6f\x00\x6e\x00\x73\
\x00\x0f\
\x03\xec\xfb\x67\
\x00\x74\
\x00\x68\x00\x65\x00\x72\x00\x6d\x00\x6f\x00\x6d\x00\x65\x00\x74\x00\x65\x00\x72\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x0c\
\x07\xb5\x0f\xc7\
\x00\x63\
\x00\x61\x00\x6c\x00\x65\x00\x6e\x00\x64\x00\x61\x00\x72\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x0c\
\x0c\xa8\x9d\xc7\
\x00\x64\
\x00\x6f\x00\x6f\x00\x72\x00\x2d\x00\x6b\x00\x65\x00\x79\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x09\
\x05\x9e\x83\x27\
\x00\x63\
\x00\x6c\x00\x6f\x00\x63\x00\x6b\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x08\
\x09\xc5\x58\xc7\
\x00\x75\
\x00\x73\x00\x65\x00\x72\x00\x2e\x00\x70\x00\x6e\x00\x67\
\x00\x0a\
\x0b\xb9\x11\x87\
\x00\x63\
\x00\x6c\x00\x6f\x00\x75\x00\x64\x00\x79\x00\x2e\x00\x70\x00\x6e\x00\x67\
"
qt_resource_struct = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\
\x00\x00\x00\x10\x00\x02\x00\x00\x00\x06\x00\x00\x00\x03\
\x00\x00\x00\x20\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
\x00\x00\x00\x80\x00\x00\x00\x00\x00\x01\x00\x00\x09\x15\
\x00\x00\x00\x44\x00\x00\x00\x00\x00\x01\x00\x00\x04\x35\
\x00\x00\x00\x98\x00\x00\x00\x00\x00\x01\x00\x00\x0c\x45\
\x00\x00\x00\xae\x00\x00\x00\x00\x00\x01\x00\x00\x10\x53\
\x00\x00\x00\x62\x00\x00\x00\x00\x00\x01\x00\x00\x06\x5d\
"
def qInitResources():
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()
|
kunz07/fyp2017
|
GUI/FinalLock.py
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'howmanylocks.ui'
#
# Created by: PyQt5 UI code generator 5.8.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_UserText(object):
def setupUi(self, UserText):
UserText.setObjectName("UserText")
UserText.resize(400, 388)
UserText.setStyleSheet("background-color: rgb(44, 0, 30);")
self.login = QtWidgets.QPushButton(UserText)
self.login.setGeometry(QtCore.QRect(160, 350, 75, 27))
self.login.setStyleSheet("color: rgb(255, 255, 255);\n"
"font: 11pt \"Big John\";")
self.login.setObjectName("login")
self.login.clicked.connect(self.Login)
self.fuzzysystem = QtWidgets.QLabel(UserText)
self.fuzzysystem.setGeometry(QtCore.QRect(40, 10, 321, 61))
font = QtGui.QFont()
font.setFamily("Peace Sans")
font.setPointSize(22)
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.fuzzysystem.setFont(font)
self.fuzzysystem.setStyleSheet("font: 22pt \"Peace Sans\";")
self.fuzzysystem.setObjectName("fuzzysystem")
self.message = QtWidgets.QLabel(UserText)
self.message.setGeometry(QtCore.QRect(90, 330, 221, 20))
self.message.setStyleSheet("font: 10pt \"Ubuntu Mono\";\n"
"color: rgb(255, 0, 0);")
self.message.setObjectName("message")
self.message.setAlignment(QtCore.Qt.AlignHCenter)
self.layoutWidget = QtWidgets.QWidget(UserText)
self.layoutWidget.setGeometry(QtCore.QRect(60, 250, 273, 34))
self.layoutWidget.setObjectName("layoutWidget")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.layoutWidget)
self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.username_icon = QtWidgets.QLabel(self.layoutWidget)
self.username_icon.setObjectName("username_icon")
self.horizontalLayout_3.addWidget(self.username_icon)
self.username = QtWidgets.QLabel(self.layoutWidget)
self.username.setStyleSheet("color: rgb(233, 84, 32);\n"
"font: 75 11pt \"Moon\";")
self.username.setObjectName("username")
self.horizontalLayout_3.addWidget(self.username)
self.usertext = QtWidgets.QLineEdit(self.layoutWidget)
self.usertext.setStyleSheet("color: rgb(174, 167, 159);\n"
"background-color: rgb(44, 0, 30);\n"
"selection-background-color: rgb(85, 170, 255);\n"
"border: none;\n" "font: 11pt \"Moon\";")
self.usertext.setPlaceholderText("Enter Username")
self.usertext.setObjectName("usertext")
self.usertext.setMaxLength(10)
self.horizontalLayout_3.addWidget(self.usertext)
self.layoutWidget1 = QtWidgets.QWidget(UserText)
self.layoutWidget1.setGeometry(QtCore.QRect(60, 290, 278, 34))
self.layoutWidget1.setObjectName("layoutWidget1")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.layoutWidget1)
self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.password_icon = QtWidgets.QLabel(self.layoutWidget1)
self.password_icon.setObjectName("password_icon")
self.horizontalLayout_4.addWidget(self.password_icon)
self.password = QtWidgets.QLabel(self.layoutWidget1)
self.password.setStyleSheet("color: rgb(233, 84, 32);\n"
"font: 25 11pt \"Moon\";")
self.password.setObjectName("password")
self.horizontalLayout_4.addWidget(self.password)
self.passtext = QtWidgets.QLineEdit(self.layoutWidget1)
self.passtext.setStyleSheet("color: rgb(174, 167, 159);\n"
"background-color: rgb(44, 0, 30);\n"
"selection-background-color: rgb(85, 170, 255);\n"
"border: none;\n" "font: 11pt \"Moon\";")
self.passtext.setPlaceholderText("Enter Password")
self.passtext.setObjectName("passtext")
self.passtext.setMaxLength(10)
self.passtext.setEchoMode(2)
self.horizontalLayout_4.addWidget(self.passtext)
self.time_hours = QtWidgets.QLabel(UserText)
self.time_hours.setGeometry(QtCore.QRect(196, 70, 101, 135))
self.time_hours.setStyleSheet("font: 76pt \"Slim Joe\";\n"
"color:rgb(174, 167, 159)")
self.time_hours.setObjectName("time_hours")
self.time_min = QtWidgets.QLabel(UserText)
self.time_min.setGeometry(QtCore.QRect(310, 90, 67, 41))
self.time_min.setStyleSheet("font: 30pt \"Big John\";\n"
"color:rgb(174, 167, 159)")
self.time_min.setText("")
self.time_min.setObjectName("time_min")
self.time_hours.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
self.time_min.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.timer1 = QtCore.QTimer()
self.timer1.setInterval(1000)
self.timer1.timeout.connect(self.Time)
self.timer1.start()
self.date = QtWidgets.QLabel(UserText)
self.date.setGeometry(QtCore.QRect(300, 140, 101, 21))
self.date.setStyleSheet("font: 10pt \"Big John\";\n"
"color:rgb(174, 167, 159)")
self.date.setText("")
self.date.setObjectName("date")
self.date.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.timer2 = QtCore.QTimer()
self.timer2.setInterval(1000)
self.timer2.timeout.connect(self.Date)
self.timer2.start()
self.retranslateUi(UserText)
QtCore.QMetaObject.connectSlotsByName(UserText)
def retranslateUi(self, UserText):
_translate = QtCore.QCoreApplication.translate
UserText.setWindowTitle(_translate("UserText", "Dialog"))
self.login.setText(_translate("UserText", "Login"))
self.fuzzysystem.setText(_translate("UserText", "<html><head/><body><p align=\"center\"><span style=\" font-size:28pt; color:#e95420;\">FUZZY SYSTEM</span></p></body></html>"))
self.message.setText(_translate("UserText", "<html><head/><body><p><br/></p></body></html>"))
self.username_icon.setText(_translate("UserText", "<html><head/><body><p><img src=\":/icons/Icons/user.png\"/></p></body></html>"))
self.username.setText(_translate("UserText", "Username :"))
self.usertext.setToolTip(_translate("UserText", "<html><head/><body><p><br/></p></body></html>"))
self.password_icon.setText(_translate("UserText", "<html><head/><body><p><img src=\":/icons/Icons/door-key.png\"/></p></body></html>"))
self.password.setText(_translate("UserText", "Password :"))
self.time_hours.setText(_translate("UserText", "<html><head/><body><p align=\"right\"><br/></p></body></html>"))
def Time(self):
self.time_hours.setText(QtCore.QTime.currentTime().toString("h"))
self.time_min.setText(QtCore.QTime.currentTime().toString("mm"))
def Date(self):
self.date.setText(QtCore.QDate.currentDate().toString("ddd, MMM d"))
def Login(self):
username = self.usertext.text()
password = self.<PASSWORD>stext.text()
allow = ['kunal', 'kamran', 'vidya']
if(username.lower() == "fyp2017" and password.lower() in allow):
self.message.setText("Access Granted")
else:
self.message.setText("Wrong Password! Try Again")
import lockscreen_rc
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
UserText = QtWidgets.QDialog()
ui = Ui_UserText()
ui.setupUi(UserText)
UserText.show()
sys.exit(app.exec_())
|
kunz07/fyp2017
|
Weather.py
|
<reponame>kunz07/fyp2017
# FYP2017
# Program to get average forecast of temperature and cloud cover for 2 days
# Author: <NAME>
# License: Public Domain
from forecastiopy import *
import datetime
f = open('DS_APIkey.txt','r')
apikey = f.read()
f.close()
Bangalore = [12.9716, 77.5946]
fio = ForecastIO.ForecastIO(apikey,
units=ForecastIO.ForecastIO.UNITS_SI,
lang=ForecastIO.ForecastIO.LANG_ENGLISH,
latitude=Bangalore[0], longitude=Bangalore[1],
)
tempc = 0
clouds = 0
if fio.has_hourly() is True:
hourly = FIOHourly.FIOHourly(fio)
for hour in range(0, 48):
tempc = tempc + float(str(hourly.get_hour(hour)['temperature']))
clouds = clouds + float(str(hourly.get_hour(hour)['cloudCover']))
else:
print('No Hourly data')
tempc = round(tempc / 48, 2)
clouds = round(clouds / 48, 2)
|
kunz07/fyp2017
|
ZigBeetest.py
|
# FYP2017
# Program to establish ZigBee communication between raspberry Pi and arduino
# Complete control of HVAC elements based on commands sent from the Pi (TESTING)
# Author: <NAME>
# License: Public Domain
import time
import serial
#import fuzzy
hour = 3600
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
def getSensorData():
if ser.isOpen():
ser.close()
ser.open()
ser.isOpen()
ser.write('s'.encode())
time.sleep(2)
response = ser.readline().strip().decode()
hum = float(response[:5])
temp = float(response[5:])
return (hum, temp)
def level_1():
h, t = getSensorData()
print('humidity is: ',h)
print('Temperature is: ',t)
print('Running in level 1..')
if (t > 35):
ser.write('c'.encode())
print('Cooler on')
if (t < 15):
ser.write('f'.encode())
print('Heater on')
if (h < 25):
ser.write('h'.encode())
print('Humidifier on')
if (h > 80):
ser.write('e'.encode())
print('Exhaust on')
time.sleep(300)
def level_2():
h, t = getSensorData()
print('humidity is: ',h)
print('Temperature is: ',t)
print('Running in level 2..')
if (t > 32):
ser.write('c'.encode())
print('Cooler on')
if (t < 18):
ser.write('f'.encode())
print('Heater on')
if (h < 30):
ser.write('h'.encode())
print('Humidifier on')
if (h > 70):
ser.write('e'.encode())
print('Exhaust on')
time.sleep(300)
def level_3():
h, t = getSensorData()
print('humidity is: ',h)
print('Temperature is: ',t)
print('Running in level 3..')
if (t > 30):
ser.write('c'.encode())
print('Cooler on')
if (t < 20):
ser.write('f'.encode())
print('Heater on')
if (h < 40):
ser.write('h'.encode())
print('Humidifier on')
if (h > 60):
ser.write('e'.encode())
print('Exhaust on')
time.sleep(300)
def level_4():
h, t = getSensorData()
print('humidity is: ',h)
print('Temperature is: ',t)
print('Running in level 4..')
if (t > 28):
ser.write('c'.encode())
print('Cooler on')
if (t < 22):
ser.write('f'.encode())
print('Heater on')
if (h < 25):
ser.write('h'.encode())
print('Humidifier on')
if (h > 50):
ser.write('e'.encode())
print('Exhaust on')
time.sleep(300)
def getLevel():
return 2 #int(fuzzy.level)
if __name__ == "__main__":
level = getLevel()
while True:
if (level == 1):
level_1()
elif (level == 2):
level_2()
elif (level == 3):
level_3()
elif (level == 4):
level_4()
else:
ser.write('x'.encode())
break
|
kunz07/fyp2017
|
GUI/final.py
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'final.ui'
#
# Created by: PyQt5 UI code generator 5.8.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from forecastiopy import *
import datetime
import sys
from ubidots import ApiClient
import time
import webbrowser
from threading import Thread
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import os.path
import serial
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_SSD1306
# Raspberry Pi pin configuration:
RST = 32
# 128x32 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
class MovieSplashScreen(QSplashScreen):
def __init__(self, movie, parent = None):
movie.jumpToFrame(0)
pixmap = QPixmap(movie.frameRect().size())
QSplashScreen.__init__(self, pixmap)
self.movie = movie
self.movie.frameChanged.connect(self.repaint)
def showEvent(self, event):
self.movie.start()
def hideEvent(self, event):
self.movie.stop()
def paintEvent(self, event):
painter = QPainter(self)
pixmap = self.movie.currentPixmap()
self.setMask(pixmap.mask())
painter.drawPixmap(0, 0, pixmap)
def sizeHint(self):
return self.movie.scaledSize()
def mousePressEvent(self, mouse_event):
pass
class Ui_system(object):
done1 = False
done2 = False
done3 = False
t = 0
c = 0
b = 0
eco = 0
roomt = 0
roomh = 0
def setupUi(self, system):
system.setObjectName("system")
system.resize(800, 600)
system.setToolTip("")
system.setStyleSheet("background-color: rgb(44, 0, 30);")
self.Fuzzy_system = QtWidgets.QWidget()
self.Fuzzy_system.setEnabled(True)
self.Fuzzy_system.setGeometry(QtCore.QRect(0, 0, 800, 538))
self.Fuzzy_system.setObjectName("Fuzzy_system")
self.title_1 = QtWidgets.QLabel(self.Fuzzy_system)
self.title_1.setGeometry(QtCore.QRect(150, -20, 503, 85))
self.title_1.setStyleSheet("font: 36pt \"Peace Sans\";\n"
"color: rgb(233, 84, 32);")
self.title_1.setObjectName("title_1")
self.time_hours = QtWidgets.QLabel(self.Fuzzy_system)
self.time_hours.setGeometry(QtCore.QRect(576, 60, 121, 121))
self.time_hours.setStyleSheet("font: 76pt \"Slim Joe\";\n"
"color:rgb(238, 247, 251);")
self.time_hours.setObjectName("time_hours")
self.time_min = QtWidgets.QLabel(self.Fuzzy_system)
self.time_min.setGeometry(QtCore.QRect(710, 80, 67, 41))
self.time_min.setStyleSheet("font: 26pt \"Big John\";\n"
"color:rgb(238, 247, 251);")
self.time_min.setText("")
self.time_min.setObjectName("time_min")
self.time_hours.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
self.time_min.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.timer1 = QtCore.QTimer()
self.timer1.setInterval(1000)
self.timer1.timeout.connect(self.Time)
self.timer1.start()
self.date = QtWidgets.QLabel(self.Fuzzy_system)
self.date.setGeometry(QtCore.QRect(700, 130, 101, 21))
self.date.setStyleSheet("font: 10pt \"<NAME>\";\n"
"color:rgb(238, 247, 251);")
self.date.setText("")
self.date.setObjectName("date")
self.date.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.timer2 = QtCore.QTimer()
self.timer2.setInterval(1000)
self.timer2.timeout.connect(self.Date)
self.timer2.start()
self.run_system = QtWidgets.QPushButton(self.Fuzzy_system)
self.run_system.setGeometry(QtCore.QRect(230, 480, 361, 51))
self.run_system.setStyleSheet("color: rgb(255, 255, 255);\n"
"font: 11pt \"<NAME>\";")
self.run_system.setObjectName("run_system")
self.run_system.clicked.connect(self.Run_System)
self.timer5 = QtCore.QTimer()
self.timer5.setInterval(1000 * 300)
self.timer5.timeout.connect(self.Run_System)
self.timer5.start()
self.avg_temp_txt = QtWidgets.QLabel(self.Fuzzy_system)
self.avg_temp_txt.setGeometry(QtCore.QRect(0, 100, 121, 51))
self.avg_temp_txt.setStyleSheet("font: 75 32pt \"Moon\";\n"
"color:rgbrgb(85, 85, 255);")
self.avg_temp_txt.setObjectName("avg_temp_txt")
self.avg_temp_txt.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
self.temp_icon = QtWidgets.QLabel(self.Fuzzy_system)
self.temp_icon.setGeometry(QtCore.QRect(340, 110, 32, 32))
self.temp_icon.setStyleSheet("font: 26pt \"Big John\";\n"
"color:rgb(174, 167, 159)")
self.temp_icon.setObjectName("temp_icon")
self.avg_cc_txt = QtWidgets.QLabel(self.Fuzzy_system)
self.avg_cc_txt.setGeometry(QtCore.QRect(0, 170, 121, 51))
self.avg_cc_txt.setStyleSheet("font: 75 32pt \"Moon\";\n"
"color:rgb(85, 85, 255);")
self.avg_cc_txt.setObjectName("avg_cc_txt")
self.avg_cc_txt.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
self.avg_batt_txt = QtWidgets.QLabel(self.Fuzzy_system)
self.avg_batt_txt.setGeometry(QtCore.QRect(0, 240, 121, 51))
self.avg_batt_txt.setStyleSheet("font: 75 32pt \"Moon\";\n"
"color:rgb(85, 85, 255);")
self.avg_batt_txt.setObjectName("avg_batt_txt")
self.avg_batt_txt.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
self.timer3 = QtCore.QTimer()
self.timer3.setInterval(1000 * 900)
self.timer3.timeout.connect(self.Update_Battery)
self.timer3.start()
self.battery_percent_but = QtWidgets.QPushButton(self.Fuzzy_system)
self.battery_percent_but.setGeometry(QtCore.QRect(120, 250, 221, 32))
self.battery_percent_but.setStyleSheet("font: 75 11pt \"Moon\";\n"
"color: rgb(200, 226, 240);")
self.battery_percent_but.clicked.connect(self.Batt_Percent)
self.battery_percent_but.setObjectName("battery_percent_but")
self.batt_icon = QtWidgets.QLabel(self.Fuzzy_system)
self.batt_icon.setGeometry(QtCore.QRect(340, 250, 32, 32))
self.batt_icon.setStyleSheet("font: 26pt \"Big John\";\n"
"color:rgb(174, 167, 159)")
self.batt_icon.setObjectName("batt_icon")
self.cloud_icon = QtWidgets.QLabel(self.Fuzzy_system)
self.cloud_icon.setGeometry(QtCore.QRect(340, 180, 32, 32))
self.cloud_icon.setStyleSheet("font: 26pt \"Big John\";\n"
"color:rgb(174, 167, 159)")
self.cloud_icon.setObjectName("cloud_icon")
self.average_cc_but = QtWidgets.QPushButton(self.Fuzzy_system)
self.average_cc_but.setGeometry(QtCore.QRect(120, 180, 221, 32))
self.average_cc_but.setStyleSheet("font: 75 11pt \"Moon\";\n"
"color: rgb(200, 226, 240);")
self.average_cc_but.setObjectName("average_cc_but")
self.average_cc_but.clicked.connect(self.Avg_CC)
self.defuzz_txt = QtWidgets.QLabel(self.Fuzzy_system)
self.defuzz_txt.setGeometry(QtCore.QRect(240, 380, 161, 71))
self.defuzz_txt.setStyleSheet("font: 40pt \"Big John\";\n"
"color:rgb(238, 247, 251);")
self.defuzz_txt.setObjectName("defuzz_txt")
self.defuzz_but = QtWidgets.QPushButton(self.Fuzzy_system)
self.defuzz_but.setGeometry(QtCore.QRect(50, 400, 179, 32))
self.defuzz_but.setStyleSheet("font: 11pt \"Peace Sans\";\n"
"color: rgb(34, 139, 34)")
self.defuzz_but.setObjectName("defuzz_but")
self.defuzz_but.clicked.connect(self.Defuzz)
self.eco_level_but = QtWidgets.QPushButton(self.Fuzzy_system)
self.eco_level_but.setGeometry(QtCore.QRect(450, 400, 179, 32))
self.eco_level_but.setStyleSheet("font: 11pt \"Peace Sans\";\n"
"color: rgb(34, 139, 34)")
self.eco_level_but.setObjectName("eco_level_but")
self.eco_level_but.clicked.connect(self.Eco)
self.temp_but = QtWidgets.QPushButton(self.Fuzzy_system)
self.temp_but.setGeometry(QtCore.QRect(500, 200, 161, 26))
self.temp_but.setStyleSheet("color:rgb(200, 226, 240);\n"
"font: 75 11pt \"Moon\";")
self.temp_but.setObjectName("temp_but")
self.temp_but.clicked.connect(self.DarkSky)
self.average_temp_but = QtWidgets.QPushButton(self.Fuzzy_system)
self.average_temp_but.setGeometry(QtCore.QRect(120, 110, 221, 32))
self.average_temp_but.setStyleSheet("font: 75 11pt \"Moon\";\n"
"color: rgb(200, 226, 240);")
self.average_temp_but.setObjectName("average_temp_but")
self.average_temp_but.clicked.connect(self.Avg_temp)
self.cloud_cover_but = QtWidgets.QPushButton(self.Fuzzy_system)
self.cloud_cover_but.setGeometry(QtCore.QRect(500, 270, 161, 26))
self.cloud_cover_but.setStyleSheet("color:rgb(200, 226, 240);\n"
"font: 75 11pt \"Moon\";")
self.cloud_cover_but.setObjectName("cloud_cover_but")
self.cloud_cover_but.clicked.connect(self.DarkSky)
self.temp_text = QtWidgets.QLabel(self.Fuzzy_system)
self.temp_text.setGeometry(QtCore.QRect(662, 180, 131, 61))
self.temp_text.setStyleSheet("font: 75 32pt \"Moon\";\n"
"color:rgb(233, 99, 94);")
self.temp_text.setObjectName("temp_text")
self.temp_text.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
self.eco_level_txt = QtWidgets.QLabel(self.Fuzzy_system)
self.eco_level_txt.setGeometry(QtCore.QRect(640, 380, 61, 71))
self.eco_level_txt.setStyleSheet("font: 40pt \"Big John\";\n"
"color:rgb(238, 247, 251);")
self.eco_level_txt.setObjectName("eco_level_txt")
self.cloud_cover_txt = QtWidgets.QLabel(self.Fuzzy_system)
self.cloud_cover_txt.setGeometry(QtCore.QRect(662, 250, 131, 61))
self.cloud_cover_txt.setStyleSheet("font: 75 32pt \"Moon\";\n"
"color:rgb(233, 99, 94);")
self.cloud_cover_txt.setObjectName("cloud_cover_txt")
self.cloud_cover_txt.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
self.refresh_current = QtWidgets.QToolButton(self.Fuzzy_system)
self.refresh_current.setGeometry(QtCore.QRect(610, 330, 88, 31))
self.refresh_current.setStyleSheet("font: 11pt \"Peace Sans\";\n"
"color: rgb(34, 139, 34)")
self.refresh_current.setObjectName("refresh_current")
self.refresh_current.clicked.connect(self.loading2)
self.refresh_avg = QtWidgets.QToolButton(self.Fuzzy_system)
self.refresh_avg.setGeometry(QtCore.QRect(150, 300, 88, 31))
self.refresh_avg.setStyleSheet("font: 11pt \"Peace Sans\";\n"
"color: rgb(34, 139, 34)")
self.refresh_avg.setObjectName("refresh_avg")
self.refresh_avg.clicked.connect(self.loading1)
self.timer4 = QtCore.QTimer()
self.timer4.setInterval(1000 * 86400)
self.timer4.timeout.connect(self.loading1)
self.timer4.start()
self.dark_sky_1 = QtWidgets.QToolButton(self.Fuzzy_system)
self.dark_sky_1.setGeometry(QtCore.QRect(640, 510, 158, 23))
self.dark_sky_1.setStyleSheet("font: 25 10pt \"Ubuntu\";\n"
"color: rgb(85, 170, 255)")
self.dark_sky_1.setObjectName("dark_sky_1")
self.dark_sky_1.clicked.connect(self.DarkSky)
self.title_1.raise_()
self.time_hours.raise_()
self.time_min.raise_()
self.date.raise_()
self.run_system.raise_()
self.avg_temp_txt.raise_()
self.avg_cc_txt.raise_()
self.avg_batt_txt.raise_()
self.defuzz_txt.raise_()
self.average_temp_but.raise_()
self.temp_icon.raise_()
self.average_cc_but.raise_()
self.cloud_icon.raise_()
self.battery_percent_but.raise_()
self.batt_icon.raise_()
self.cloud_cover_but.raise_()
self.temp_text.raise_()
self.defuzz_but.raise_()
self.eco_level_but.raise_()
self.eco_level_txt.raise_()
self.temp_but.raise_()
self.cloud_cover_txt.raise_()
self.refresh_current.raise_()
self.refresh_avg.raise_()
self.dark_sky_1.raise_()
system.addItem(self.Fuzzy_system, "")
self.Room_Conditions = QtWidgets.QWidget()
self.Room_Conditions.setGeometry(QtCore.QRect(0, 0, 800, 538))
self.Room_Conditions.setObjectName("Room_Conditions")
self.title_2 = QtWidgets.QLabel(self.Room_Conditions)
self.title_2.setGeometry(QtCore.QRect(130, -20, 521, 85))
self.title_2.setStyleSheet("font: 36pt \"Peace Sans\";\n"
"color: rgb(233, 84, 32);")
self.title_2.setObjectName("title_2")
self.room_temp_txt = QtWidgets.QLabel(self.Room_Conditions)
self.room_temp_txt.setGeometry(QtCore.QRect(2, 90, 131, 61))
self.room_temp_txt.setStyleSheet("font: 75 32pt \"Moon\";\n"
"color:rgb(238, 247, 251);")
self.room_temp_txt.setObjectName("room_temp_txt")
self.room_temp_txt.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
self.room_hum_but = QtWidgets.QPushButton(self.Room_Conditions)
self.room_hum_but.setGeometry(QtCore.QRect(490, 110, 161, 26))
self.room_hum_but.setStyleSheet("color:rgb(233, 99, 94);\n"
"font: 75 11pt \"Moon\";")
self.room_hum_but.setObjectName("room_hum_but")
self.room_hum_but.clicked.connect(self.Room_hum_browser)
self.room_hum_txt = QtWidgets.QLabel(self.Room_Conditions)
self.room_hum_txt.setGeometry(QtCore.QRect(660, 90, 131, 61))
self.room_hum_txt.setStyleSheet("font: 75 32pt \"Moon\";\n"
"color:rgb(238, 247, 251);")
self.room_hum_txt.setObjectName("room_hum_txt")
self.room_hum_txt.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
self.room_temp_but = QtWidgets.QPushButton(self.Room_Conditions)
self.room_temp_but.setGeometry(QtCore.QRect(140, 110, 161, 26))
self.room_temp_but.setStyleSheet("color:rgb(233, 99, 94);\n"
"font: 75 11pt \"Moon\";")
self.room_temp_but.setObjectName("room_temp_but")
self.room_temp_but.clicked.connect(self.Room_temp_browser)
self.heater_on = QtWidgets.QLabel(self.Room_Conditions)
self.heater_on.setGeometry(QtCore.QRect(230, 310, 61, 61))
self.heater_on.setStyleSheet("font: 75 26pt \"Moon\";\n"
"color: rgb(0, 255, 0);")
self.heater_on.setObjectName("heater_on")
self.cooler_on = QtWidgets.QLabel(self.Room_Conditions)
self.cooler_on.setGeometry(QtCore.QRect(230, 380, 61, 61))
self.cooler_on.setStyleSheet("font: 75 26pt \"Moon\";\n"
"color: rgb(0, 255, 0);")
self.cooler_on.setObjectName("cooler_on")
self.heater_off = QtWidgets.QLabel(self.Room_Conditions)
self.heater_off.setGeometry(QtCore.QRect(300, 310, 61, 61))
self.heater_off.setStyleSheet("font: 75 26pt \"Moon\";\n"
"color: rgb(255, 0, 0);\n"
"")
self.heater_off.setObjectName("heater_off")
self.cooler_off = QtWidgets.QLabel(self.Room_Conditions)
self.cooler_off.setGeometry(QtCore.QRect(300, 380, 61, 61))
self.cooler_off.setStyleSheet("font: 75 26pt \"Moon\";\n"
"color: rgb(255, 0, 0);")
self.cooler_off.setObjectName("cooler_off")
self.heater = QtWidgets.QLabel(self.Room_Conditions)
self.heater.setGeometry(QtCore.QRect(150, 330, 71, 31))
self.heater.setStyleSheet("font: 11pt \"Peace Sans\";\n"
"color:rgb(85, 85, 255);")
self.heater.setObjectName("heater")
self.cooler = QtWidgets.QLabel(self.Room_Conditions)
self.cooler.setGeometry(QtCore.QRect(150, 400, 71, 31))
self.cooler.setStyleSheet("color:rgb(85, 85, 255);\n"
"font: 11pt \"Peace Sans\";")
self.cooler.setObjectName("cooler")
self.dehumid_on = QtWidgets.QLabel(self.Room_Conditions)
self.dehumid_on.setGeometry(QtCore.QRect(490, 380, 61, 61))
self.dehumid_on.setStyleSheet("font: 75 26pt \"Moon\";\n"
"color: rgb(0, 255, 0);")
self.dehumid_on.setObjectName("dehumid_on")
self.humid_off = QtWidgets.QLabel(self.Room_Conditions)
self.humid_off.setGeometry(QtCore.QRect(420, 310, 61, 61))
self.humid_off.setStyleSheet("font: 75 26pt \"Moon\";\n"
"color: rgb(255, 0, 0);")
self.humid_off.setObjectName("humid_off")
self.humid_on = QtWidgets.QLabel(self.Room_Conditions)
self.humid_on.setGeometry(QtCore.QRect(490, 310, 61, 61))
self.humid_on.setStyleSheet("font: 75 26pt \"Moon\";\n"
"color: rgb(0, 255, 0);")
self.humid_on.setObjectName("humid_on")
self.dehumid_off = QtWidgets.QLabel(self.Room_Conditions)
self.dehumid_off.setGeometry(QtCore.QRect(420, 380, 61, 61))
self.dehumid_off.setStyleSheet("font: 75 26pt \"Moon\";\n"
"color: rgb(255, 0, 0);")
self.dehumid_off.setObjectName("dehumid_off")
self.humidifier = QtWidgets.QLabel(self.Room_Conditions)
self.humidifier.setGeometry(QtCore.QRect(560, 330, 101, 31))
self.humidifier.setStyleSheet("font: 11pt \"Peace Sans\";\n"
"color:rgb(85, 85, 255);")
self.humidifier.setObjectName("humidifier")
self.dehumidifier = QtWidgets.QLabel(self.Room_Conditions)
self.dehumidifier.setGeometry(QtCore.QRect(560, 400, 121, 31))
self.dehumidifier.setStyleSheet("font: 11pt \"Peace Sans\";\n"
"color:rgb(85, 85, 255);")
self.dehumidifier.setObjectName("dehumidifier")
self.running = QtWidgets.QLabel(self.Room_Conditions)
self.running.setGeometry(QtCore.QRect(230, 170, 331, 41))
self.running.setStyleSheet("color: rgb(255, 255, 0);\n"
"font: 14pt \"Big John\";")
self.running.setObjectName("running")
self.run_eco_level = QtWidgets.QLabel(self.Room_Conditions)
self.run_eco_level.setGeometry(QtCore.QRect(350, 220, 81, 61))
self.run_eco_level.setStyleSheet("font: 40pt \"Big John\";\n"
"color: rgb(255, 255, 255);\n"
"")
self.run_eco_level.setObjectName("run_eco_level")
self.run_eco_level.setObjectName("run_eco_level")
self.run_eco_level.setText("--")
self.run_eco_level.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
self.open_ubidots = QtWidgets.QPushButton(self.Room_Conditions)
self.open_ubidots.setGeometry(QtCore.QRect(230, 460, 361, 51))
self.open_ubidots.setStyleSheet("color: rgb(255, 255, 255);\n"
"font: 11pt \"Big John\";")
self.open_ubidots.setObjectName("open_ubidots")
self.open_ubidots.clicked.connect(self.Open_ubidots)
self.dark_sky_2 = QtWidgets.QToolButton(self.Room_Conditions)
self.dark_sky_2.setGeometry(QtCore.QRect(640, 490, 158, 23))
self.dark_sky_2.setStyleSheet("font: 25 10pt \"Ubuntu\";\n"
"color: rgb(85, 170, 255)")
self.dark_sky_2.setObjectName("dark_sky_2")
system.addItem(self.Room_Conditions, "")
self.retranslateUi(system)
system.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(system)
def retranslateUi(self, system):
_translate = QtCore.QCoreApplication.translate
system.setWindowTitle(_translate("system", "ToolBox"))
self.title_1.setText(_translate("system", "SYSTEM VARIABLES"))
self.time_hours.setText(_translate("system", "<html><head/><body><p align=\"right\"><br/></p></body></html>"))
self.run_system.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">RUN SYSTEM IN OBTAINED ECONOMY LEVEL</span></p></body></html>"))
self.run_system.setText(_translate("system", "RUN SYSTEM"))
self.avg_temp_txt.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.temp_icon.setText(_translate("system", "<html><head/><body><p><img src=\":/icons/Icons/thermometer.png\"/></p></body></html>"))
self.avg_cc_txt.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.avg_batt_txt.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.battery_percent_but.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-size:9pt; font-weight:600; color:#e95420;\">VIEW PLOT IN UBIDOTS</span></p></body></html>"))
self.battery_percent_but.setText(_translate("system", "BATTERY PERCENTAGE"))
self.batt_icon.setText(_translate("system", "<html><head/><body><p><img src=\":/icons/Icons/battery.png\"/></p></body></html>"))
self.cloud_icon.setText(_translate("system", "<html><head/><body><p><img src=\":/icons/Icons/cloudy.png\"/></p></body></html>"))
self.average_cc_but.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-size:9pt; font-weight:600; color:#e95420;\">VIEW PLOT IN UBIDOTS</span></p></body></html>"))
self.average_cc_but.setText(_translate("system", "AVERAGE CLOUD COVER"))
self.defuzz_txt.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.defuzz_but.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">DEFUZZIFY THE INPUTS</span></p></body></html>"))
self.defuzz_but.setText(_translate("system", "DEFUZZIFICATION"))
self.eco_level_but.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">Log DATA</span></p></body></html>"))
self.eco_level_but.setText(_translate("system", "ECONOMY LEVEL"))
self.temp_but.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-size:9pt; font-weight:600; color:#e95420;\">WEATHER FORECAST</span></p></body></html>"))
self.temp_but.setText(_translate("system", "TEMPERATURE"))
self.average_temp_but.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-size:9pt; font-weight:600; color:#e95420;\">VIEW PLOT IN UBIDOTS</span></p></body></html>"))
self.average_temp_but.setText(_translate("system", "AVERAGE TEMPERATURE"))
self.cloud_cover_but.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-size:9pt; font-weight:600; color:#e95420;\">WEATHER FORECAST</span></p></body></html>"))
self.cloud_cover_but.setText(_translate("system", "CLOUD COVER"))
self.temp_text.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.eco_level_txt.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.cloud_cover_txt.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.refresh_current.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">REFRESH DATA</span></p></body></html>"))
self.refresh_current.setText(_translate("system", "REFRESH"))
self.refresh_avg.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">REFRESH DATA</span></p></body></html>"))
self.refresh_avg.setText(_translate("system", "REFRESH"))
self.dark_sky_1.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">DARK SKY</span></p></body></html>"))
self.dark_sky_1.setText(_translate("system", "POWERED BY DARK SKY"))
system.setItemText(system.indexOf(self.Fuzzy_system), _translate("system", "Page 1"))
self.title_2.setText(_translate("system", "ROOM CONDITIONS"))
self.room_temp_txt.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.room_hum_but.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-size:9pt; font-weight:600; color:#e95420;\">VIEW PLOT IN UBIDOTS</span></p></body></html>"))
self.room_hum_but.setText(_translate("system", "HUMIDITY"))
self.room_hum_txt.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.room_temp_but.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-size:9pt; font-weight:600; color:#e95420;\">VIEW PLOT IN UBIDOTS</span></p></body></html>"))
self.room_temp_but.setText(_translate("system", "TEMPERATURE"))
self.heater_on.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.cooler_on.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.heater_off.setText(_translate("system", "<html><head/><body><p align=\"right\"><br/></p></body></html>"))
self.cooler_off.setText(_translate("system", "<html><head/><body><p align=\"right\"><br/></p></body></html>"))
self.heater.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">HEATER STATUS</span></p></body></html>"))
self.heater.setText(_translate("system", "<html><head/><body><p align=\"right\">HEATER</p></body></html>"))
self.cooler.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">COOLER STATUS</span></p></body></html>"))
self.cooler.setText(_translate("system", "<html><head/><body><p align=\"right\">COOLER</p></body></html>"))
self.dehumid_on.setText(_translate("system", "<html><head/><body><p align=\"right\"><br/></p></body></html>"))
self.humid_off.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.humid_on.setText(_translate("system", "<html><head/><body><p align=\"right\"><br/></p></body></html>"))
self.dehumid_off.setText(_translate("system", "<html><head/><body><p><br/></p></body></html>"))
self.humidifier.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">HUMIDIFIER STATUS</span></p></body></html>"))
self.humidifier.setText(_translate("system", "HUMIDIFIER"))
self.dehumidifier.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">DEHUMIDIFIER STATUS</span></p></body></html>"))
self.dehumidifier.setText(_translate("system", "DEHUMIDIFIER"))
self.running.setText(_translate("system", "<html><head/><body><p align=\"center\">RUNNING IN ECONOMY LEVEL</p></body></html>"))
self.run_eco_level.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">VIEW PLOT</span></p></body></html>"))
self.run_eco_level.setText(_translate("system", "<html><head/><body><p align=\"center\"><br/></p></body></html>"))
self.open_ubidots.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">OPEN UBIDOTS IN WEB BROWSER</span></p></body></html>"))
self.open_ubidots.setText(_translate("system", "OPEN UBIDOTS"))
self.dark_sky_2.setToolTip(_translate("system", "<html><head/><body><p align=\"center\"><span style=\" font-family:\'Moon\'; font-size:9pt; font-weight:600; color:#e95420;\">DARK SKY</span></p></body></html>"))
self.dark_sky_2.setText(_translate("system", "POWERED BY DARK SKY"))
system.setItemText(system.indexOf(self.Room_Conditions), _translate("system", "Page 2"))
def DarkSky(self):
webbrowser.open('https://darksky.net/poweredby/', new = 2)
def Time(self):
self.time_hours.setText(QtCore.QTime.currentTime().toString("h"))
self.time_min.setText(QtCore.QTime.currentTime().toString("mm"))
def Date(self):
self.date.setText(QtCore.QDate.currentDate().toString("ddd, MMM d"))
def loading1(self):
self.done1 = False
movie = QMovie("Icons/loading.gif")
splash = MovieSplashScreen(movie)
splash.setMask(splash.mask())
splash.show()
test1 = Thread(target = self.Update_Average).start()
while not self.done1:
app.processEvents()
splash.finish(system)
def Update_Average(self):
f = open('Ubidots_APIkey.txt', 'r')
apikey = f.readline().strip()
f.close()
api = ApiClient(token = apikey)
try:
temp = api.get_variable("58d76383762542260cf36d8f")
cloud_cover = api.get_variable("58d76394762542260a851a05")
batt = api.get_variable("58d763aa762542260cf36f24")
except ValueError:
print('Unable to obtain variable')
f = open('DS_APIkey.txt','r')
apikey = f.read()
f.close()
Bangalore = [12.9716, 77.5946]
fio = ForecastIO.ForecastIO(apikey,
units=ForecastIO.ForecastIO.UNITS_SI,
lang=ForecastIO.ForecastIO.LANG_ENGLISH,
latitude=Bangalore[0], longitude=Bangalore[1],
)
tempc = 0
clouds = 0
if fio.has_hourly() is True:
hourly = FIOHourly.FIOHourly(fio)
for hour in range(0, 48):
tempc = tempc + float(str(hourly.get_hour(hour)['temperature']))
clouds = clouds + float(str(hourly.get_hour(hour)['cloudCover']))
else:
print('No Hourly data')
self.t = round(tempc / 48, 2)
self.c = round(clouds / 48, 2)
self.b = self.Update_Battery()
try:
temp.save_value({'value': self.t})
cloud_cover.save_value({'value': self.c})
batt.save_value({'value': self.b})
time.sleep(1)
except:
print('Value not sent')
self.avg_temp_txt.setText('{:0.01f}°'.format(self.t))
self.avg_cc_txt.setText('{}%'.format(int(self.c*100)))
self.avg_batt_txt.setText('{}%'.format(self.b))
self.done1 = True
def loading2(self):
self.done2 = False
movie = QMovie("Icons/loading.gif")
splash = MovieSplashScreen(movie)
splash.setMask(splash.mask())
splash.show()
test = Thread(target = self.Update_Current).start()
while not self.done2:
app.processEvents()
splash.finish(system)
def Batt_Percent(self):
webbrowser.open('https://app.ubidots.com/ubi/getchart/page/R2kbUV5P5DSJVlXdTfMOXflxNtM', new = 2)
def Avg_CC(self):
webbrowser.open('https://app.ubidots.com/ubi/getchart/page/0f62Hh2lV0PMO8-p_X7DYFyNnd4', new = 2)
def Avg_temp(self):
webbrowser.open('https://app.ubidots.com/ubi/getchart/page/DlD6wC0uiipZzD3nbBT_Xty6myk', new = 2)
def Update_Battery(self):
f = open('Ubidots_APIkey.txt', 'r')
apikey = f.readline().strip()
f.close()
api = ApiClient(token = apikey)
try:
batt = api.get_variable("58d763aa762542260cf36f24")
except ValueError:
print('Value Error')
# Initialize library.
disp.begin()
time.sleep(5)
width = disp.width
height = disp.height
# Clear display.
disp.clear()
disp.display()
image = Image.new('1', (width, height))
# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)
# Load default font.
font = ImageFont.load_default()
# Alternatively load a TTF font. Make sure the .ttf font file is in the same directory as the python script!
# Some other nice fonts to try: http://www.dafont.com/bitmap.php
#font = ImageFont.truetype('Minecraftia.ttf', 8)
# Hardware SPI configuration:
SPI_PORT = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
# Main program loop.
time.sleep(2)
# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)
value = mcp.read_adc(0)
volts = ((value*3.3)) / float(1023) #voltage divider voltage
volts = volts * 5.7 #actual voltage
volts = round(volts,2)
if (volts >=13.6):
batt = 100
print('100% Battery')
draw.text((0, 0), 'Battery percent at: ',font=font, fill = 255)
draw.text((50, 20),str(batt) , font=font, fill = 255)
disp.image(image)
disp.display()
time.sleep(1)
elif (volts > 11.6):
batt = round ((volts - 11.6) * 50,1)
print(batt,'% Battery')
draw.text((10, 0), 'Battery percent at: ',font=font, fill = 255)
draw.text((45, 20),str(batt) , font=font, fill = 255)
disp.image(image)
disp.display()
time.sleep(1)
else:
batt = 0
print('Connection Error')
draw.text((55, 10),':(' , font=font, fill = 255)
disp.image(image)
disp.display()
# Print the ADC values.
# Pause time.
time.sleep(1)
return(batt)
def Update_Current(self):
f = open('DS_APIkey.txt','r')
apikey = f.read()
f.close()
Bangalore = [12.9716, 77.5946]
fio = ForecastIO.ForecastIO(apikey,
units=ForecastIO.ForecastIO.UNITS_SI,
lang=ForecastIO.ForecastIO.LANG_ENGLISH,
latitude=Bangalore[0], longitude=Bangalore[1],
)
if fio.has_currently() is True:
currently = FIOCurrently.FIOCurrently(fio)
self.temp_text.setText('{:0.01f}°'.format(currently.temperature))
self.cloud_cover_txt.setText('{}%'.format(int(currently.cloudCover * 100)))
else:
print('No Currently data')
self.done2 = True
def Defuzz(self):
# New Antecedent/Consequent objects hold universe variables and membership
# functions
batt_percent = ctrl.Antecedent(np.arange(0, 100, 1), 'Battery_percentage')
temp = ctrl.Antecedent(np.arange(15, 30, 1), 'Temperature')
cloud_cover = ctrl.Antecedent(np.arange(0, 1, 0.01), 'Cloud_cover')
eco_level = ctrl.Consequent(np.arange(1, 4, 0.01), 'Economy_level')
# Battery membership function population
batt_percent['Low_battery'] = fuzz.trapmf(batt_percent.universe, [0, 0, 20, 30])
batt_percent['Medium_battery'] = fuzz.trapmf(batt_percent.universe, [20, 25, 75, 80])
batt_percent['High_battery'] = fuzz.trapmf(batt_percent.universe, [75, 80, 100, 100])
# Temperature membership function population
temp['Low_temperature'] = fuzz.trapmf(temp.universe, [0, 0, 18, 20])
temp['Medium_temperature'] = fuzz.trapmf(temp.universe, [18, 20, 24, 26])
temp['High_temperature'] = fuzz.trapmf(temp.universe, [24 , 26, 30, 30])
# Cloud_cover membership function population
cloud_cover['Minimum_clouds'] = fuzz.trapmf(cloud_cover.universe, [0, 0, 0.20, 0.25])
cloud_cover['Medium_clouds'] = fuzz.trapmf(cloud_cover.universe, [0.20, 0.25, 0.65, 0.70])
cloud_cover['High_clouds'] = fuzz.trapmf(cloud_cover.universe, [0.65, 0.70, 1, 1])
# Custom membership functions can be built interactively with a familiar,
# Pythonic API
eco_level['Critical'] = fuzz.trimf(eco_level.universe, [0, 1.0, 2.0])
eco_level['Alert'] = fuzz.trimf(eco_level.universe, [1.75, 2.25, 2.75])
eco_level['Normal'] = fuzz.trimf(eco_level.universe, [2.5, 3.0, 3.5])
eco_level['Economyless'] = fuzz.trimf(eco_level.universe, [3.25, 4.0, 5.0])
# Rules
rule1 = ctrl.Rule(batt_percent['Low_battery'] &
(~temp['High_temperature']),
eco_level['Critical'])
rule2 = ctrl.Rule(batt_percent['Low_battery'] &
temp['High_temperature'] &
cloud_cover['High_clouds'],
eco_level['Critical'])
rule3 = ctrl.Rule(batt_percent['Low_battery'] &
temp['High_temperature'] &
(~cloud_cover['High_clouds']),
eco_level['Alert'])
rule4 = ctrl.Rule(batt_percent['Medium_battery'] &
temp['Low_temperature'] &
(~cloud_cover['High_clouds']),
eco_level['Alert'])
rule5 = ctrl.Rule(batt_percent['Medium_battery'] &
temp['Low_temperature'] &
cloud_cover['High_clouds'],
eco_level['Critical'])
rule6 = ctrl.Rule(batt_percent['Medium_battery'] &
(~temp['Low_temperature']) &
(~cloud_cover['High_clouds']),
eco_level['Normal'])
rule7 = ctrl.Rule(batt_percent['Medium_battery'] &
(~temp['Low_temperature']) &
cloud_cover['High_clouds'],
eco_level['Alert'])
rule8 = ctrl.Rule(batt_percent['High_battery'] &
temp['Low_temperature'] &
(~cloud_cover['High_clouds']),
eco_level['Normal'])
rule9 = ctrl.Rule(batt_percent['High_battery'] &
temp['Low_temperature'] &
cloud_cover['High_clouds'],
eco_level['Alert'])
rule10 = ctrl.Rule(batt_percent['High_battery'] &
(~temp['Low_temperature']) &
(~cloud_cover['High_clouds']),
eco_level['Economyless'])
rule11 = ctrl.Rule(batt_percent['High_battery'] &
(~temp['Low_temperature']) &
cloud_cover['High_clouds'],
eco_level['Normal'])
eco_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4,
rule5, rule6, rule7, rule8,
rule9, rule10, rule11])
eco_mode = ctrl.ControlSystemSimulation(eco_ctrl)
# Pass inputs to the ControlSystem using Antecedent labels with Pythonic API
# Note: if you like passing many inputs all at once, use .inputs(dict_of_data)
eco_mode.input['Temperature'] = self.t
eco_mode.input['Cloud_cover'] = self.c
eco_mode.input['Battery_percentage'] = self.b
# Crunch the numbers
eco_mode.compute()
defuzz = eco_mode.output['Economy_level']
self.defuzz_txt.setText(format(defuzz,'.2f'))
self.eco = int(defuzz + 0.5)
def Eco(self):
if (self.eco < 1):
self.eco = 1
self.eco_level_txt.setNum(self.eco)
self.run_eco_level.setNum(self.eco)
filename1 = datetime.datetime.now().strftime("%Y.%m.%d_%H:%M")
save_path = 'Logs/'
complete_path = os.path.join(save_path, filename1+'.log')
f = open(complete_path, 'w')
if (self.t == 0) or (self.c == 0) or (self.b == 0):
f.write('Data Unavailable, running in economy level 1')
else:
f.write('Average Temperature is: ' + str(self.t) + ' °C' + '\n')
f.write('Average Cloud Cover is: ' + str(self.c) + ' %' + '\n')
f.write('Battery level is: ' + str(self.b) + '%' + '\n')
f.write('Economy Level is: ' + str(self.eco) + '\n')
f.close()
else:
self.eco_level_txt.setNum(self.eco)
self.run_eco_level.setNum(self.eco)
filename1 = datetime.datetime.now().strftime("%Y.%m.%d_%H:%M")
save_path = 'Logs/'
complete_path = os.path.join(save_path, filename1+'.txt')
f = open(complete_path, 'w')
if (self.t == 0) or (self.c == 0) or (self.b == 0):
f.write('Data Unavailable, running in economy level 1')
else:
f.write('Average Temperature is: ' + str(self.t) + ' °C' + '\n')
f.write('Average Cloud Cover is: ' + str(self.c) + ' %' + '\n')
f.write('Battery level is: ' + str(self.b) + ' % ' + '\n')
f.write('Economy Level is: ' + str(self.eco) + '\n')
f.close()
def Room_cond(self):
if ser.isOpen():
ser.close()
ser.open()
ser.isOpen()
ser.write('s'.encode())
time.sleep(2)
response = ser.readline().strip().decode()
hum = float(response[:5])
temp = float(response[5:])
f = open('Ubidots_APIkey.txt', 'r')
apikey = f.readline().strip()
f.close()
api = ApiClient(token = apikey)
try:
roomtemp = api.get_variable("58d763b8762542260a851bd1")
roomhumidity = api.get_variable("58d763c57625422609b8d088")
except ValueError:
print('Unable to obtain variable')
self.roomt = temp
self.roomh = hum
try:
roomtemp.save_value({'value': self.roomt})
roomhumidity.save_value({'value': self.roomh})
time.sleep(1)
except:
pass
self.room_temp_txt.setText(format(self.roomt,'.2f'))
self.room_hum_txt.setText(format(self.roomh,'.2f'))
def Room_temp_browser(self):
webbrowser.open('https://app.ubidots.com/ubi/getchart/page/G284654CCK1E77kbBR7zmpBDNkw', new = 2)
def Room_hum_browser(self):
webbrowser.open('https://app.ubidots.com/ubi/getchart/page/qgaJ95jUNq91E3aVxJsNo7NphbU', new = 2)
def Run_System(self):
f = open('Ubidots_APIkey.txt', 'r')
apikey = f.readline().strip()
f.close()
api = ApiClient(token = apikey)
self.cooler_on.setText(' ')
self.heater_on.setText(' ')
self.humid_on.setText(' ')
self.dehumid_on.setText(' ')
self.cooler_off.setText(' ')
self.heater_off.setText(' ')
self.humid_off.setText(' ')
self.dehumid_off.setText(' ')
self.Room_cond()
try:
cooler = api.get_variable("58d768e0762542260a855c7a")
heater = api.get_variable("58d768eb7625422609b91152")
humidifier = api.get_variable("58d768f8762542260cf3b292")
exhaust = api.get_variable("58d76907762542260dfad769")
except ValueError:
print('Unable to obtain variable')
cooler.save_value({'value': 0})
heater.save_value({'value': 0})
humidifier.save_value({'value': 0})
exhaust.save_value({'value': 0})
if (self.eco < 1):
self.run_eco_level.setText('--')
elif (self.eco == 1):
t = self.roomt
h = self.roomh
if (t >= 35):
ser.write('c'.encode())
self.cooler_on.setText('ON')
self.heater_off.setText('OFF')
cooler.save_value({'value': 1})
heater.save_value({'value': 0})
time.sleep(1)
if (t <= 15):
ser.write('f'.encode())
self.heater_on.setText('ON')
self.cooler_off.setText('OFF')
heater.save_value({'value': 1})
cooler.save_value({'value': 0})
time.sleep(1)
if (h <= 25):
ser.write('h'.encode())
self.humid_on.setText('ON')
self.dehumid_off.setText('OFF')
humidifier.save_value({'value': 1})
exhaust.save_value({'value': 0})
time.sleep(1)
if (h >= 80):
ser.write('e'.encode())
self.dehumid_on.setText('ON')
self.humid_off.setText('OFF')
exhaust.save_value({'value': 1})
humidifier.save_value({'value': 0})
time.sleep(1)
if ((h > 25 and h < 80)):
self.humid_off.setText('OFF')
self.dehumid_off.setText('OFF')
humidifier.save_value({'value': 0})
exhaust.save_value({'value': 0})
time.sleep(1)
if ((t > 15) and (t < 35)):
self.cooler_off.setText('OFF')
self.heater_off.setText('OFF')
cooler.save_value({'value': 0})
heater.save_value({'value': 0})
time.sleep(1)
elif (self.eco == 2):
t = self.roomt
h = self.roomh
if (t >= 32):
ser.write('c'.encode())
self.cooler_on.setText('ON')
self.heater_off.setText('OFF')
cooler.save_value({'value': 1})
heater.save_value({'value': 0})
time.sleep(1)
if (t <= 18):
ser.write('f'.encode())
self.heater_on.setText('ON')
self.cooler_off.setText('OFF')
heater.save_value({'value': 1})
cooler.save_value({'value': 0})
time.sleep(1)
if (h <= 30):
ser.write('h'.encode())
self.humid_on.setText('ON')
self.dehumid_off.setText('OFF')
humidifier.save_value({'value': 1})
exhaust.save_value({'value': 0})
time.sleep(1)
if (h >= 70):
ser.write('e'.encode())
self.dehumid_on.setText('ON')
self.humid_off.setText('OFF')
exhaust.save_value({'value': 1})
humidifier.save_value({'value': 0})
time.sleep(1)
if ((h > 30 and h < 70)):
self.humid_off.setText('OFF')
self.dehumid_off.setText('OFF')
exhaust.save_value({'value': 0})
humidifier.save_value({'value': 0})
time.sleep(1)
if ((t > 18) and (t < 32)):
self.cooler_off.setText('OFF')
self.heater_off.setText('OFF')
cooler.save_value({'value': 0})
heater.save_value({'value': 0})
time.sleep(1)
elif (self.eco == 3):
t = self.roomt
h = self.roomh
if (t >= 30):
ser.write('c'.encode())
self.cooler_on.setText('ON')
self.heater_off.setText('OFF')
cooler.save_value({'value': 1})
heater.save_value({'value': 0})
time.sleep(1)
if (t <= 20):
ser.write('f'.encode())
self.heater_on.setText('ON')
self.cooler_off.setText('OFF')
heater.save_value({'value': 1})
cooler.save_value({'value': 0})
time.sleep(1)
if (h <= 40):
ser.write('h'.encode())
self.humid_on.setText('ON')
self.dehumid_off.setText('OFF')
humidifier.save_value({'value': 1})
exhaust.save_value({'value': 0})
time.sleep(1)
if (h >= 60):
ser.write('e'.encode())
self.dehumid_on.setText('ON')
self.humid_off.setText('OFF')
exhaust.save_value({'value': 1})
humidifier.save_value({'value': 0})
time.sleep(1)
if ((h > 40 and h < 60)):
self.humid_off.setText('OFF')
self.dehumid_off.setText('OFF')
exhaust.save_value({'value': 0})
humidifier.save_value({'value': 0})
time.sleep(1)
if ((t > 20) and (t < 30)):
self.cooler_off.setText('OFF')
self.heater_off.setText('OFF')
cooler.save_value({'value': 0})
heater.save_value({'value': 0})
time.sleep(1)
elif (self.eco == 4):
t = self.roomt
h = self.roomh
if (t >= 27):
ser.write('c'.encode())
self.cooler_on.setText('ON')
self.heater_off.setText('OFF')
cooler.save_value({'value': 1})
heater.save_value({'value': 0})
time.sleep(1)
if (t <= 22):
ser.write('f'.encode())
self.heater_on.setText('ON')
self.cooler_off.setText('OFF')
heater.save_value({'value': 1})
cooler.save_value({'value': 0})
time.sleep(1)
if (h <= 25):
ser.write('h'.encode())
self.humid_on.setText('ON')
self.dehumid_off.setText('OFF')
humidifier.save_value({'value': 1})
exhaust.save_value({'value': 0})
time.sleep(1)
if (h >= 50):
ser.write('e'.encode())
self.dehumid_on.setText('ON')
self.humid_off.setText('OFF')
exhaust.save_value({'value': 1})
humidifier.save_value({'value': 0})
time.sleep(1)
if ((h > 25) and (h < 50)):
self.humid_off.setText('OFF')
self.dehumid_off.setText('OFF')
exhaust.save_value({'value': 0})
humidifier.save_value({'value': 0})
time.sleep(1)
if ((t > 22) and (t < 27)):
self.cooler_off.setText('OFF')
self.heater_off.setText('OFF')
cooler.save_value({'value': 0})
heater.save_value({'value': 0})
time.sleep(1)
def Open_ubidots(self):
webbrowser.open('https://app.ubidots.com/ubi/public/getdashboard/page/P8OAd8cR6dtoL6aO4AQ384euynE', new = 2)
import system_rc
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
system = QtWidgets.QToolBox()
ui = Ui_system()
ui.setupUi(system)
system.move(QApplication.desktop().screen().rect().center() - system.rect().center())
system.show()
sys.exit(app.exec_())
|
kunz07/fyp2017
|
Ubidots-Finaltest.py
|
<filename>Ubidots-Finaltest.py
# FYP2017
# Program to establish ZigBee communication between raspberry Pi and arduino
# Complete control of HVAC elements based on commands sent from the Pi
# Author: <NAME>
# License: Public Domain
import time
import serial
from ubidots import ApiClient
one = 1
zero = 0
f = open('Ubidots_APIkey.txt', 'r')
apikey = f.readline().strip()
f.close()
api = ApiClient(token = apikey)
try:
roomtemp = api.get_variable("58d763b8762542260a851bd1")
roomhumidity = api.get_variable("58d763c57625422609b8d088")
cooler = api.get_variable("58d768e0762542260a855c7a")
heater = api.get_variable("58d768eb7625422609b91152")
humidifier = api.get_variable("58d768f8762542260cf3b292")
exhaust = api.get_variable("58d76907762542260dfad769")
except ValueError:
print('Unable to obtain variable')
cooler.save_value({'value': 0})
heater.save_value({'value': 0})
humidifier.save_value({'value': 0})
exhaust.save_value({'value': 0})
hour = 3600
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
def getSensorData():
if ser.isOpen():
ser.close()
ser.open()
ser.isOpen()
ser.write('s'.encode())
time.sleep(2)
response = ser.readline().strip().decode()
hum = float(response[:5])
temp = float(response[5:])
try:
roomtemp.save_value({'value': temp})
roomhumidity.save_value({'value': hum})
print('Value',temp,'and',hum, 'sent')
time.sleep(2)
except:
print('Value not sent')
return (hum, temp)
def level_1():
h, t = getSensorData()
if (t > 35):
cooler.save_value({'value': one})
time.sleep(2)
if (t < 15):
heater.save_value({'value': one})
time.sleep(2)
if (h < 25):
humidifier.save_value({'value': one})
time.sleep(2)
if (h > 80):
exhaust.save_value({'value': one})
time.sleep(2)
time.sleep(10)
cooler.save_value({'value': 0})
heater.save_value({'value': 0})
humidifier.save_value({'value': 0})
exhaust.save_value({'value': 0})
def level_2():
h, t = getSensorData()
if (t > 32):
cooler.save_value({'value': one})
time.sleep(2)
if (t < 18):
heater.save_value({'value': one})
time.sleep(2)
if (h < 30):
humidifier.save_value({'value': one})
time.sleep(2)
if (h > 70):
exhaust.save_value({'value': one})
time.sleep(2)
time.sleep(10)
cooler.save_value({'value': 0})
heater.save_value({'value': 0})
humidifier.save_value({'value': 0})
exhaust.save_value({'value': 0})
def level_3():
h, t = getSensorData()
if (t > 30):
cooler.save_value({'value': one})
time.sleep(2)
if (t < 20):
heater.save_value({'value': one})
time.sleep(2)
if (h < 40):
humidifier.save_value({'value': one})
time.sleep(2)
if (h > 60):
exhaust.save_value({'value': one})
time.sleep(2)
time.sleep(10)
cooler.save_value({'value': 0})
heater.save_value({'value': 0})
humidifier.save_value({'value': 0})
exhaust.save_value({'value': 0})
def level_4():
h, t = getSensorData()
if (t > 27):
cooler.save_value({'value': one})
time.sleep(2)
if (t < 22):
heater.save_value({'value': one})
time.sleep(2)
if (h < 25):
humidifier.save_value({'value': one})
time.sleep(2)
if (h > 30):
exhaust.save_value({'value': one})
time.sleep(2)
time.sleep(10)
cooler.save_value({'value': 0})
heater.save_value({'value': 0})
humidifier.save_value({'value': 0})
exhaust.save_value({'value': 0})
def getLevel():
return 4
if __name__ == "__main__":
level = getLevel()
while True:
if (level == 1):
level_1()
elif (level == 2):
level_2()
elif (level == 3):
level_3()
elif (level == 4):
level_4()
else:
ser.write('x'.encode())
break
|
kunz07/fyp2017
|
Ubidots-Battery.py
|
# FYP2017
# Program to send battery status to ThingSpeak channel
# Author: <NAME>
# License: Public Domain
import time
import sys
from ubidots import ApiClient
f = open('Ubidots_APIkey.txt', 'r')
apikey = f.readline().strip()
f.close()
api = ApiClient(token = apikey)
try:
variable1 = api.get_variable("58d763aa762542260cf36f24")
except ValueError:
print('Unable to obtain variable')
def sendBattery(x):
try:
batt = x
variable1.save_value({'value': batt})
print('Value ',batt, ' sent')
time.sleep(2)
except:
print('Value not sent')
if __name__ == "__main__":
x = 40
while True:
sendBattery(x)
x = x - 5
time.sleep(5)
if x < 5:
break
|
kunz07/fyp2017
|
RoomIOT.py
|
<reponame>kunz07/fyp2017
# FYP2017
# Program to send room temperature and humidity to ThingSpeak
# Author: <NAME>
# License: Public Domain
import time
import serial
import sys
import urllib.request
import urllib.parse
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
def sendData():
if ser.isOpen():
ser.close()
ser.open()
ser.isOpen()
ser.write('s'.encode())
time.sleep(2)
response = ser.readline().strip().decode()
hum = float(response[:5])
temp = float(response[5:])
# Send to ThingSpeak
f = open('TS_APIkey.txt','r')
api_key = f.read()
params = urllib.parse.urlencode({'key': api_key ,
'field4': temp ,
'field5': hum
})
params = params.encode('utf-8')
fh = urllib.request.urlopen("https://api.thingspeak.com/update", data=params)
fh.close()
if __name__ == "__main__":
while True:
sendData()
time.sleep(300)
|
mbarnaba/numerical-analysis-2021-2022
|
main.py
|
import numpy as np
from matplotlib import pyplot as plt
'''
Implement a function that given the domain interval, the forcing function, the number of discretization points,
the boundary conditions, returns the matrix and the the right hand side b.
'''
def finDif(omega, f, n, bc):
span = omega[ -1 ] - omega[ 0 ]
delta = span / ( n - 1 )
# A's diagonals
diags = [
30 * np.ones( (n,) ),
-16 * np.ones( (n - 1,) ),
np.ones( (n - 2,) )
]
A = np.diag( diags[ 0 ], 0 ) \
+ np.diag( diags[ 1 ], -1 ) \
+ np.diag( diags[ 1 ], 1 ) \
+ np.diag( diags[ 2 ], -2 ) \
+ np.diag( diags[ 2 ], 2 )
A /= (12 * delta**2)
x = np.linspace( omega[ 0 ], omega[ -1 ], n )
b = f( x )
# boundary conditions
A[ 0, : ] = 0
A[ :, 0 ] = 0
A[ 0, 0 ] = 1
b[ 0 ] = bc[ 0 ]
A[ -1, : ] = 0
A[ :, -1 ] = 0
A[ -1, -1 ] = 1
b[ -1 ] = bc[ -1 ]
return (A, b)
omega = [ 0, np.pi ]
f = lambda x : np.sin(x)
n = 100
bc = [ 0, 0 ]
(A, b) = finDif( omega, f, n, bc )
print(A)
print(b)
'''
Implement two functions that compute the LU and the Cholesky factorization of the system matrix A
'''
def LU(A, tol=1e-15):
A = A.copy()
size = len( A )
for k in range(size - 1):
pivot = A[ k, k ]
if abs(pivot) < tol:
raise RuntimeError("Null pivot")
for j in range( k + 1, size ):
A[ j, k ] /= pivot
for j in range( k + 1, size ):
A[ k + 1 : size, j ] -= A[ k + 1 : size, k ] * A[ k, j ]
L = np.tril( A )
for i in range( size ):
L[ i, i ] = 1.0
U = np.triu( A )
return (L, U)
(L, U) = LU( A )
print(L, U)
def cholesky(A):
A = A.copy()
size = len( A )
for k in range( size - 1 ):
A[ k, k ] = np.sqrt(A[ k, k ])
A[ k + 1 : size, k ] = A[ k + 1 : size, k ] / A[ k, k ]
for j in range(k+1,size):
A[ j : size, j ] = A[ j : size, j ] - A[ j : size, k ] * A[ j, k ]
A[ -1, -1 ] = np.sqrt(A[ -1, -1 ])
L = np.tril( A )
Lt = L.transpose()
return (L, Lt)
(Ht, H) = cholesky( A )
print(Ht, H)
# Implement forward and backward substitution functions to exploit the developed factorization methods to solve the
# derived linear system of equations.
def L_solve(L, rhs):
size = len( L )
x = np.zeros( size )
x[ 0 ] = rhs[ 0 ] / L[ 0, 0 ]
for i in range( 1, size ):
x[ i ] = ( rhs[ i ] - np.dot( L[ i, 0 : i ], x[ 0 : i ] ) ) / L[ i, i ]
return x
def U_solve(U, rhs):
size = len( U )
x = np.zeros( size )
x[ -1 ] = rhs[ -1 ] / L[ -1, -1 ]
for i in reversed( range( size - 1 ) ):
x[ i ] = ( rhs[ i ] - np.dot( U[ i, i + 1 : size ], x[ i + 1 : size ] ) ) / U[ i, i ]
return x
'''
Solve the derived linear system using the implemented functions and plot the computed solution:
'''
(fig, ax) = plt.subplots()
# exact solution
x = np.linspace( omega[0], omega[-1], n)
u_exact = np.sin( x )
ax.plot( x, u_exact, label = 'exact' )
# using LU factorization
w = L_solve( L, b )
u = U_solve( U, w )
ax.plot( x, u, label = 'lu' )
# using cholesky factorizations
w = L_solve( Ht, b )
u = U_solve( H, w )
ax.plot( x, u, label = 'cholesky' )
ax.legend()
ax.grid()
fig.savefig( 'plot1.svg' )
'''
Considering the new domain [0, 1] and the forcing term with B.C. ,
on produce a plot and a table where you show the decay of the error w.r.t. the number of grid points.
(The analytical solution for the above problems is )
'''
def compute_errors(omega, f, fex, bc, npoints):
errors = []
for idx in range( len(npoints) ):
npts = npoints[ idx ]
x = np.linspace( omega[0], omega[1], npts )
ex = fex( x )
( A, b ) = finDif( omega, f, npts, bc )
( L, U ) = LU( A )
w = L_solve( L, b )
u = U_solve( U, w )
err = sum( ( ex - u )**2 )**0.5
errors.append( err )
return errors
omega = [ 0, 1 ]
def func(x):
return x * (1 - x)
def fex(x):
return x**4/12 - x**3/6 + x/12
bc = [ 0, 0 ]
npoints = np.arange( 10, 310, 10 )
errors = compute_errors( omega, func, fex, bc, npoints )
(fig, ax) = plt.subplots()
ax.set_yscale( 'log' )
ax.plot( npoints, errors )
fig.savefig( 'plot2.svg' )
'''
Exploit the derived LU factorizations to compute the condition number of the system's matrix using the original problem formulation.
'''
def PM(A, z0, tol=1e-12, nmax=10000):
q = z0 / np.linalg.norm( z0, 2 )
it = 0
err = tol + 1
while it < nmax and err > tol:
z = A.dot( q )
l = q.T.dot( z )
err = np.linalg.norm( z - l*q, 2 )
q = z / np.linalg.norm( z, 2 )
it = it + 1
return (l, q)
def IPM(A, x0, mu, eps=1.0e-12, nmax=10000):
M = A - mu * np.eye(len(A))
(L, U) = LU( M )
q = x0 / np.linalg.norm( x0, 2 )
err = eps + 1.0
it = 0
while err > eps and it < nmax:
y = L_solve( L, q )
x = U_solve( U, y )
q = x / np.linalg.norm( x, 2 )
z = A.dot( q )
l = q.T.dot( z )
err = np.linalg.norm( z - l*q, 2 )
it = it + 1
return (l, q)
def condNumb(A):
z0 = np.ones( ( len(A), ))
lmax = PM( A, z0 )[ 0 ]
lmin = IPM( A, z0, 0.0 )[ 0 ]
condNum = lmax / lmin
return condNum
condNum = condNumb( A )
print( condNum )
'''
Implement a preconditioned Conjugant Gradient method to solve the original linear system of equations using an iterative method:
'''
def conjugate_gradient(A, b, P, nmax=len(A), eps=1e-10):
x = np.zeros_like( b )
r = b - A.dot( x )
rho0 = 1
p0 = np.zeros_like( b )
err = eps + 1.0
it = 1
while it < nmax and err > eps:
z = np.linalg.solve( P, r )
rho = r.dot( z )
if it > 1:
beta = rho / rho0
p = z + beta * p0
else:
p = z
q = A.dot( p )
alpha = rho / p.dot( q )
x += p * alpha
r -= q * alpha
p0 = p
rho0 = rho
err = np.linalg.norm( r, 2 )
it = it + 1
print( f'iterations: {it}' )
print( f'error: {err}' )
return x
omega = [ 0, np.pi ]
x = np.linspace( omega[ 0 ], omega[ -1 ], n )
ex = np.sin( x )
u = conjugate_gradient( A, b, np.diag(np.diag( A ) ))
(fig, ax) = plt.subplots()
ax.plot( x, ex, label = 'exact' )
ax.plot( x, u, label = 'CG' )
ax.legend()
fig.savefig( 'plot3.svg' )
exit( 0 )
'''
Consider the following time dependent variation of the PDE starting from the orginal problem formulation:
for , with and
Use the same finite difference scheme to derive the semi-discrete formulation and solve it using a forward Euler's method.
Plot the time dependent solution solution at , ,
'''
#TODO
'''
Given the original system, implement an algorithm to compute the eigenvalues and eigenvectors of the matrix .
oExploit the computed LU factorization
'''
#TODO
'''
Compute the inverse of the matrix A exploiting the derived LU factorization
'''
#TODO
'''
Consider the following Cauchy problem
Implement a Backward Euler's method in a suitable function and solve the resulting non-linear equation using a Newton's method.
'''
#TODO
|
jmtroll/my-resume2
|
manage.py
|
from flask_script import Manager
from myResume2 import app, db, Professor, Course
manager = Manager(app)
# reset the database and create some initial data
@manager.command
def deploy():
db.drop_all()
db.create_all()
p1 = Professor(name='Hartono', department='MIS')
p2 = Professor(name='Harry', department='MIS')
p3 = Professor(name='Robin', department='ENTI')
course1 = Course(course_number='MISY225', title='Introduction to Programming Business Applications', description="Use of higher level contemporary computing languages to structure Prototyping applications of systems. PREREQ: MISY160", professor=p1)
course2 = Course(course_number='MISY350', title='Business Application Development II', description="This course Covers concepts related to client side development. PREREQ: MISY225", professor=p2)
course3 = Course(course_number='ENTR458', title='App Development for New Technology', description="Presents frameworks for developing commercially feasible applications of new technology.", professor=p3)
db.session.add(p1)
db.session.add(p2)
db.session.add(p3)
db.session.add(course1)
db.session.add(course2)
db.session.add(course3)
db.session.commit()
if __name__ == "__main__":
manager.run()
|
ahelmy/weather2tts-raspi
|
temp.py
|
#!/usr/bin/env python
import logging.handlers
import os
import json
API_KEY = ''
LONG_LAT = '26.2172,50.1971'
PATH = "temp.log"
handler = logging.handlers.WatchedFileHandler(
os.environ.get("LOGFILE", PATH))
formatter = logging.Formatter(logging.BASIC_FORMAT)
handler.setFormatter(formatter)
root = logging.getLogger()
root.setLevel(os.environ.get("LOGLEVEL", "INFO"))
root.addHandler(handler)
logging.info('<<<START>>>')
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
def F2C(f):
c = (f - 32) * 5.0/9.0
return c
def getTTSNumber(num):
if len(num) >= 2:
num = num[0] +'0'+ ' '+num[1]
elif len(num) == 1:
num = num[0] + '0'
return num
url = 'https://api.darksky.net/forecast/' + API_KEY + '/' + LONG_LAT
logging.info('Opening url : [{0}]...'.format(url))
response = urlopen(url)
logging.info('Url opened')
logging.info('Parsing data...')
data = response.read().decode('utf-8')
json = json.loads(data)
current = json['currently']
logging.debug('Data => {0}'.format(current))
hum = str(int(float(current['humidity']) * 100))
temp = round(F2C(current['temperature']))
temp = str(int(temp))
logging.info('Temperature = {0}, Humidity = {1}'.format(temp,hum))
print("Temp: "+temp +", Humidity: "+hum)
#temp = getTTSNumber(temp)
#hum = getTTSNumber(hum)
#print('TTS Temp: ' +temp+", Humidity: "+hum)
print('Calling Festival tts...')
logging.info('Calling festival tts...')
try:
os.system('echo "Temperature is: ' + temp + ' Degree. Humidity is: ' + hum + ' ." | festival --tts')
logging.info('TTS called.')
except Exception as e:
logging.error('Failed to call festival tts',exc_info=True)
logging.info('<<<END>>>')
print('Have a nice day :)')
|
datablane/QuantEcon.py
|
quantecon/distributions.py
|
<gh_stars>0
"""
Probability distributions useful in economics.
References
----------
http://en.wikipedia.org/wiki/Beta-binomial_distribution
"""
from math import sqrt
import numpy as np
from scipy.special import binom, beta
class BetaBinomial:
"""
The Beta-Binomial distribution
Parameters
----------
n : scalar(int)
First parameter to the Beta-binomial distribution
a : scalar(float)
Second parameter to the Beta-binomial distribution
b : scalar(float)
Third parameter to the Beta-binomial distribution
Attributes
----------
n, a, b : see Parameters
"""
def __init__(self, n, a, b):
self.n, self.a, self.b = n, a, b
@property
def mean(self):
"mean"
n, a, b = self.n, self.a, self.b
return n * a / (a + b)
@property
def std(self):
"standard deviation"
return sqrt(self.var)
@property
def var(self):
"Variance"
n, a, b = self.n, self.a, self.b
top = n*a*b * (a + b + n)
btm = (a+b)**2.0 * (a+b+1.0)
return top / btm
@property
def skew(self):
"skewness"
n, a, b = self.n, self.a, self.b
t1 = (a+b+2*n) * (b - a) / (a+b+2)
t2 = sqrt((1+a+b) / (n*a*b * (n+a+b)))
return t1 * t2
def pdf(self):
r"""
Generate the vector of probabilities for the Beta-binomial
(n, a, b) distribution.
The Beta-binomial distribution takes the form
.. math::
p(k \,|\, n, a, b) =
{n \choose k} \frac{B(k + a, n - k + b)}{B(a, b)},
\qquad k = 0, \ldots, n,
where :math:`B` is the beta function.
Parameters
----------
n : scalar(int)
First parameter to the Beta-binomial distribution
a : scalar(float)
Second parameter to the Beta-binomial distribution
b : scalar(float)
Third parameter to the Beta-binomial distribution
Returns
-------
probs: array_like(float)
Vector of probabilities over k
"""
n, a, b = self.n, self.a, self.b
k = np.arange(n + 1)
probs = binom(n, k) * beta(k + a, n - k + b) / beta(a, b)
return probs
# def cdf(self):
# r"""
# Generate the vector of cumulative probabilities for the
# Beta-binomial(n, a, b) distribution.
# The cdf of the Beta-binomial distribution takes the form
# .. math::
# P(k \,|\, n, a, b) = 1 -
# \frac{B(b+n-k-1, a+k+1) {}_3F_2(a,b;k)}{B(a,b) B(n-k, k+2)},
# \qquad k = 0, \ldots, n
# where :math:`B` is the beta function.
# Parameters
# ----------
# n : scalar(int)
# First parameter to the Beta-binomial distribution
# a : scalar(float)
# Second parameter to the Beta-binomial distribution
# b : scalar(float)
# Third parameter to the Beta-binomial distribution
# Returns
# -------
# probs: array_like(float)
# Vector of probabilities over k
# """
|
Lagg/steam-swissapiknife
|
steamswissapiknife/main.py
|
#!/usr/bin/env python
"""steam-swissapiknife
see README.md"""
# Python 2 <-> 3 glue
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
import json, sys
import argparse
def parse_args(args):
"""Parse command line arguments"""
cmdline = argparse.ArgumentParser(description="Carve up some API docs in list or wiki format")
cmdline.add_argument(
"key",
help="Your API key")
cmdline.add_argument(
"-f",
"--format",
choices=["list", "wiki"],
default="list",
help="Print out API docs in condensed list form or wikitext")
cmdline.add_argument(
"-i",
"--interface",
default=None,
help="Only print methods in this interface")
cmdline.add_argument(
"-m",
"--method",
default=None,
help="Only print methods with this name")
return cmdline.parse_args(args)
def main(opts=None):
"""Main entry point"""
opts = opts or parse_args(sys.argv[1:])
key = opts.key
request_url = "http://api.steampowered.com/ISteamWebAPIUtil/GetSupportedAPIList/v0001/?key=" + key
url_root = "http://api.steampowered.com/"
apilist = json.loads(urlopen(request_url).read().decode("utf-8"))
api_names = []
api_methods = {}
mw_skeleton = (opts.format == "wiki")
for api in apilist["apilist"]["interfaces"]:
api_names.append(api["name"])
api_methods[api["name"]] = api["methods"]
api_names.sort()
for api in api_names:
if opts.interface and api != opts.interface:
continue
methods = api_methods[api]
for method in methods:
param_doc_lines = []
if opts.method and method["name"] != opts.method:
continue
querypart = ["key=" + key]
for param in method["parameters"]:
name = param["name"]
ptype = param["type"]
optional = param["optional"]
desc = param.get("description", '')
ptypewrapper = "<{1}>"
if optional:
ptypewrapper = "[{1}]"
if name != "key":
querypart.append(("{0}=" + ptypewrapper).format(name, ptype))
if mw_skeleton:
if optional:
name = "{{API optional|" + name + "}}"
param_doc_lines.append(";{0} ''({1})'': {2}".format(name, ptype, desc))
else:
param_doc_lines.append(name + ": " + desc)
fullurl = url_root + api + '/' + method["name"] + '/v' + str(method["version"])
if mw_skeleton:
print("Page URL: http://wiki.teamfortress.com/wiki/WebAPI/{0}\n".format(method["name"]))
print("== URL ==\n<nowiki>{1} {0}</nowiki>\n\n== Method-specific parameters ==".format(fullurl, method["httpmethod"]))
else:
print(method["httpmethod"] + ' ' + fullurl + '?' + "&".join(querypart))
print('\n'.join(param_doc_lines))
if mw_skeleton:
print("\n== Result data ==\n")
print('\n')
if __name__ == "__main__":
main()
|
Lagg/steam-swissapiknife
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name='steam-swissapiknife',
version='0.1',
description='A tool to explore the Steam API.',
url='https://github.com/Lagg/steam-swissapiknife',
author='Lagg',
author_email='<EMAIL>',
license='ISC',
packages=['steamswissapiknife'],
test_suite='nose.collector',
tests_require=['nose'],
keywords=['Steam', 'WebAPI'],
classifiers = [
"License :: OSI Approved :: ISC License (ISCL)",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python"
],
entry_points={
'console_scripts': [
'steamswissapiknife = steamswissapiknife.main:main',
],
},
)
|
Lagg/steam-swissapiknife
|
steamswissapiknife/tests/test_all.py
|
#!/usr/bin/env python
"""steam-swissapiknife test suite"""
from steamswissapiknife import main
import unittest
import os
from contextlib import contextmanager
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
key = os.environ['STEAM_API_KEY']
@contextmanager
def captured_output():
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
def test_interface_wiki_output():
parser = main.parse_args(['-f', 'wiki', '-i', 'ITFItems_440', key])
expected = """Page URL: http://wiki.teamfortress.com/wiki/WebAPI/GetGoldenWrenches
== URL ==
<nowiki>GET http://api.steampowered.com/ITFItems_440/GetGoldenWrenches/v2</nowiki>
== Method-specific parameters ==
== Result data =="""
with captured_output() as (out, err):
main.main(parser)
output = out.getvalue().strip()
assert(output == expected)
def test_interface_list_output():
parser = main.parse_args(['-f', 'list', '-i', 'ITFItems_440', key])
expected = """GET http://api.steampowered.com/ITFItems_440/GetGoldenWrenches/v2?key=%s""" % (key)
with captured_output() as (out, err):
main.main(parser)
output = out.getvalue().strip()
assert(output == expected)
def test_method_wiki_output():
parser = main.parse_args(['-f', 'wiki', '-m', 'GetGoldenWrenches', key])
expected = """Page URL: http://wiki.teamfortress.com/wiki/WebAPI/GetGoldenWrenches
== URL ==
<nowiki>GET http://api.steampowered.com/ITFItems_440/GetGoldenWrenches/v2</nowiki>
== Method-specific parameters ==
== Result data =="""
with captured_output() as (out, err):
main.main(parser)
output = out.getvalue().strip()
assert(output == expected)
def test_method_list_output():
parser = main.parse_args(['-m', 'GetGoldenWrenches', key])
expected = """GET http://api.steampowered.com/ITFItems_440/GetGoldenWrenches/v2?key=%s""" % (key)
with captured_output() as (out, err):
main.main(parser)
output = out.getvalue().strip()
assert(output == expected)
|
nairraghav/tkinter-example
|
app.py
|
import tkinter as tk
# create window
root = tk.Tk()
# creates a frame within our window
top_frame = tk.Frame(root)
top_frame.pack()
bottom_frame = tk.Frame(root)
bottom_frame.pack(side=tk.BOTTOM)
first_buttom = tk.Button(top_frame, text='Login', fg='red')
second_buttom = tk.Button(top_frame, text='Forgot Username', fg='orange')
third_buttom = tk.Button(bottom_frame, text='Register', fg='blue')
fourth_buttom = tk.Button(bottom_frame, text='Forgot Password', fg='green')
first_buttom.pack(side=tk.LEFT)
second_buttom.pack(side=tk.RIGHT)
third_buttom.pack(side=tk.LEFT)
fourth_buttom.pack(side=tk.RIGHT)
# create some sample text to put on window
# sample_text = tk.Label(root, text='Sample Text')
# essentially runs a while loop so the program stays open forever
root.mainloop()
|
AspirinCode/Compound_Protein_Interaction_Prediction
|
code/preprocess_data.py
|
<filename>code/preprocess_data.py<gh_stars>0
from collections import defaultdict
import os
import pickle
import sys
import numpy as np
from rdkit import Chem
def create_atoms(mol):
atoms = [atom_dict[a.GetSymbol()] for a in mol.GetAtoms()]
return np.array(atoms)
def create_adjacency(mol):
adjacency = Chem.GetAdjacencyMatrix(mol)
return np.array(adjacency)
def create_ijbonddict(mol):
i_jbond_dict = defaultdict(lambda: [])
for b in mol.GetBonds():
i, j = b.GetBeginAtomIdx(), b.GetEndAtomIdx()
bond = bond_dict[str(b.GetBondType())]
i_jbond_dict[i].append((j, bond))
i_jbond_dict[j].append((i, bond))
return i_jbond_dict
def create_fingerprints(atoms, i_jbond_dict, radius):
"""Extract the r-radius subgraphs (i.e., fingerprints)
from a molecular graph using WeisfeilerLehman-like algorithm."""
if (len(atoms) == 1) or (radius == 0):
return np.array(atoms)
else:
vertices = atoms
for _ in range(radius):
fingerprints = []
for i, j_bond in i_jbond_dict.items():
neighbors = [(vertices[j], bond) for j, bond in j_bond]
fingerprint = (vertices[i], tuple(sorted(neighbors)))
fingerprints.append(fingerprint_dict[fingerprint])
vertices = fingerprints
return np.array(fingerprints)
def split_sequence(sequence, ngram):
words = [word_dict[sequence[i:i+ngram]]
for i in range(len(sequence)-ngram+1)]
return np.array(words)
def pickle_dump(dictionary, file_name):
with open(file_name, 'wb') as f:
pickle.dump(dict(dictionary), f)
if __name__ == "__main__":
DATASET, radius, ngram = sys.argv[1:]
radius, ngram = map(int, [radius, ngram])
with open('../dataset/' + DATASET +
'/original/smiles_sequence_interaction.txt', 'r') as f:
data_list = f.read().strip().split('\n')
N = len(data_list)
atom_dict = defaultdict(lambda: len(atom_dict))
bond_dict = defaultdict(lambda: len(bond_dict))
fingerprint_dict = defaultdict(lambda: len(fingerprint_dict))
word_dict = defaultdict(lambda: len(word_dict))
Compounds, Adjacencies, Proteins, Interactions = [], [], [], []
for no, data in enumerate(data_list):
smiles, sequence, interaction = data.strip().split()
"""We exclude the data including '.' in the smiles."""
if ('.' not in smiles):
print('/'.join(map(str, [no, N])))
"""Atoms in the compound."""
mol = Chem.MolFromSmiles(smiles)
atoms = create_atoms(mol)
"""Bonds between atoms in the compound."""
i_jbond_dict = create_ijbonddict(mol)
"""Fingerprints (i.e., r-radius subgraphs) in the compound."""
fingerprints = create_fingerprints(atoms, i_jbond_dict, radius)
Compounds.append(fingerprints)
"""Adjacency matrix of the compound."""
adjacency = create_adjacency(mol)
Adjacencies.append(adjacency)
"""n-gram words in the protein."""
words = split_sequence(sequence, ngram)
Proteins.append(words)
"""Label (interact=1 or not=0) of the compound-protein pair."""
interaction = np.array([int(interaction)])
Interactions.append(interaction)
if (radius == 0):
fingerprint_dict = atom_dict
"""Save each data."""
radius, ngram = str(radius), str(ngram)
dir_input = ('../dataset/' + DATASET + '/input/radius' +
radius + '_ngram' + ngram + '/')
if not os.path.isdir(dir_input):
os.mkdir(dir_input)
np.save(dir_input + 'compounds', Compounds)
np.save(dir_input + 'adjacencies', Adjacencies)
np.save(dir_input + 'proteins', Proteins)
np.save(dir_input + 'interactions', Interactions)
pickle_dump(fingerprint_dict, dir_input + 'fingerprint_dict' + '.pickle')
pickle_dump(word_dict, dir_input + 'word_dict' + '.pickle')
print('-'*30)
print('The preprocess has finished! '
'Information of the data is as follows.')
print('Dataset: ', DATASET)
print('Radius: ', radius)
print('N-gram: ', ngram)
print('The number of fingerprints: ', len(fingerprint_dict))
print('The number of n-gram: ', len(word_dict))
print('-'*30)
|
AspirinCode/Compound_Protein_Interaction_Prediction
|
code/run_training.py
|
from collections import defaultdict
import pickle
import sys
import timeit
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics import roc_auc_score, precision_score, recall_score
class CompoundProteinInteractionPrediction(nn.Module):
def __init__(self):
super(CompoundProteinInteractionPrediction, self).__init__()
self.embed_fingerprint = nn.Embedding(n_fingerprint, dim)
self.embed_word = nn.Embedding(n_word, dim)
self.W_gnn = nn.Linear(dim, dim)
self.W_cnn = nn.Conv2d(in_channels=1, out_channels=1,
kernel_size=2*window+1, stride=1,
padding=window)
self.W_attention = nn.Linear(dim, dim)
self.W_out = nn.Linear(2*dim, 2)
def gnn(self, xs, adjacency, layer_gnn):
for _ in range(layer_gnn):
hs = F.relu(self.W_gnn(xs))
xs = hs + torch.matmul(adjacency, hs)
return torch.unsqueeze(torch.sum(xs, 0), 0)
def cnn(self, xs):
xs = torch.unsqueeze(torch.unsqueeze(xs, 0), 0)
return F.relu(self.W_cnn(xs))
def attention_cnn(self, x, xs, layer_cnn):
for _ in range(layer_cnn):
hs = self.cnn(xs)
hs = torch.squeeze(torch.squeeze(hs, 0), 0)
weights = torch.tanh(F.linear(x, hs))
xs = torch.t(weights) * hs
return torch.unsqueeze(torch.sum(xs, 0), 0)
def forward(self, inputs):
fingerprints, adjacency, words = inputs
"""Compound vector with GNN."""
x_fingerprints = self.embed_fingerprint(fingerprints)
x_compound = self.gnn(x_fingerprints, adjacency, layer_gnn)
"""Protein vector with attention-CNN."""
x_words = self.embed_word(words)
x_protein = self.attention_cnn(x_compound, x_words, layer_cnn)
y = torch.cat((x_compound, x_protein), 1)
z = self.W_out(y)
return z
def __call__(self, data, train=True):
inputs, interaction = data[:-1], data[-1]
z = self.forward(inputs)
if train:
loss = F.cross_entropy(z, interaction)
return loss
else:
z = F.softmax(z, 1).to('cpu').data[0].numpy()
t = interaction.to('cpu').data[0].numpy()
return z, t
class Trainer(object):
def __init__(self, model):
self.model = model
self.optimizer = optim.Adam(self.model.parameters(), lr=lr)
def train(self, dataset_train):
np.random.shuffle(dataset_train)
loss_total = 0
for data in dataset_train:
loss = self.model(data)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
loss_total += loss.to('cpu').data.numpy()
return loss_total
class Tester(object):
def __init__(self, model):
self.model = model
def test(self, dataset_test):
z_list, t_list = [], []
for data in dataset_test:
z, t = self.model(data, train=False)
z_list.append(z)
t_list.append(t)
score_list, label_list = [], []
for z in z_list:
score_list.append(z[1])
label_list.append(np.argmax(z))
auc = roc_auc_score(t_list, score_list)
precision = precision_score(t_list, label_list)
recall = recall_score(t_list, label_list)
return auc, precision, recall
def result(self, epoch, time, loss_total, auc_dev,
auc_test, precision, recall, file_result):
with open(file_result, 'a') as f:
result = map(str, [epoch, time, loss_total, auc_dev,
auc_test, precision, recall])
f.write('\t'.join(result) + '\n')
def save(self, model, file_name):
torch.save(model.state_dict(), file_name)
def load_dataset(data, dtype):
return [dtype(d).to(device) for d in np.load(dir_input + data + '.npy')]
def load_pickle(data):
with open(dir_input + data, 'rb') as f:
return pickle.load(f)
def shuffle_dataset(dataset, seed):
np.random.seed(seed)
np.random.shuffle(dataset)
return dataset
def split_dataset(dataset, ratio):
n = int(ratio * len(dataset))
dataset_1, dataset_2 = dataset[:n], dataset[n:]
return dataset_1, dataset_2
if __name__ == "__main__":
(DATASET, radius, ngram, dim, layer_gnn, window, layer_cnn, lr, lr_decay,
decay_interval, iteration, setting) = sys.argv[1:]
(dim, layer_gnn, window, layer_cnn,
decay_interval, iteration) = map(int, [dim, layer_gnn, window, layer_cnn,
decay_interval, iteration])
lr, lr_decay = map(float, [lr, lr_decay])
if torch.cuda.is_available():
device = torch.device('cuda')
print('The code uses GPU...')
else:
device = torch.device('cpu')
print('The code uses CPU!!!')
dir_input = ('../dataset/' + DATASET + '/input/radius' +
radius + '_ngram' + ngram + '/')
compounds = load_dataset('compounds', torch.LongTensor)
adjacencies = load_dataset('adjacencies', torch.FloatTensor)
proteins = load_dataset('proteins', torch.LongTensor)
interactions = load_dataset('interactions', torch.LongTensor)
fingerprint_dict = load_pickle('fingerprint_dict.pickle')
word_dict = load_pickle('word_dict.pickle')
dataset = list(zip(compounds, adjacencies, proteins, interactions))
dataset = shuffle_dataset(dataset, 1234)
dataset_train, dataset_ = split_dataset(dataset, 0.8)
dataset_dev, dataset_test = split_dataset(dataset_, 0.5)
unknown = 100
n_fingerprint = len(fingerprint_dict) + unknown
n_word = len(word_dict) + unknown
torch.manual_seed(1234)
model = CompoundProteinInteractionPrediction().to(device)
trainer = Trainer(model)
tester = Tester(model)
file_result = '../output/result/' + setting + '.txt'
with open(file_result, 'w') as f:
f.write('Epoch\tTime(sec)\tLoss\tAUC_dev\t'
'AUC_test\tPrecision\tRecall\n')
file_model = '../output/model/' + setting
print('Epoch Time(sec) Loss AUC_dev AUC_test Precision Recall')
start = timeit.default_timer()
for epoch in range(iteration):
if (epoch+1) % decay_interval == 0:
trainer.optimizer.param_groups[0]['lr'] *= lr_decay
loss_total = trainer.train(dataset_train)
auc_dev = tester.test(dataset_dev)[0]
auc_test, precision, recall = tester.test(dataset_test)
end = timeit.default_timer()
time = end - start
tester.result(epoch, time, loss_total, auc_dev,
auc_test, precision, recall, file_result)
tester.save(model, file_model)
print(epoch, time, loss_total, auc_dev, auc_test, precision, recall)
|
dmcomm/dmcomm-python
|
lib/dmcomm/hardware/barcode.py
|
<gh_stars>1-10
# This file is part of the DMComm project by BladeSabre. License: MIT.
import array
import pulseio
from dmcomm import CommandError
from dmcomm.protocol.barcode import ean13_lengths
class BarcodeCommunicator:
def __init__(self, ir_output):
self._pin_output = ir_output.pin_output
self._output_pulses = None
self._enabled = False
def enable(self, protocol):
self.disable()
try:
self._output_pulses = pulseio.PulseOut(self._pin_output, frequency=100_000, duty_cycle=0xFFFF)
except:
self.disable()
raise
self._enabled = True
def disable(self):
if self._output_pulses is not None:
self._output_pulses.deinit()
self._output_pulses = None
self._enabled = False
def reset(self):
pass
def send(self, digits_to_send):
if not self._enabled:
raise RuntimeError("not enabled")
if len(digits_to_send) != 13:
raise CommandError("requires 13 digits")
array_to_send = array.array("H", [0xFFFF])
for length in ean13_lengths(digits_to_send):
array_to_send.append(length * 1000)
array_to_send.append(0xFFFF)
self._output_pulses.send(array_to_send)
def receive(self, timeout_ms):
return []
|
dmcomm/dmcomm-python
|
utils/pio_asm_src.py
|
# This file is part of the DMComm project by BladeSabre. License: MIT.
# Source code for the RP2 PIO programs, to be pre-assembled using desktop Python.
# Main writes to ../lib/dmcomm/hardware/pio_programs.py .
import os
import adafruit_pioasm
# Output to pronged devices.
# Run with 1MHz clock, 2 set pins, initial_set_pin_direction=0 (input).
# First set pin is pin_drive_signal. Second set pin is pin_drive_low.
# PIO can change both values or directions at the same time. Change values before directions for output.
# If number sent is 0, drive the output low (both pins output low).
# If number sent is 1, drive the output high (pin_drive_signal output high, pin_drive_low output low).
# If number sent is 2, disable the output (both pins input).
# Otherwise, delay for approximately that number of microseconds.
prong_TX_ASM = """
start:
pull
mov x osr
jmp x-- notdrivelow
jmp drivelow ; if osr==0
notdrivelow:
jmp x-- notdrivehigh
jmp drivehigh ; if osr==1
notdrivehigh:
jmp x-- delay
jmp release ; if osr==2
; else:
delay:
jmp x-- delay
jmp start
drivelow:
set pins 0
set pindirs 3
jmp start
drivehigh:
set pins 1
set pindirs 3
jmp start
release:
set pindirs 0
"""
# Outputs the specified bytes to iC.
# Run with 100kHz clock, 1 out pin and 1 set pin which are the same.
# TODO This is inefficient on PIO space and could be redone with a loop.
iC_TX_ASM = """
pull
mov osr ~ osr
set pins 1
set pins 0 [8]
""" + ("""
out pins 1
set pins 0 [8]
""" * 8) + """
nop [12]
"""
this_file_name = os.path.basename(__file__)
output_text = f"""# This file is part of the DMComm project by BladeSabre. License: MIT.
# Auto-generated from {this_file_name} - do not edit.
from array import array
prong_TX = {repr(adafruit_pioasm.assemble(prong_TX_ASM))}
iC_TX = {repr(adafruit_pioasm.assemble(iC_TX_ASM))}
"""
if __name__ == "__main__":
dir_above = os.path.dirname(os.path.dirname(os.path.realpath("__file__")))
target_filepath = os.path.join(dir_above, "lib/dmcomm/hardware/pio_programs.py")
with open(target_filepath, "w") as f:
f.write(output_text)
|
dmcomm/dmcomm-python
|
lib/dmcomm/hardware/ic_encoding.py
|
START_SEQUENCE = [0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xC0,0xFF,0x13,0x70,0x70]
def redundancy_bits(x):
"Calculates the 16 redundancy bits for 16 bits of data."
result = 0x79B4
mask = 0x19D8
for i in range(16):
if x & 1:
result ^= mask
x >>= 1
mask <<= 1
if mask >= 0x10000:
mask ^= 0x10811
return result
def encode(x):
"Calculates the byte sequence for 16 bits of data."
r = redundancy_bits(x)
result = START_SEQUENCE[:]
for byte_ in [x & 0xFF, (x & 0xFF00) >> 8, r & 0xFF, (r & 0xFF00) >> 8]:
if byte_ == 0xC0:
result.append(0x7D)
result.append(0xE0)
elif byte_ == 0xC1:
result.append(0x7D)
result.append(0xE1)
else:
result.append(byte_)
result.append(0xC1)
return result
def decode(bytes_, start_index=0):
offset = 0
bytes4 = []
stage = 1
count_C0 = 0
while True:
i = start_index + offset
if i >= len(bytes_):
raise ValueError("ended unfinished")
b1 = bytes_[i]
if i <= len(bytes_) - 2:
b2 = bytes_[i+1]
else:
b2 = None
if stage == 1:
if b1 == 0xC0:
count_C0 += 1
if count_C0 > 10:
raise ValueError("more than 10 C0")
elif count_C0 < 5:
raise ValueError("less than 5 C0")
else:
stage = 2
start_sequence_remaining = 4
if stage == 1:
pass #continuing from above to stage 2 with same byte
elif stage == 2:
target = START_SEQUENCE[-start_sequence_remaining]
if b1 != target:
raise ValueError("byte at position %d expected %02X, got %02X" % (offset, target, b1))
start_sequence_remaining -= 1
if start_sequence_remaining == 0:
stage = 3
elif b1 == 0x7D:
if b2 == 0xE0:
bytes4.append(0xC0)
elif b2 == 0xE1:
bytes4.append(0xC1)
elif b2 is None:
raise ValueError("ended unfinished")
else:
raise ValueError("bad escape sequence %02X %02X" % (b1, b2))
offset += 1
elif b1 == 0xC1:
if b2 == 0xFF:
offset += 1
break
else:
bytes4.append(b1)
offset += 1
if len(bytes4) != 4:
raise ValueError("length not 4: " + str(bytes4))
x = bytes4[0] | (bytes4[1] << 8)
r = bytes4[2] | (bytes4[3] << 8)
r_calc = redundancy_bits(x)
if r_calc != r:
raise ValueError("redundancy bits for %04X expected %04X, got %04X" % (x, r_calc, r))
return (x, offset + 1)
|
dmcomm/dmcomm-python
|
lib/dmcomm/protocol/__init__.py
|
# This file is part of the DMComm project by BladeSabre. License: MIT.
"""
`dmcomm.protocol`
=================
...
Note: This API is still under development and may change at any time.
"""
from dmcomm import CommandError
def parse_command(text):
parts = text.strip().upper().split("-")
if len(parts[0]) >= 2:
op = parts[0][:-1]
turn = parts[0][-1]
else:
op = parts[0]
turn = ""
if op in ["D", "T"]:
return OtherCommand(op, turn)
elif op in ["V", "X", "Y", "!IC"]:
from dmcomm.protocol.core16 import CommandSegment, DigiROM
elif op in ["!DL", "!FL"]:
from dmcomm.protocol.core_bytes import CommandSegment, DigiROM
elif op in ["!BC"]:
from dmcomm.protocol.core_digits import CommandSegment, DigiROM
else:
raise CommandError("op=" + op)
if turn not in "012":
raise CommandError("turn=" + turn)
segments = [CommandSegment.from_string(part) for part in parts[1:]]
return DigiROM(op, int(turn), segments)
class OtherCommand:
def __init__(self, op, param):
self.op = op
self.param = param
class BaseDigiROM:
"""Base class for describing the communication and recording the results.
"""
def __init__(self, result_segment_class, physical, turn, segments=[]):
self.result_segment_class = result_segment_class
self.physical = physical
self.turn = turn
self._segments = segments
self.result = None
def append(self, c):
self._segments.append(c)
def prepare(self):
self.result = Result(self.physical, 0)
self._command_index = 0
def send(self):
if self._command_index >= len(self._segments):
return None
c = self._segments[self._command_index]
self._command_index += 1
self.result.append(self.result_segment_class(True, c.data))
return c.data
def receive(self, data):
self.result.append(self.result_segment_class(False, data))
def __len__(self):
return len(self._segments)
class Result:
"""Describes the result of the communication.
"""
def __init__(self, physical, turn):
self.physical = physical
self.turn = turn
self._results = []
def append(self, segment):
self._results.append(segment)
def __str__(self):
"""Returns text formatted for the serial protocol."""
return " ".join([str(r) for r in self._results])
|
dmcomm/dmcomm-python
|
lib/dmcomm/hardware/control.py
|
# This file is part of the DMComm project by BladeSabre. License: MIT.
from dmcomm import CommandError
from . import WAIT_REPLY
from . import pins
class Controller:
"""Main class which controls the communication.
The constructor takes no parameters.
"""
def __init__(self):
self._digirom = None
self._communicator = None
self._prong_output = None
self._prong_input = None
self._ir_output = None
self._ir_input_modulated = None
self._ir_input_raw = None
self._prong_comm = None
self._ic_comm = None
self._modulated_comm = None
self._barcode_comm = None
def register(self, io_object) -> None:
"""Registers pins for a particular type of input or output.
Each type should only be provided once.
:param io_object: One of the `Input` or `Output` types provided.
"""
if isinstance(io_object, pins.ProngOutput):
self._prong_output = io_object
if isinstance(io_object, pins.ProngInput):
self._prong_input = io_object
if isinstance(io_object, pins.InfraredOutput):
self._ir_output = io_object
if isinstance(io_object, pins.InfraredInputModulated):
self._ir_input_modulated = io_object
if isinstance(io_object, pins.InfraredInputRaw):
self._ir_input_raw = io_object
if self._prong_comm is None and self._prong_output is not None and self._prong_input is not None:
from . import prongs
self._prong_comm = prongs.ProngCommunicator(self._prong_output, self._prong_input)
if self._ic_comm is None and self._ir_output is not None and self._ir_input_raw is not None:
from . import ic
self._ic_comm = ic.iC_Communicator(self._ir_output, self._ir_input_raw)
if self._modulated_comm is None and self._ir_output is not None and self._ir_input_modulated is not None:
from . import modulated
self._modulated_comm = modulated.ModulatedCommunicator(self._ir_output, self._ir_input_modulated)
if self._barcode_comm is None and self._ir_output is not None:
from . import barcode
self._barcode_comm = barcode.BarcodeCommunicator(self._ir_output)
def execute(self, digirom) -> None:
"""Carries out the communication specified.
:param digirom: The DigiROM to execute.
:raises CommandError: If the required pins for the selected physical protocol are not registered.
:raises ReceiveError: If a broken transmission was received.
"""
self._digirom = digirom
try:
self._prepare()
if digirom.turn in [0, 2]:
if not self._received(5000):
return
if digirom.turn == 0:
while True:
if not self._received(WAIT_REPLY):
return
else:
while True:
data_to_send = self._digirom.send()
if data_to_send is None:
return
self._communicator.send(data_to_send)
if not self._received(WAIT_REPLY):
return
finally:
self._disable()
self._digirom = None
def _prepare(self):
"""Prepares for a single interaction.
"""
protocol = self._digirom.physical
self._disable()
if protocol in ["V", "X", "Y"]:
if self._prong_output is None:
raise CommandError("no prong output registered")
if self._prong_input is None:
raise CommandError("no prong input registered")
self._communicator = self._prong_comm
elif protocol == "!IC":
if self._ir_output is None:
raise CommandError("no infrared output registered")
if self._ir_input_raw is None:
raise CommandError("no raw infrared input registered")
self._communicator = self._ic_comm
elif protocol in ["!DL", "!FL"]:
if self._ir_output is None:
raise CommandError("no infrared output registered")
if self._ir_input_modulated is None:
raise CommandError("no modulated infrared input registered")
self._communicator = self._modulated_comm
elif protocol in ["!BC"]:
if self._ir_output is None:
raise CommandError("no infrared output registered")
self._communicator = self._barcode_comm
else:
raise CommandError("protocol=" + protocol)
self._communicator.enable(protocol)
self._digirom.prepare()
def _received(self, timeout_ms):
received_data = self._communicator.receive(timeout_ms)
self._digirom.receive(received_data)
if received_data is None or received_data == []:
return False
return True
def _disable(self):
if self._communicator is not None:
self._communicator.disable()
self._communicator = None
|
dmcomm/dmcomm-python
|
lib/dmcomm/hardware/pio_programs.py
|
# This file is part of the DMComm project by BladeSabre. License: MIT.
# Auto-generated from pio_asm_src.py - do not edit.
from array import array
prong_TX = array('H', [32928, 40999, 68, 10, 70, 13, 72, 16, 72, 0, 57344, 57475, 0, 57345, 57475, 0, 57472])
iC_TX = array('H', [32928, 41199, 57345, 59392, 24577, 59392, 24577, 59392, 24577, 59392, 24577, 59392, 24577, 59392, 24577, 59392, 24577, 59392, 24577, 59392, 44098])
|
dmcomm/dmcomm-python
|
lib/dmcomm/hardware/modulated.py
|
# This file is part of the DMComm project by BladeSabre. License: MIT.
import array
import pulseio
from dmcomm import CommandError, ReceiveError
from . import WAIT_REPLY
from . import misc
class ModulatedCommunicator:
def __init__(self, ir_output, ir_input_modulated):
self._pin_output = ir_output.pin_output
self._pin_input = ir_input_modulated.pin_input
self._output_pulses = None
self._input_pulses = None
self._params = ModulatedParams()
self._enabled = False
def enable(self, protocol):
self.disable()
self._params.set_protocol(protocol)
try:
self._output_pulses = pulseio.PulseOut(self._pin_output, frequency=38000, duty_cycle=0x8000)
self._input_pulses = pulseio.PulseIn(self._pin_input, maxlen=300, idle_state=True)
self._input_pulses.pause()
except:
self.disable()
raise
self._enabled = True
def disable(self):
for item in [self._output_pulses, self._input_pulses]:
if item is not None:
item.deinit()
self._ouput_pulses = None
self._input_pulses = None
self._enabled = False
def reset(self):
pass
def send(self, bytes_to_send):
if not self._enabled:
raise RuntimeError("not enabled")
num_durations = len(bytes_to_send) * 16 + 4
array_to_send = array.array("H")
for i in range(num_durations):
array_to_send.append(0)
#This function would be simpler if we append as we go along,
#but still hoping for a fix that allows reuse of the array.
array_to_send[0] = self._params.start_pulse_send
array_to_send[1] = self._params.start_gap_send
buf_cursor = 2
for current_byte in bytes_to_send:
for j in range(8):
array_to_send[buf_cursor] = self._params.bit_pulse_send
buf_cursor += 1
if current_byte & 1:
array_to_send[buf_cursor] = self._params.bit_gap_send_long
else:
array_to_send[buf_cursor] = self._params.bit_gap_send_short
buf_cursor += 1
current_byte >>= 1
array_to_send[buf_cursor] = self._params.stop_pulse_send
array_to_send[buf_cursor + 1] = self._params.stop_gap_send
self._output_pulses.send(array_to_send)
def receive(self, timeout_ms):
if not self._enabled:
raise RuntimeError("not enabled")
pulses = self._input_pulses
pulses.clear()
pulses.resume()
if timeout_ms == WAIT_REPLY:
timeout_ms = self._params.reply_timeout_ms
misc.wait_for_length_no_more(pulses, timeout_ms,
self._params.packet_length_timeout_ms, self._params.packet_continue_timeout_ms)
pulses.pause()
if len(pulses) == 0:
return []
bytes_received = []
t = misc.pop_pulse(pulses, -2)
if t < self._params.start_pulse_min or t > self._params.start_pulse_max:
raise ReceiveError("start pulse = %d" % t)
t = misc.pop_pulse(pulses, -1)
if t < self._params.start_gap_min or t > self._params.start_gap_max:
raise ReceiveError("start gap = %d" % t)
current_byte = 0
bit_count = 0
while True:
t = misc.pop_pulse(pulses, 2*bit_count+1)
if t >= self._params.bit_pulse_min and t <= self._params.bit_pulse_max:
#normal pulse
pass
elif t >= self._params.stop_pulse_min and t <= self._params.stop_pulse_max:
#stop pulse
break
else:
raise ReceiveError("bit %d pulse = %d" % (bit_count, t))
t = misc.pop_pulse(pulses, 2*bit_count+2)
if t < self._params.bit_gap_min or t > self._params.bit_gap_max:
raise ReceiveError("bit %d gap = %d" % (bit_count, t))
current_byte >>= 1
if t > self._params.bit_gap_threshold:
current_byte |= 0x80
bit_count += 1
if bit_count % 8 == 0:
bytes_received.append(current_byte)
current_byte = 0
if bit_count % 8 != 0:
raise ReceiveError("bit_count = %d" % bit_count)
return bytes_received
class ModulatedParams:
def __init__(self):
self.set_protocol("!DL")
def set_protocol(self, protocol):
if protocol == "!DL":
self.start_pulse_min = 9000
self.start_pulse_send = 9800
self.start_pulse_max = 11000
self.start_gap_min = 2000
self.start_gap_send = 2450
self.start_gap_max = 3000
self.bit_pulse_min = 300
self.bit_pulse_send = 500
self.bit_pulse_max = 650
self.bit_gap_min = 300
self.bit_gap_send_short = 700
self.bit_gap_threshold = 800
self.bit_gap_send_long = 1300
self.bit_gap_max = 1500
self.stop_pulse_min = 1000
self.stop_pulse_send = 1300
self.stop_pulse_max = 1400
self.stop_gap_send = 400
self.reply_timeout_ms = 40
self.packet_length_timeout_ms = 300
self.packet_continue_timeout_ms = 10
elif protocol == "!FL":
self.start_pulse_min = 5000
self.start_pulse_send = 5880
self.start_pulse_max = 7000
self.start_gap_min = 3000
self.start_gap_send = 3872
self.start_gap_max = 4000
self.bit_pulse_min = 250
self.bit_pulse_send = 480
self.bit_pulse_max = 600
self.bit_gap_min = 200
self.bit_gap_send_short = 480
self.bit_gap_threshold = 650
self.bit_gap_send_long = 1450
self.bit_gap_max = 1600
self.stop_pulse_min = 700
self.stop_pulse_send = 950
self.stop_pulse_max = 1100
self.stop_gap_send = 1500
self.reply_timeout_ms = 100
self.packet_length_timeout_ms = 300
self.packet_continue_timeout_ms = 10
else:
raise ValueError("protocol must be !DL/!FL")
self.protocol = protocol
|
dmcomm/dmcomm-python
|
lib/dmcomm/protocol/core16.py
|
<reponame>dmcomm/dmcomm-python
# This file is part of the DMComm project by BladeSabre. License: MIT.
"""
`dmcomm.protocol.core16`
========================
Handling of 16-bit low-level protocols.
Note: This API is still under development and may change at any time.
"""
from dmcomm import CommandError
from dmcomm.protocol import Result
class DigiROM:
"""Describes the communication for 16-bit protocols and records the results.
"""
def __init__(self, physical, turn, segments=[]):
self.physical = physical
self.turn = turn
self._segments = segments
self.result = None
def append(self, c):
self._segments.append(c)
def prepare(self):
self.result = Result(self.physical, 0)
self._command_index = 0
self._bits_received = 0
self._checksum = 0
def send(self):
if self._command_index >= len(self._segments):
return None
c = self._segments[self._command_index]
self._command_index += 1
bits = c.bits
bits &= ~c.copy_mask
bits |= c.copy_mask & self._bits_received
bits &= ~c.invert_mask
bits |= c.invert_mask & ~self._bits_received
if c.checksum_target is not None:
bits &= ~(0xF << c.check_digit_LSB_pos)
for i in range(4):
self._checksum += bits >> (4 * i)
self._checksum %= 16
if c.checksum_target is not None:
check_digit = (c.checksum_target - self._checksum) % 16
bits |= check_digit << c.check_digit_LSB_pos
self._checksum = c.checksum_target
self.result.append(ResultSegment(True, bits))
return bits
def receive(self, bits):
self.result.append(ResultSegment(False, bits))
self._bits_received = bits
def __len__(self):
return len(self._segments)
class CommandSegment:
"""Describes how to carry out one segment of the communication for 16-bit protocols.
"""
@classmethod
def from_string(cls, text):
"""Creates a `CommandSegment` from one of the dash-separated parts of a text command.
"""
bits = 0
copy_mask = 0
invert_mask = 0
checksum_target = None
check_digit_LSB_pos = None
cursor = 0
for i in range(4):
LSB_pos = 12 - (i * 4)
bits <<= 4
try:
ch1 = text[cursor]
if ch1 == "@" or ch1 == "^":
cursor += 1
ch_digit = text[cursor]
else:
ch_digit = ch1
except IndexError:
raise CommandError("incomplete: " + text)
try:
digit = int(ch_digit, 16)
except:
raise CommandError("not hex number: " + ch_digit)
if ch1 == "@":
checksum_target = digit
check_digit_LSB_pos = LSB_pos
elif ch1 == "^":
copy_mask |= (~digit & 0xF) << LSB_pos
invert_mask |= digit << LSB_pos
else:
bits |= digit
cursor += 1
if cursor != len(text):
raise CommandError("too long: " + text)
return cls(bits, copy_mask, invert_mask, checksum_target, check_digit_LSB_pos)
def __init__(self, bits, copy_mask=0, invert_mask=0, checksum_target=None, check_digit_LSB_pos=12):
self.bits = bits
self.copy_mask = copy_mask
self.invert_mask = invert_mask
self.checksum_target = checksum_target
self.check_digit_LSB_pos = check_digit_LSB_pos
#def __str__():
class ResultSegment:
"""Describes the result of one segment of the communication for 16-bit protocols.
:param is_send: True if this represents data sent, False if data received.
:param data: A 16-bit integer representing the bits sent or received.
If is_send is False, can be None to indicate nothing was received before timeout.
"""
def __init__(self, is_send: bool, data: int):
self.is_send = is_send
self.data = data
def __str__(self):
"""Returns text formatted for the serial protocol."""
if self.is_send:
return "s:%04X" % self.data
elif self.data is None:
return "t"
else:
return "r:%04X" % self.data
|
dmcomm/dmcomm-python
|
lib/dmcomm/protocol/core_digits.py
|
# This file is part of the DMComm project by BladeSabre. License: MIT.
"""
`dmcomm.protocol.core_digits`
=============================
Handling of digit sequence low-level protocols.
Note: This API is still under development and may change at any time.
"""
from dmcomm import CommandError
from dmcomm.protocol import BaseDigiROM, Result
class DigiROM(BaseDigiROM):
"""Describes the communication for digit-sequence protocols and records the results.
"""
def __init__(self, physical, turn, segments=[]):
super().__init__(ResultSegment, physical, turn, segments)
class CommandSegment:
"""Describes how to carry out one segment of the communication for digit-sequence protocols.
"""
@classmethod
def from_string(cls, text):
"""Creates a `CommandSegment` from one of the dash-separated parts of a text command.
"""
data = []
for digit in text:
try:
n = int(digit)
except:
raise CommandError("not a number: " + digit)
data.append(n)
return cls(data)
def __init__(self, data):
self.data = data
#def __str__():
class ResultSegment:
"""Describes the result of one segment of the communication for digit-sequence protocols.
:param is_send: True if this represents data sent, False if data received.
:param data: A list of integers representing the digits sent or received.
If is_send is False, can be empty to indicate nothing was received before timeout.
"""
def __init__(self, is_send: bool, data: list):
self.is_send = is_send
self.data = data
def __str__(self):
"""Returns text formatted for the serial protocol."""
digits = ["%d" % n for n in self.data]
digit_str = "".join(digits)
if self.is_send:
return "s:" + digit_str
elif self.data == []:
return "t"
else:
return "r:" + digit_str
|
dmcomm/dmcomm-python
|
lib/dmcomm/hardware/ic.py
|
# This file is part of the DMComm project by BladeSabre. License: MIT.
import array
import pulseio
import time
import rp2pio
from dmcomm import ReceiveError
from . import WAIT_REPLY
from . import ic_encoding
from . import misc
from . import pio_programs
class iC_Communicator:
def __init__(self, ir_output, ir_input_raw):
self._pin_output = ir_output.pin_output
self._pin_input = ir_input_raw.pin_input
self._output_state_machine = None
self._input_pulses = None
self._params = iC_Params()
self._enabled = False
def enable(self, protocol):
self.disable()
self._params.set_protocol(protocol)
try:
self._output_state_machine = rp2pio.StateMachine(
pio_programs.iC_TX,
frequency=100_000,
first_out_pin=self._pin_output,
first_set_pin=self._pin_output,
)
self._input_pulses = pulseio.PulseIn(self._pin_input, maxlen=250, idle_state=True)
self._input_pulses.pause()
except:
self.disable()
raise
self._enabled = True
def disable(self):
for item in [self._output_state_machine, self._input_pulses]:
if item is not None:
item.deinit()
self._ouput_state_machine = None
self._input_pulses = None
self._enabled = False
def send(self, bits):
if not self._enabled:
raise RuntimeError("not enabled")
bytes_to_send = ic_encoding.encode(bits)
self.send_bytes(bytes_to_send)
def send_bytes(self, bytes_to_send):
if not self._enabled:
raise RuntimeError("not enabled")
self._output_state_machine.write(bytes(bytes_to_send))
def receive(self, timeout_ms):
if not self._enabled:
raise RuntimeError("not enabled")
bytes_received = self.receive_bytes(timeout_ms)
if bytes_received == []:
return None
try:
(result, count) = ic_encoding.decode(bytes_received)
except ValueError as e:
raise ReceiveError(str(e))
return result
def receive_bytes(self, timeout_ms):
if not self._enabled:
raise RuntimeError("not enabled")
pulses = self._input_pulses
pulses.clear()
pulses.resume()
if timeout_ms == WAIT_REPLY:
timeout_ms = self._params.reply_timeout_ms
misc.wait_for_length(pulses, 1, timeout_ms)
time.sleep(self._params.packet_length_timeout_ms / 1000)
pulses.pause()
if len(pulses) == 0:
return []
#discard first byte or part of byte since we're joining partway through
min_gap_find = 2.5 * self._params.tick_length
while True:
if len(pulses) == 0:
raise ReceiveError("fragment")
if pulses.popleft() > min_gap_find:
break
bytes_received = []
current_byte = 0
pulse_count = 0
ticks_into_byte = 0
ended = False
while not ended:
pulse_count += 1
if len(pulses) == 0:
raise ReceiveError("ended with gap")
t_pulse = pulses.popleft()
if t_pulse > self._params.pulse_max:
raise ReceiveError("pulse %d = %d" % (pulse_count, t_pulse))
if len(pulses) != 0:
t_gap = pulses.popleft()
else:
t_gap = 0xFFFF
ended = True
dur = t_pulse + t_gap
ticks = round(dur / self._params.tick_length)
dur_rounded = ticks * self._params.tick_length
off_rounded = abs(dur - dur_rounded)
if ticks_into_byte + ticks >= 9:
#finish byte
for i in range(8 - ticks_into_byte):
current_byte >>= 1
current_byte |= 0x80
bytes_received.append(current_byte)
current_byte = 0
ticks_into_byte = 0
elif off_rounded > self._params.tick_margin:
raise ReceiveError("pulse+gap %d = %d" % (pulse_count, dur))
else:
for i in range(ticks - 1):
current_byte >>= 1
current_byte |= 0x80
current_byte >>= 1
ticks_into_byte += ticks
return bytes_received
class iC_Params:
def __init__(self):
self.set_protocol("!IC")
def set_protocol(self, protocol):
if protocol == "!IC":
self.reply_timeout_ms = 100
self.packet_length_timeout_ms = 30
self.pulse_max = 25
self.tick_length = 100
self.tick_margin = 30
else:
raise ValueError("protocol must be !IC")
self.protocol = protocol
|
dmcomm/dmcomm-python
|
lib/dmcomm/hardware/prongs.py
|
<filename>lib/dmcomm/hardware/prongs.py
# This file is part of the DMComm project by BladeSabre. License: MIT.
import array
import digitalio
import pulseio
import rp2pio
from dmcomm import ReceiveError
from . import WAIT_REPLY
from . import misc
from . import pio_programs
class ProngCommunicator:
def __init__(self, prong_output, prong_input):
self._pin_drive_signal = prong_output.pin_drive_signal
self._pin_weak_pull = prong_output.pin_weak_pull
self._pin_input = prong_input.pin_input
#Doesn't work to create the weak pull right before use, #TODO deinit? or bug report?
self._output_weak_pull = digitalio.DigitalInOut(self._pin_weak_pull)
self._output_weak_pull.switch_to_output(value=True)
self._output_state_machine = None
self._input_pulses = None
self._params = ProngParams()
self._enabled = False
def enable(self, protocol):
self.disable()
self._params.set_protocol(protocol)
try:
self._output_state_machine = rp2pio.StateMachine(
pio_programs.prong_TX,
frequency=1_000_000,
first_set_pin=self._pin_drive_signal,
set_pin_count=2,
initial_set_pin_direction=0,
)
self._output_weak_pull.value = self._params.idle_state
self._input_pulses = pulseio.PulseIn(self._pin_input, maxlen=40, idle_state=self._params.idle_state)
self._input_pulses.pause()
except:
self.disable()
raise
self._enabled = True
def disable(self):
for item in [self._output_state_machine, self._input_pulses]:
#add back self._output_weak_pull if it gets fixed
if item is not None:
item.deinit()
self._ouput_state_machine = None
#self._output_weak_pull = None
self._input_pulses = None
self._enabled = False
def send(self, bits):
if not self._enabled:
raise RuntimeError("not enabled")
if self._params.idle_state == True:
DRIVE_ACTIVE = 0
DRIVE_INACTIVE = 1
else:
DRIVE_ACTIVE = 1
DRIVE_INACTIVE = 0
RELEASE = 2
array_to_send = array.array("L", [
DRIVE_INACTIVE, self._params.pre_high_send,
DRIVE_ACTIVE, self._params.pre_low_send,
DRIVE_INACTIVE, self._params.start_high_send,
DRIVE_ACTIVE, self._params.start_low_send,
])
for i in range(16):
array_to_send.append(DRIVE_INACTIVE)
if bits & 1:
array_to_send.append(self._params.bit1_high_send)
array_to_send.append(DRIVE_ACTIVE)
array_to_send.append(self._params.bit1_low_send)
else:
array_to_send.append(self._params.bit0_high_send)
array_to_send.append(DRIVE_ACTIVE)
array_to_send.append(self._params.bit0_low_send)
bits >>= 1
array_to_send.append(DRIVE_INACTIVE)
array_to_send.append(self._params.cooldown_send)
array_to_send.append(RELEASE)
self._output_state_machine.write(array_to_send)
def receive(self, timeout_ms):
if not self._enabled:
raise RuntimeError("not enabled")
pulses = self._input_pulses
pulses.clear()
pulses.resume()
if timeout_ms == WAIT_REPLY:
timeout_ms = self._params.reply_timeout_ms
misc.wait_for_length_2(pulses, 35, timeout_ms, self._params.packet_length_timeout_ms)
pulses.pause()
if len(pulses) == 0:
return None
if len(pulses) < 35:
#TODO handle the iC bug
raise ReceiveError("incomplete: %d pulses" % len(pulses))
t = pulses.popleft()
if t < self._params.pre_low_min:
raise ReceiveError("pre_low = %d" % t)
t = pulses.popleft()
if t < self._params.start_high_min or t > self._params.start_high_max:
raise ReceiveError("start_high = %d" % t)
t = pulses.popleft()
if t < self._params.start_low_min or t > self._params.start_low_max:
raise ReceiveError("start_low = %d" % t)
result = 0
for i in range(16):
t = pulses.popleft()
if t < self._params.bit_high_min or t > self._params.bit_high_max:
raise ReceiveError("bit_high %d = %d" % (i + 1, t))
result >>= 1
if t > self._params.bit_high_threshold:
result |= 0x8000
t = pulses.popleft()
if t < self._params.bit_low_min or t > self._params.bit_low_max:
raise ReceiveError("bit_low %d = %d" % (i + 1, t))
return result
class ProngParams:
def __init__(self):
self.set_protocol("V")
def set_protocol(self, protocol):
if protocol == "V":
self.idle_state = True
self.invert_bit_read = False
self.pre_high_send = 3000
self.pre_low_min = 40000
self.pre_low_send = 59000
#self.pre_low_max? PulseIn only goes up to 65535
self.start_high_min = 1500
self.start_high_send = 2083
self.start_high_max = 2500
self.start_low_min = 600
self.start_low_send = 917
self.start_low_max = 1200
self.bit_high_min = 800
self.bit0_high_send = 1000
self.bit_high_threshold = 1800
self.bit1_high_send = 2667
self.bit_high_max = 3400
self.bit_low_min = 1000
self.bit1_low_send = 1667
self.bit0_low_send = 3167
self.bit_low_max = 3500
self.cooldown_send = 400
self.reply_timeout_ms = 100
self.packet_length_timeout_ms = 300
elif protocol == "X":
self.idle_state = True
self.invert_bit_read = False
self.pre_high_send = 3000
self.pre_low_min = 40000
self.pre_low_send = 60000
#self.pre_low_max? PulseIn only goes up to 65535
self.start_high_min = 1500
self.start_high_send = 2200
self.start_high_max = 2500
self.start_low_min = 1000
self.start_low_send = 1600
self.start_low_max = 2000
self.bit_high_min = 800
self.bit0_high_send = 1600
self.bit_high_threshold = 2600
self.bit1_high_send = 4000
self.bit_high_max = 4500
self.bit_low_min = 1200
self.bit1_low_send = 1600
self.bit0_low_send = 4000
self.bit_low_max = 4500
self.cooldown_send = 400
self.reply_timeout_ms = 100
self.packet_length_timeout_ms = 300
elif protocol == "Y":
self.idle_state = False
self.invert_bit_read = True
self.pre_high_send = 5000
self.pre_low_min = 30000
self.pre_low_send = 40000
#self.pre_low_max? PulseIn only goes up to 65535
self.start_high_min = 9000
self.start_high_send = 11000
self.start_high_max = 13000
self.start_low_min = 4000
self.start_low_send = 6000
self.start_low_max = 8000
self.bit_high_min = 1000
self.bit0_high_send = 4000
self.bit_high_threshold = 3000
self.bit1_high_send = 1400
self.bit_high_max = 4500
self.bit_low_min = 1200
self.bit1_low_send = 4400
self.bit0_low_send = 1600
self.bit_low_max = 5000
self.cooldown_send = 200
self.reply_timeout_ms = 100
self.packet_length_timeout_ms = 300
else:
raise ValueError("protocol must be V/X/Y")
self.protocol = protocol
|
dmcomm/dmcomm-python
|
lib/dmcomm/hardware/__init__.py
|
<reponame>dmcomm/dmcomm-python
# This file is part of the DMComm project by BladeSabre. License: MIT.
"""
`dmcomm.hardware`
=================
Communication with pronged and infrared Digimon toys, for CircuitPython 7 on RP2040.
Note: This API is still under development and may change at any time.
"""
#: Value to pass to receiving functions indicating there is no timeout.
WAIT_FOREVER = -2
#: Value to pass to receiving functions indicating the default reply timeout.
WAIT_REPLY = -1
from .control import Controller
from .pins import ProngOutput, ProngInput, InfraredOutput, InfraredInputModulated, InfraredInputRaw
__all__ = [
"WAIT_FOREVER", "WAIT_REPLY", "Controller",
"ProngOutput", "ProngInput", "InfraredOutput", "InfraredInputModulated", "InfraredInputRaw",
]
|
dmcomm/dmcomm-python
|
lib/dmcomm/protocol/core_bytes.py
|
# This file is part of the DMComm project by BladeSabre. License: MIT.
"""
`dmcomm.protocol.core_bytes`
============================
Handling of byte-sequence low-level protocols.
Note: This API is still under development and may change at any time.
"""
from dmcomm import CommandError
from dmcomm.protocol import BaseDigiROM, Result
class DigiROM(BaseDigiROM):
"""Describes the communication for byte-sequence protocols and records the results.
"""
def __init__(self, physical, turn, segments=[]):
super().__init__(ResultSegment, physical, turn, segments)
class CommandSegment:
"""Describes how to carry out one segment of the communication for byte-sequence protocols.
"""
@classmethod
def from_string(cls, text):
"""Creates a `CommandSegment` from one of the dash-separated parts of a text command.
"""
if len(text) < 2 or len(text) % 2 != 0:
raise CommandError("bad length: " + text)
data = []
for i in range(len(text)-2, -1, -2):
digits = text[i:i+2]
try:
b = int(digits, 16)
except:
raise CommandError("not hex number: " + digits)
data.append(b)
return cls(data)
def __init__(self, data):
self.data = data
#def __str__():
class ResultSegment:
"""Describes the result of one segment of the communication for byte-sequence protocols.
:param is_send: True if this represents data sent, False if data received.
:param data: A list of 8-bit integers representing the bytes sent or received.
If is_send is False, can be empty to indicate nothing was received before timeout.
"""
def __init__(self, is_send: bool, data: list):
self.is_send = is_send
self.data = data
def __str__(self):
"""Returns text formatted for the serial protocol."""
hex_parts = ["%02X" % b for b in self.data]
hex_parts.reverse()
hex_str = "".join(hex_parts)
if self.is_send:
return "s:" + hex_str
elif self.data == []:
return "t"
else:
return "r:" + hex_str
|
dmcomm/dmcomm-python
|
docs/conf.py
|
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('../lib'))
# -- Project information -----------------------------------------------------
project = 'DMComm'
copyright = '2021, BladeSabre'
author = 'BladeSabre'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc']
# Autodoc settings
autodoc_member_order = 'bysource'
autodoc_mock_imports = ['supervisor']
# Git commit ID
import subprocess
_git_args = ['git', 'show', '-s', '--format=%cd %h', '--date=short', 'HEAD']
_git_commit = subprocess.check_output(_git_args).strip().decode('ascii')
_git_args = ['git', 'status', '--porcelain']
_git_status = subprocess.check_output(_git_args).strip().decode('ascii')
rst_epilog = 'Generated from git commit: ' + _git_commit
if _git_status != "":
rst_epilog += " (dirty)"
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinxdoc'
html_theme_options = {
"nosidebar": "true",
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
|
dmcomm/dmcomm-python
|
lib/dmcomm/__init__.py
|
<reponame>dmcomm/dmcomm-python
# This file is part of the DMComm project by BladeSabre. License: MIT.
"""
`dmcomm`
========
Communication with Digimon toys.
Note: This API is still under development and may change at any time.
"""
class CommandError(ValueError):
"""Exception raised when an incorrect command is provided."""
class ReceiveError(Exception):
"""Exception raised when a broken transmission is received."""
|
dmcomm/dmcomm-python
|
code.py
|
# This file is part of the DMComm project by BladeSabre. License: MIT.
import board
import digitalio
import time
import usb_cdc
from dmcomm import CommandError, ReceiveError
import dmcomm.hardware as hw
import dmcomm.protocol
pins_extra_power = [board.GP11, board.GP13, board.GP18]
outputs_extra_power = []
for pin in pins_extra_power:
output = digitalio.DigitalInOut(pin)
output.direction = digitalio.Direction.OUTPUT
output.value = True
outputs_extra_power.append(output)
controller = hw.Controller()
controller.register(hw.ProngOutput(board.GP19, board.GP21))
controller.register(hw.ProngInput(board.GP26))
controller.register(hw.InfraredOutput(board.GP16))
controller.register(hw.InfraredInputModulated(board.GP17))
controller.register(hw.InfraredInputRaw(board.GP14))
usb_cdc.console.timeout = 1
digirom = None
while True:
time_start = time.monotonic()
if usb_cdc.console.in_waiting != 0:
digirom = None
serial_bytes = usb_cdc.console.readline()
serial_str = serial_bytes.decode("ascii", "ignore")
# readline only accepts "\n" but we can receive "\r" after timeout
if serial_str[-1] not in ["\r", "\n"]:
print("too slow")
continue
serial_str = serial_str.strip()
print("got %d bytes: %s -> " % (len(serial_str), serial_str), end="")
try:
command = dmcomm.protocol.parse_command(serial_str)
if hasattr(command, "op"):
# It's an OtherCommand
raise NotImplementedError("op=" + command.op)
digirom = command
print(f"{digirom.physical}{digirom.turn}-[{len(digirom)} packets]")
except (CommandError, NotImplementedError) as e:
print(repr(e))
time.sleep(1)
if digirom is not None:
error = ""
result_end = "\n"
try:
controller.execute(digirom)
except (CommandError, ReceiveError) as e:
error = repr(e)
result_end = " "
print(digirom.result, end=result_end)
if error != "":
print(error)
seconds_passed = time.monotonic() - time_start
if seconds_passed < 5:
time.sleep(5 - seconds_passed)
|
dmcomm/dmcomm-python
|
lib/dmcomm/hardware/misc.py
|
<reponame>dmcomm/dmcomm-python<gh_stars>1-10
# This file is part of the DMComm project by BladeSabre. License: MIT.
import supervisor
from . import WAIT_FOREVER
# Example from https://circuitpython.readthedocs.io/en/latest/shared-bindings/supervisor/index.html
_TICKS_PERIOD = 1 << 29
_TICKS_MAX = _TICKS_PERIOD - 1
_TICKS_HALFPERIOD = _TICKS_PERIOD // 2
def ticks_diff(ticks1, ticks2):
"Compute the signed difference between two ticks values, assuming that they are within 2**28 ticks"
diff = (ticks1 - ticks2) & _TICKS_MAX
diff = ((diff + _TICKS_HALFPERIOD) & _TICKS_MAX) - _TICKS_HALFPERIOD
return diff
def wait_for_length(obj, target, timeout_ms):
start_ticks_ms = supervisor.ticks_ms()
while True:
if len(obj) >= target:
return True
passed_ms = ticks_diff(supervisor.ticks_ms(), start_ticks_ms)
if timeout_ms != WAIT_FOREVER and passed_ms >= timeout_ms:
return False
def wait_for_length_2(obj, target, start_timeout_ms, dur_timeout_ms):
if not wait_for_length(obj, 1, start_timeout_ms):
return False
return wait_for_length(obj, target, dur_timeout_ms)
def wait_for_length_no_more(obj, start_timeout_ms, dur_timeout_ms, no_more_timeout_ms):
if not wait_for_length(obj, 1, start_timeout_ms):
return False
prev_length = len(obj)
start_ticks_ms = supervisor.ticks_ms()
prev_ticks_ms = start_ticks_ms
while True:
now_length = len(obj)
now_ticks_ms = supervisor.ticks_ms()
if now_length != prev_length:
prev_length = now_length
prev_ticks_ms = now_ticks_ms
if ticks_diff(now_ticks_ms, prev_ticks_ms) > no_more_timeout_ms:
return True
if ticks_diff(now_ticks_ms, start_ticks_ms) > dur_timeout_ms:
return True #cut it off before it was done, but not worrying about that for now
def pop_pulse(pulses, empty_error_code):
if len(pulses) == 0:
raise ReceiveError(str(empty_error_code))
return pulses.popleft()
|
dmcomm/dmcomm-python
|
lib/dmcomm/hardware/pins.py
|
<reponame>dmcomm/dmcomm-python<filename>lib/dmcomm/hardware/pins.py
# This file is part of the DMComm project by BladeSabre. License: MIT.
class ProngOutput:
"""Description of the outputs for the RP2040 prong circuit.
:param pin_drive_signal: The first pin to use for signal output.
Note that `pin_drive_low=pin_drive_signal+1` due to the rules of PIO.
:param pin_weak_pull: The pin to use for the weak pull-up / pull-down.
"""
def __init__(self, pin_drive_signal, pin_weak_pull):
#pin_drive_low must be pin_drive_signal+1
self.pin_drive_signal = pin_drive_signal
self.pin_weak_pull = pin_weak_pull
class ProngInput:
"""Description of the input for the RP2040 prong circuit.
:param pin_input: The pin to use for input.
An analog pin is recommended for compatibility with the Arduino version
and for a possible future voltage test.
"""
def __init__(self, pin_input):
self.pin_input = pin_input
class InfraredOutput:
"""Description of the infrared LED output.
:param pin_output: The pin to use for output.
"""
def __init__(self, pin_output):
self.pin_output = pin_output
class InfraredInputModulated:
"""Description of the modulated infrared input (TSOP4838 recommended).
:param pin_input: The pin to use for input.
"""
def __init__(self, pin_input):
self.pin_input = pin_input
class InfraredInputRaw:
"""Description of the non-modulated infrared input (TSMP58000 recommended).
:param pin_input: The pin to use for input.
"""
def __init__(self, pin_input):
self.pin_input = pin_input
|
dmcomm/dmcomm-python
|
lib/dmcomm/protocol/barcode.py
|
# This file is part of the DMComm project by BladeSabre. License: MIT.
"""
`dmcomm.protocol.barcode`
=========================
Functions for generating EAN-13 patterns.
"""
# https://en.wikipedia.org/wiki/International_Article_Number
_START_END = "101"
_CENTRE = "01010"
_CODES = {
"L": ["0001101", "0011001", "0010011", "0111101", "0100011", "0110001", "0101111", "0111011", "0110111", "0001011"],
"G": ["0100111", "0110011", "0011011", "0100001", "0011101", "0111001", "0000101", "0010001", "0001001", "0010111"],
"R": ["1110010", "1100110", "1101100", "1000010", "1011100", "1001110", "1010000", "1000100", "1001000", "1110100"],
}
_SELECT = ["LLLLLL", "LLGLGG", "LLGGLG", "LLGGGL", "LGLLGG", "LGGLLG", "LGGGLL", "LGLGLG", "LGLGGL", "LGGLGL"]
def ean13_bits(barcode_number: list) -> str:
result = [_START_END]
selection = _SELECT[barcode_number[0]]
for i in range(6):
digit = barcode_number[i + 1]
code = _CODES[selection[i]][digit]
result.append(code)
result.append(_CENTRE)
for i in range(6):
digit = barcode_number[i + 7]
code = _CODES["R"][digit]
result.append(code)
result.append(_START_END)
return "".join(result)
def run_lengths(seq) -> list:
if len(seq) == 0:
return []
result = []
prev = seq[0]
count = 1
for item in seq[1:]:
if item == prev:
count += 1
else:
result.append(count)
count = 1
prev = item
result.append(count)
return result
def ean13_lengths(barcode_number: list) -> list:
return run_lengths(ean13_bits(barcode_number))
|
ctrotz/seashell-generation
|
seashell.py
|
import math
import numpy as np
import matplotlib.pyplot as plt
from typing import Callable
from mpl_toolkits.mplot3d import Axes3D
class Seashell(object):
def __init__(self, r0: float, z0: float, growth: float, d_theta: float):
self.__base_radius = r0
self.__base_z = z0
self.__growth_rate = growth
self.__increment = d_theta
self.__base = pow(growth, 1/d_theta)
def __frenet_frame(self, t: float) -> np.ndarray:
vec1 = self.__first_partial(t)
vec1 /= np.linalg.norm(vec1)
vec3 = np.cross(vec1, self.__second_partial(t))
vec3 /= np.linalg.norm(vec3)
vec2 = np.cross(vec3, vec1)
return np.array([vec1, vec2, vec3])
def helicospiral(self, t: float) -> np.ndarray:
x = self.__base_radius * pow(self.__base, t) * np.cos(t)
y = self.__base_radius * pow(self.__base, t) * np.sin(t)
z = self.__base_z * pow(self.__base, t)
return np.array([x, y, z])
def __first_partial(self, t: float) -> np.ndarray:
x = self.__base_radius * (t * pow(self.__base, t - 1) * np.cos(t) - pow(self.__base, t) * np.sin(t))
y = self.__base_radius * (t * pow(self.__base, t - 1) * np.sin(t) + pow(self.__base, t) * np.cos(t))
z = t * self.__base_z * pow(self.__base, t - 1)
return np.array([x, y, z])
def __second_partial(self, t: float) -> np.ndarray:
x = self.__base_radius * pow(self.__base, t) * ((pow(np.log(self.__base), 2) - 1) * np.cos(t)
- 2 * np.log(self.__base) * np.sin(t))
y = self.__base_radius * pow(self.__base, t) * ((pow(np.log(self.__base), 2) - 1) * np.sin(t)
+ 2 * np.log(self.__base) * np.cos(t))
z = self.__base_z * pow(self.__base, t) * pow(np.log(self.__base), 2)
return np.array([x, y, z])
def generate_curve_sample(self, f: Callable[[float], np.ndarray], t: float, s: float):
pt = f(s)
scale = pow(self.__base, t)
pt *= scale
rot_mat = self.__frenet_frame(t).transpose()
pt = np.matmul(rot_mat, pt)
# print(pt)
pt += self.helicospiral(t)
return pt
def generate_curve_samples(self, f: Callable[[float], np.ndarray], t: float, n: int) -> list:
ss = np.linspace(0, 2 * np.pi, n)
samples = []
for s in ss:
samples.append(a.generate_curve_sample(f, t, s))
return samples
def generate_vertices_faces(self, f: Callable[[float], np.ndarray], t_max: float, n: int) -> tuple:
faces = []
cur = self.generate_curve_samples(f, 0, n) # first samples
vertices = cur
ts = np.linspace(0, t_max, math.floor(t_max/self.__increment))[1:]
for i in range(1, len(ts)):
cur = self.generate_curve_samples(f, ts[i], n)
faces.extend(self.generate_faces(n, i))
vertices.extend(cur)
return vertices, faces
def generate_faces(self, n, i):
assert i > 0
prev_offset = (i - 1) * n
cur_offset = i * n
faces = []
for j in range(n - 1):
v1_cur = j + 1 + cur_offset
v2_cur = j + cur_offset
v1_prev = j + 1 + prev_offset
v2_prev = j + prev_offset
faces.append([v1_cur, v1_prev, v2_cur])
faces.append([v2_cur, v1_prev, v2_prev])
v1_cur = cur_offset
v2_cur = (n-1) + cur_offset
v1_prev = prev_offset
v2_prev = (n-1) + prev_offset
faces.append([v1_cur, v1_prev, v2_cur])
faces.append([v2_cur, v1_prev, v2_prev])
return faces
if __name__ == "__main__":
a = Seashell(0.04, 1.9, 1.007, 0.174533)
def func(x): return np.array([np.cos(x), np.sin(x), 0]) * (1 + (1/10.0) * np.sin(10 * x))
vertices, faces = a.generate_vertices_faces(func, 30 * np.pi, 30)
file = open("test4.obj", "w")
for vertex in vertices:
file.write(f'v {vertex[0]} {vertex[1]} {vertex[2]}\n')
for face in faces:
file.write(f'f {face[0]} {face[1]} {face[2]}\n')
file.close()
# pts = []
# samples = []
# counter = 0
# for t in ts:
# pts.append(a.helicospiral(t))
# counter += 1
# if counter == 20:
# for s in ss:
# samples.append(a.generate_sample(func, t, s))
# counter = 0
#
# pts = np.array(pts)
#
# x = pts[:, 0]
# y = pts[:, 1]
# z = pts[:, 2]
#
#
# plt.rcParams['legend.fontsize'] = 10
#
# fig = plt.figure()
# ax = fig.gca(projection='3d')
#
# ax.plot(x, y, z, label='parametric curve')
# samples = np.array(samples)
# print(samples.shape)
# x = samples[:, 0]
# y = samples[:, 1]
# z = samples[:, 2]
#
# ax.plot(x, y, z, label='samples')
#
# ax.legend()
#
# plt.show()
# # for angle in range(0, 360):
# # ax.view_init(30, angle)
# # plt.draw()
# # plt.pause(.001)
|
tomoki171923/selenium-ci
|
src/common/const.py
|
class _const(object):
class ConstError(TypeError):
pass
def __setattr__(self, name, value):
if name in self.__dict__:
raise self.ConstError()
self.__dict__[name] = value
import sys
sys.modules[__name__] = _const()
|
tomoki171923/selenium-ci
|
case1_sample.py
|
# How to execute this file
# Executing the follow command.
# python3 ./SchoolQuotation_case3_reservation.py -v
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as ExpectedConditions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from src.common import myconst
from src.scenario import scenario
import unittest
import datetime
import pathlib
import os
import sys
import platform
import termcolor
import time
class case1_sample(scenario.Scenario):
# unittest上での事実上のコンストラクタ
@classmethod
def setUpClass(self):
super().setUpClass(classname)
# unittest上test実施前処理
def setUp(self):
self.setWebdriver()
self.toReservationPage()
# unittest上各test実施後処理
def tearDown(self):
# close chrome driver
self.driver.close()
# go to the reservation page.
def toReservationPage(self):
self.toPage(self.yaml['data']['url']['option'])
option_form = self.yaml['data']['form']['quotation']['option']
self.setSelectboxById(option_form['stay']['id'], option_form['stay']['text'])
self.clickById('btn-result')
self.scrollByClass('next-step')
self.clickByText('留学カウンセリング予約')
# 初期描画時のフォーム項目テスト
def execInitTest(self, case_name):
case_form = self.yaml['data']['form'][case_name]['set']
self.scrollByClass('form_sections')
self.getScreenshot(case_name ,'init')
self.scrollByName('comment')
self.getScreenshot(case_name ,'init')
# checkbox
case_form_check = case_form['check']['counselings']
checkbox_texts = list()
# 15は余裕値(今後checkboxが増えた時用)
for i in range(15):
id = case_form_check['id'] + str(i)
try:
element = self.driver.find_element_by_id(id)
# 補足:Nuxt 上ではvalue = labeltextでコーディングしている
checkbox_texts.append(element.get_attribute("value"))
except:
# element が見つからなかったらbreak
break
with self.subTest(msg=f"init checkbox test"):
self.assertEqual(checkbox_texts, case_form_check['values'])
# text box
case_form_text = case_form['text']
for form in case_form_text:
element = self.driver.find_element_by_name(case_form_text[form]['name'])
with self.subTest(msg=f"init text test"):
self.assertEqual(element.text, case_form_text[form]['text'])
# select option
case_form_option = case_form['option']
for form in case_form_option:
select, options = self.getSelectboxOptionsByName(case_form_option[form]['name'])
init_option = self.trimStr(select.all_selected_options[0].text)
with self.subTest(msg=f"init select test"):
self.assertEqual(options, case_form_option[form]['values'])
self.assertEqual(init_option, case_form_option[form]['text'])
# 各フォーム項目バリデーションテスト
def execValidationTest(self, case_name: str, case_type="error"):
case_form = self.yaml['data']['form'][case_name]
self.scrollByClass('form_sections')
self.setTextboxByName(case_form['set']['name'], case_form['set']['text'])
self.getScreenshot(case_name ,case_form['set']['name'])
if case_type == "error":
element = self.driver.find_element_by_class_name('err-text')
elif case_type == "success":
element = self.driver.find_element_by_class_name('alert_currect')
with self.subTest(msg=f"{case_form['set']['name']} validation test"):
self.assertEqual(
element.text, case_form['msg'])
# 各フォーム項目Null値テスト
def execNullTest(self, case_name: str):
case_form = self.yaml['data']['form'][case_name]
name = case_form['set']['name']
self.scrollByClass('form_sections')
element = self.driver.find_element_by_name(name)
self.getScreenshot(case_name ,name)
element.send_keys(Keys.TAB)
self.getScreenshot(case_name ,name)
element = self.driver.find_element_by_class_name('err-text')
with self.subTest(msg=f"{name} null test"):
self.assertEqual(
element.text, case_form['msg'])
# Submitボタン挙動テスト
def execSubmitTest(self, case_name, case_type="error"):
case_form = self.yaml['data']['form'][case_name]['set']
case_form_text = case_form['text']
self.scrollByClass('form_sections')
for form in case_form_text:
self.setTextboxByName(case_form_text[form]['name'], case_form_text[form]['text'])
case_form_option = case_form['option']
for form in case_form_option:
self.setSelectboxByName(case_form_option[form]['name'], case_form_option[form]['text'])
if 'radio' in case_form:
self.clickByClass(case_form['radio']['agree']['class'])
self.getScreenshot(case_name ,'submit')
self.scrollByName('comment')
submit = self.driver.find_element_by_id('submitBtn')
self.getScreenshot(case_name ,'submit')
with self.subTest(msg=f"submit test"):
if case_type=="error":
self.assertEqual(submit.is_enabled(), False)
elif case_type == "success":
self.assertEqual(submit.is_enabled(), True)
# ---------------------init item test begin
def test_case01(self):
self.execInitTest(sys._getframe().f_code.co_name)
# ---------------------init item test end
# ---------------------validation item test begin
def test_case02(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case03(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case04(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case05(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case06(self):
self.execNullTest(sys._getframe().f_code.co_name)
def test_case07(self):
self.execNullTest(sys._getframe().f_code.co_name)
def test_case08(self):
self.execNullTest(sys._getframe().f_code.co_name)
def test_case09(self):
self.execNullTest(sys._getframe().f_code.co_name)
def test_case10(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case11(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case12(self):
self.execValidationTest(sys._getframe().f_code.co_name , "success")
def test_case13(self):
self.execValidationTest(sys._getframe().f_code.co_name , "success")
def test_case14(self):
self.execValidationTest(sys._getframe().f_code.co_name , "success")
def test_case15(self):
self.execValidationTest(sys._getframe().f_code.co_name , "success")
def test_case16(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case17(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case18(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case19(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case20(self):
self.execValidationTest(sys._getframe().f_code.co_name , "success")
def test_case21(self):
self.execValidationTest(sys._getframe().f_code.co_name , "success")
def test_case22(self):
self.execValidationTest(sys._getframe().f_code.co_name , "success")
def test_case23(self):
self.execValidationTest(sys._getframe().f_code.co_name , "success")
def test_case24(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case25(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case26(self):
self.execValidationTest(sys._getframe().f_code.co_name)
def test_case27(self):
self.execValidationTest(sys._getframe().f_code.co_name)
# ---------------------validation item test end
# ---------------------submit test begin
def test_case28(self):
self.execSubmitTest(sys._getframe().f_code.co_name)
def test_case29(self):
self.execSubmitTest(sys._getframe().f_code.co_name)
def test_case30(self):
self.execSubmitTest(sys._getframe().f_code.co_name)
def test_case31(self):
self.execSubmitTest(sys._getframe().f_code.co_name , "success")
# ---------------------submit test end
if __name__ == '__main__':
date = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
classname = os.path.splitext(os.path.basename(__file__))[0]
myconst.cst.LOG_FOLDER = myconst.cst.LOG_FOLDER_PATH + myconst.cst.LOG_FOLDER_NAME + '_' + date + '_' + classname + '/'
os.makedirs(myconst.cst.LOG_FOLDER)
logpath = myconst.cst.LOG_FOLDER + classname + '.log'
#unittest.main()
with pathlib.Path(logpath).open('w') as fw:
date = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
fw.write(
f'******************* SELENIUM TEST START : {date} *******************\n'
'\n')
unittest.main(
testRunner=unittest.TextTestRunner(
stream=fw,
descriptions=False,
verbosity=2))
|
tomoki171923/selenium-ci
|
src/scenario/scenario.py
|
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as ExpectedConditions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from src.common import myconst
from src.common.selenium import Selenium
from PIL import ImageGrab
import os
import time
import unittest
import yaml
class Scenario(Selenium, unittest.TestCase):
# constructor of unittest class
@classmethod
def setUpClass(self,classname):
filepath = myconst.cst.MOCK_FOLDER_PATH + classname + '.yml'
with open(filepath) as file:
self.yaml = yaml.safe_load(file)
# destructor of unittest class
@classmethod
def tearDownClass(self):
pass
# the action before each of tests is executed in unittest
def setUp(self):
raise NotImplementedError()
# the action after each of tests is executed in unittest
def tearDown(self):
raise NotImplementedError()
|
tomoki171923/selenium-ci
|
src/common/myconst.py
|
<reponame>tomoki171923/selenium-ci
from src.common import const as cst
import platform
class Myconst:
#----------------------------------------------#
# CHROME DRIVER
#----------------------------------------------#
# DRIVER PATH
if 'macOS' in platform.platform():
cst.CHROME_DRIVER_PATH = '/usr/local/bin/chromedriver'
elif 'Windows' in platform.platform():
cst.CHROME_DRIVER_PATH = 'C:\\programs\\chromedriver'
# WHETHER TO USE BROWSER OR NOT (True / False)
cst.CHROME_DRIVER_BROWSER = True
# WINDOW SIZE (Width / Height)
cst.CHROME_DRIVER_WINDOW_SIZE = '1920,1080'
#----------------------------------------------#
# LOG
#----------------------------------------------#
cst.LOG_FOLDER_PATH = "log/"
cst.LOG_FOLDER_NAME = "seleniumci"
#----------------------------------------------#
# MOCKDATA
#----------------------------------------------#
cst.MOCK_FOLDER_PATH = "mockdata/"
#----------------------------------------------#
# USER
#----------------------------------------------#
cst.USER_EMAIL_ADULT = "<EMAIL>"
cst.USER_EMAIL_UNDERAGE = "<EMAIL>"
cst.USER_PASSWORD = "<PASSWORD>"
|
tomoki171923/selenium-ci
|
src/common/selenium.py
|
<reponame>tomoki171923/selenium-ci
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as ExpectedConditions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from src.common import myconst
from PIL import ImageGrab
import os
import time
import yaml
class Selenium:
# set webdriver
def setWebdriver(self):
# setting chrome driver
chrome_options = Options()
chrome_options.add_argument(f"--window-size={myconst.cst.CHROME_DRIVER_WINDOW_SIZE}")
if not myconst.cst.CHROME_DRIVER_BROWSER:
chrome_options.add_argument('--headless')
self.driver = webdriver.Chrome(
options=chrome_options,
executable_path= myconst.cst.CHROME_DRIVER_PATH)
# for wait loading
self.driver.implicitly_wait(10)
# for wait javascript function
self.driver.set_script_timeout(10)
# go to the root url if root url is existed
if 'url' in self.yaml['data']:
if self.yaml['data']['url'] is not None and 'root' in self.yaml['data']['url']:
self.driver.get(self.yaml['data']['url']['root'])
# go to the specified url page
def toPage(self, url):
self.driver.get(url)
WebDriverWait(
self.driver, 10).until(
ExpectedConditions.presence_of_all_elements_located)
# trimming blank character in first and last
def trimStr(self, str):
return str.lstrip().rstrip()
# waiting until display specific element
def waitDisplayElementByClass(self, class_name):
wait = WebDriverWait(self.driver, 10)
wait.until(ExpectedConditions.presence_of_element_located((By.CLASS_NAME, class_name)))
time.sleep(1)
# waiting until complete ajax action
def waitCompleteAjax(self):
wait = WebDriverWait(self.driver, 10)
wait.until(lambda driver: self.driver.execute_script(
"return jQuery.active == 0"))
time.sleep(1)
# waiting until display alert
def waitDisplayAlert(self):
wait = WebDriverWait(self.driver, 10)
wait.until(ExpectedConditions.alert_is_present())
time.sleep(1)
# save a screenshot
def getScreenshot(self, case_name, image_name=None, zoom_ratio=100):
script = "document.body.style.zoom='{}%'"
self.driver.execute_script(script.format(zoom_ratio))
if image_name is not None:
base_filepath = myconst.cst.LOG_FOLDER + case_name + '-' + image_name
else:
base_filepath = myconst.cst.LOG_FOLDER + case_name
index = 1
filepath = base_filepath + f"-{str(index).zfill(3)}" + '.png'
while(os.path.isfile(filepath)):
index += 1
filepath = base_filepath + f"-{str(index).zfill(3)}" + '.png'
self.driver.save_screenshot(filepath)
# save a screenshot (alert only, and target is main screen only)
# main screen -> If you use a laptop, laptop's screen is main screen.
def getAlertScreenshot(self, case_name):
img = ImageGrab.grab()
img.save(myconst.cst.LOG_FOLDER + case_name + '-alert.png')
# find & click the element by id.
def clickById(self, id):
self.driver.find_element_by_id(id).click()
# find & click the element by name. (It is the first element found.)
def clickByName(self, name):
self.driver.find_element_by_name(name).click()
# find & click the element by link text. (It is the first element found.)
def clickByText(self, text):
self.driver.find_element_by_partial_link_text(text).click()
# find & click the element by class. (It is the first element found.)
def clickByClass(self, classname):
self.driver.find_element_by_class_name(classname).click()
# scroll to the element.
def scroll(self, element):
self.driver.execute_script("arguments[0].scrollIntoView(true);", element)
# scroll to the element by id.
def scrollById(self, id):
element = self.driver.find_element_by_id(id)
self.scroll(element)
# scroll to the element by name. (It is the first element found.)
def scrollByName(self, name):
element = self.driver.find_element_by_name(name)
self.scroll(element)
# scroll to the element by link text. (It is the first element found.)
def scrollByText(self, text):
element = self.driver.find_element_by_partial_link_text(text)
self.scroll(element)
# scroll to the element by class. (It is the first element found.)
def scrollByClass(self, classname):
element = self.driver.find_element_by_class_name(classname)
self.scroll(element)
# set the value on the textbox by id.
def setTextboxById(self, id, value):
element = self.driver.find_element_by_id(id)
element.send_keys(value)
# set the value on the textbox by name. (It is the first element found.)
def setTextboxByName(self, name, value):
element = self.driver.find_element_by_name(name)
element.send_keys(value)
# set the value on the textbox by class. (It is the first element found.)
def setTextboxByClass(self, classname):
element = self.driver.find_element_by_class_name(classname)
element.send_keys(value)
# set the value on the selectbox by id.
def setSelectboxById(self, id, value):
select = Select(self.driver.find_element_by_id(id))
select.select_by_visible_text(value)
# set the value on the selectbox by name. (It is the first element found.)
def setSelectboxByName(self, name, value):
select = Select(self.driver.find_element_by_name(name))
select.select_by_visible_text(value)
# set the value on the selectbox by class. (It is the first element found.)
def setSelectboxByClass(self, classname):
select = Select(self.driver.find_element_by_class_name(classname))
select.select_by_visible_text(value)
# get options on the selectbox by id.
def getSelectboxOptionsById(self, id):
select = Select(self.driver.find_element_by_id(id))
option_texts = list()
for option in select.options:
text = self.trimStr(option.text)
option_texts.append(text)
return select, option_texts
# get options on the selectbox by name. (It is the first element found.)
def getSelectboxOptionsByName(self, name):
select = Select(self.driver.find_element_by_name(name))
option_texts = list()
for option in select.options:
text = self.trimStr(option.text)
option_texts.append(text)
return select, option_texts
|
gryf/weechat-replacer
|
replacer.py
|
<filename>replacer.py
# -*- coding: utf-8 -*-
"""
Simple replacer for substitution one keyword with some text using completion
mechanism from weechat.
add: add new replacement to table
del: remove key from table
Without any argument list of defined substitution will be displayed.
Script will replace any defined keyword with the text using tab completion. To
make this work, weechat.completion.default_template should be modified:
/set weechat.completion.default_template "%%(nicks)|%%(irc_channels)|%%(replacer_plugin)"
Examples:
/%(command)s add foo foobar
/%(command)s add testutf ½°C
/%(command)s del testutf
"""
import os
import json
import weechat
NAME = 'replacer'
AUTHOR = '<NAME> <<EMAIL>>'
VERSION = '1.3'
LICENSE = 'Apache 2'
DESC = 'Word replacer for WeeChat'
COMMAND = 'replacer'
COLOR_DELIMITERS = weechat.color('chat_delimiters')
COLOR_NICK = weechat.color('chat_nick')
COLOR_RESET = weechat.color('reset')
def _decode(string):
try:
return string.decode('utf-8')
except AttributeError:
return string
def _encode(string):
try:
# Encode only, if we have decode attribute, which is available for
# string only on python2
string.decode
return string.encode('utf-8')
except AttributeError:
return string
class Replacer(object):
"""Replacer"""
# This will keep reference to created Replacer object. We need it only
# one, so it also could be global, but globals are bad, mkay?
self_object = None
def __init__(self):
"""Initialize plugin"""
self.replacement_map = {}
self._path = self._locate_replacement_file()
self._get_replacement_map()
def _locate_replacement_file(self):
map_file = "replacement_map.json"
data_dirs = (weechat.info_get("weechat_data_dir", ""),
weechat.info_get("weechat_config_dir", ""),
weechat.string_eval_path_home("%h", {}, {}, {}))
for path in data_dirs:
if os.path.exists(os.path.join(path, map_file)):
return os.path.join(path, map_file)
# nothing found. so there is no replacement file. let's assume the
# right file path.
version = weechat.info_get("version_number", "") or 0
if version < 0x3020000: # < 3.2.0
path = '%h/' + map_file
return weechat.string_eval_path_home(path, {}, {}, {})
else:
return os.path.join(weechat.info_get("weechat_data_dir", ""),
map_file)
def _get_replacement_map(self):
"""Read json file, and assign it to the replacement_map attr"""
try:
with open(self._path) as fobj:
self.replacement_map = json.load(fobj)
except (IOError, ValueError):
pass
def add(self, key, value):
"""Add item to dict"""
self.replacement_map[key] = value
self._write_replacement_map()
def delete(self, key):
"""remove item from dict"""
try:
del self.replacement_map[key]
except KeyError:
return False
self._write_replacement_map()
return True
def _write_replacement_map(self):
"""Write replacement table to json file"""
with open(self._path, "w") as fobj:
json.dump(self.replacement_map, fobj)
def echo(msg, weechat_buffer, prefix=False, **kwargs):
"""
Print preformated message. Note, that msg and arguments should be str not
unicode.
"""
display_msg = msg
arg_dict = {'color_delimiters': COLOR_DELIMITERS,
'color_nick': COLOR_NICK,
'name': NAME,
'color_reset': COLOR_RESET}
if prefix:
display_msg = "%(symbol)s" + display_msg
arg_dict['symbol'] = weechat.prefix(prefix)
arg_dict.update(kwargs)
weechat.prnt(weechat_buffer, display_msg % arg_dict)
def inject_replacer_object(fun):
"""
Decorator for injecting replacer object into weechat callback functions,
since weechat doesn't support assignment of object method
"""
def wrapper(*args, **kwargs):
"""Wrapper"""
if not Replacer.self_object:
Replacer.self_object = Replacer()
return fun(Replacer.self_object, *args, **kwargs)
return wrapper
@inject_replacer_object
def replace_cmd(replacer_obj, _, weechat_buffer, args):
"""/replacer command implementation"""
if not args:
if not replacer_obj.replacement_map:
echo("No replacements defined", weechat_buffer, 'error')
else:
echo("Defined replacements:", weechat_buffer, 'network')
for key, value in sorted(replacer_obj.replacement_map.items()):
echo('%(key)s %(color_delimiters)s->%(color_reset)s %(val)s',
weechat_buffer, key=_encode(key), val=_encode(value))
return weechat.WEECHAT_RC_OK
cmd = args.split(' ')[0]
if cmd not in ('add', 'del'):
echo('Error in command /%(command)s %(args)s (help on command: /help '
'%(command)s)', weechat_buffer, 'error', args=args,
command=COMMAND)
return weechat.WEECHAT_RC_OK
if cmd == 'add':
key = args.split(' ')[1].strip()
value = ' '.join(args.split(' ')[2:]).strip()
replacer_obj.add(_decode(key), _decode(value))
echo('added: %(key)s %(color_delimiters)s->%(color_reset)s %(val)s',
weechat_buffer, 'network', key=key, val=value)
if cmd == 'del':
key = ' '.join(args.split(' ')[1:]).strip()
if not replacer_obj.delete(_decode(key)):
echo('No such keyword in replacement table: %(key)s',
weechat_buffer, 'error', key=key)
else:
echo('Successfully removed key: %(key)s', weechat_buffer,
'network', key=_encode(key))
return weechat.WEECHAT_RC_OK
@inject_replacer_object
def completion_cb(replacer_obj, data, completion_item, weechat_buffer,
completion):
"""Complete keys from replacement table for add/del command"""
for key in replacer_obj.replacement_map:
weechat.hook_completion_list_add(completion, _encode(key), 0,
weechat.WEECHAT_LIST_POS_SORT)
return weechat.WEECHAT_RC_OK
@inject_replacer_object
def replace_cb(replacer_obj, data, completion_item, weechat_buffer,
completion):
"""replace keyword with value from replacement table, if found"""
position = weechat.buffer_get_integer(weechat_buffer, 'input_pos')
input_line = weechat.buffer_get_string(weechat_buffer, 'input')
input_line = _decode(input_line)
if len(input_line) == 0:
return weechat.WEECHAT_RC_OK
if input_line[position - 1] == ' ':
return weechat.WEECHAT_RC_OK
if position > 0:
left_space_index = input_line.rfind(' ', 0, position - 1)
if left_space_index == -1:
left_space_index = 0
word = input_line[left_space_index:position].strip()
if word in replacer_obj.replacement_map:
replacement = replacer_obj.replacement_map[word]
if position >= len(input_line.strip()):
replacement += ' '
new_line = u''
if left_space_index:
new_line += input_line[:left_space_index] + u' '
new_line += replacement
new_position = len(new_line)
new_line += input_line[position:]
weechat.buffer_set(weechat_buffer, 'input', _encode(new_line))
weechat.buffer_set(weechat_buffer, 'input_pos', str(new_position))
return weechat.WEECHAT_RC_OK
def main():
"""Main entry"""
weechat.register(NAME, AUTHOR, VERSION, LICENSE, DESC, '', '')
weechat.hook_completion('replacer_plugin', 'Try to match last word with '
'those in replacement map keys, and replace it '
'with value.', 'replace_cb', '')
weechat.hook_completion('completion_cb', 'Complete replacement map keys',
'completion_cb', '')
weechat.hook_command(COMMAND, DESC, "[add <word> <text>|del <word>]",
__doc__ % {"command": COMMAND},
'add|del %(completion_cb)', 'replace_cmd', '')
if __name__ == "__main__":
main()
|
gryf/weechat-replacer
|
test_replacer.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import unittest
from unittest import mock
import tempfile
class Weechat(object):
"""Mock weechat interface"""
ACTION = '*'
ERROR = '=!='
NETWORK = '--'
JOIN = '-->'
QUIT = '<--'
WEECHAT_RC_OK = 0
WEECHAT_LIST_POS_SORT = 1
def __init__(self):
self.wbuffer = ''
self.completions = []
self.position = 0
self.line = ''
def register(self, *args, **kwargs):
pass
def color(self, color):
return color
def prnt(self, we_buff, msg):
self.wbuffer = msg
def prefix(self, arg):
_map = {'action': Weechat.ACTION,
'error': Weechat.ERROR,
'network': Weechat.NETWORK,
'join': Weechat.JOIN,
'quit': Weechat.QUIT}
return _map[arg]
def hook_completion(self, *args, **kwargs):
pass
def hook_command(self, *args, **kwargs):
pass
def hook_completion_list_add(self, completion, item, index, sort):
self.completions.append(item)
def buffer_get_integer(self, *args, **kwargs):
return self.position
def buffer_get_string(self, *args, **kwargs):
return self.line
def buffer_set(self, wbuffer, what, value):
_map = {'input': self._set_line,
'input_pos': self._set_position}
_map[what](value)
def _set_line(self, val):
self.line = val
def _set_position(self, val):
self.position = val
def string_eval_path_home(self, path, pointers, extra_vars, options):
return path
def info_get(self, key, args):
_map = {'weechat_data_dir': None,
'weechat_config_dir': None,
'version_number': 0x3020000}
return _map.get(key)
weechat = Weechat()
sys.modules['weechat'] = weechat
import replacer
class TestReplacer(unittest.TestCase):
@mock.patch('replacer.Replacer._locate_replacement_file')
def setUp(self, rfile):
fd, fname = tempfile.mkstemp()
os.close(fd)
rfile.return_value = fname
self._path = fname
self.repl = replacer.Replacer()
def tearDown(self):
self.repl = None
try:
os.unlink(self._path)
except OSError:
pass
def test_init(self):
self.assertDictEqual(self.repl.replacement_map, {})
def test_add(self):
self.repl.add('foo', 'bar')
self.assertDictEqual(self.repl.replacement_map, {'foo': 'bar'})
def test_delete(self):
self.repl.add('foo', 'bar')
self.assertFalse(self.repl.delete('baz'))
self.assertTrue(self.repl.delete('foo'))
self.assertDictEqual(self.repl.replacement_map, {})
class TestDummyTests(unittest.TestCase):
"""
This, somehow stupid test ensures, that process of reading default
replacer config file works
"""
def tearDown(self):
replacer.Replacer.self_object = None
@mock.patch('replacer.Replacer._locate_replacement_file')
def test_init(self, rfile):
rfile.return_value = 'dummy_path'
repl = replacer.Replacer()
self.assertIsInstance(repl.replacement_map, dict)
@mock.patch('replacer.Replacer._locate_replacement_file')
def test_main(self, rfile):
rfile.return_value = 'dummy_path'
replacer.Replacer.self_object = replacer.Replacer()
replacer.main()
@mock.patch('replacer.Replacer._locate_replacement_file')
def test_injector(self, rfile):
rfile.return_value = 'dummy_path'
def fun(first, *args, **kwargs):
return first
self.assertIsNone(replacer.Replacer.self_object)
robj = replacer.inject_replacer_object(fun)()
self.assertIsNotNone(replacer.Replacer.self_object)
self.assertIsInstance(robj, replacer.Replacer)
class TestFunctions(unittest.TestCase):
@mock.patch('replacer.Replacer._locate_replacement_file')
def setUp(self, rfile):
fd, fname = tempfile.mkstemp()
os.close(fd)
self._path = fname
rfile.return_value = fname
replacer.Replacer.self_object = replacer.Replacer()
self.rc = replacer.Replacer
def tearDown(self):
self.rc.self_object = None
try:
os.unlink(self._path)
except OSError:
pass
weechat.completions = []
def test_echo(self):
replacer.echo('a', None)
self.assertEqual(weechat.wbuffer, 'a')
replacer.echo('a', None, 'action')
self.assertEqual(weechat.wbuffer, '%sa' % Weechat.ACTION)
replacer.echo('something', None, 'network')
self.assertEqual(weechat.wbuffer, '%ssomething' % Weechat.NETWORK)
def test_replace_cmd(self):
replacer.replace_cmd(None, None, None)
self.assertIn(Weechat.ERROR, weechat.wbuffer)
self.assertIn('No replacements defined', weechat.wbuffer)
self.rc.self_object.replacement_map = {'foo': 'bar'}
replacer.replace_cmd(None, None, None)
self.assertEqual(weechat.wbuffer, 'foo chat_delimiters->reset bar')
args = 'foo bar bazz'
replacer.replace_cmd(None, None, args)
self.assertIn(Weechat.ERROR, weechat.wbuffer)
self.assertIn('Error in command', weechat.wbuffer)
args = 'add baz bazz'
replacer.replace_cmd(None, None, args)
self.assertEqual(weechat.wbuffer,
'--added: baz chat_delimiters->reset bazz')
self.assertDictEqual(self.rc.self_object.replacement_map,
{'foo': 'bar', 'baz': 'bazz'})
args = 'del baz'
replacer.replace_cmd(None, None, args)
self.assertEqual(weechat.wbuffer, '--Successfully removed key: baz')
args = 'del baz'
replacer.replace_cmd(None, None, args)
self.assertIn(Weechat.ERROR, weechat.wbuffer)
self.assertIn('No such keyword', weechat.wbuffer)
def test_completion_cb(self):
replacer.completion_cb(None, None, None, None)
self.rc.self_object.replacement_map = {'foo': 'bar'}
replacer.completion_cb(None, None, None, None)
self.assertEqual(weechat.completions, ['foo'])
def test_replace_cb(self):
replacer.replace_cb(None, None, None, None)
self.assertEqual(weechat.position, 0)
self.assertEqual(weechat.line, '')
self.rc.self_object.replacement_map = {'foo': 'Vestibulum ante'}
# quis foo cursus
# ^
weechat.line = 'quis foo cursus'
weechat.position = 8
replacer.replace_cb(None, None, None, None)
self.assertEqual(weechat.line, 'quis Vestibulum ante cursus')
# quis cursus foo
# ^
weechat.line = 'quis cursus foo'
weechat.position = 15
replacer.replace_cb(None, None, None, None)
self.assertEqual(weechat.line, 'quis cursus Vestibulum ante ')
# foo quis cursus
# ^
weechat.line = 'foo quis cursus'
weechat.position = 3
replacer.replace_cb(None, None, None, None)
self.assertEqual(weechat.line, 'Vestibulum ante quis cursus')
# quis cursus
# ^
weechat.line = 'quis cursus'
weechat.position = 5
replacer.replace_cb(None, None, None, None)
self.assertEqual(weechat.line, 'quis cursus')
class TestLocateWeeHome(unittest.TestCase):
@mock.patch('os.path.exists')
@mock.patch('weechat.string_eval_path_home')
@mock.patch('weechat.info_get')
def test_locate_replacement_file_data_dir(self, info_get, eval_path_home,
path_exists):
info_get.side_effect = ('foo', 'bar')
eval_path_home.side_effect = ('baz', )
path_exists.side_effect = (True, )
result = replacer.Replacer._locate_replacement_file(object)
self.assertEqual(result, 'foo/replacement_map.json')
@mock.patch('os.path.exists')
@mock.patch('weechat.string_eval_path_home')
@mock.patch('weechat.info_get')
def test_locate_replacement_file_config_dir(self, info_get, eval_path_home,
path_exists):
info_get.side_effect = ('foo', 'bar')
eval_path_home.side_effect = ('baz', )
path_exists.side_effect = (False, True)
result = replacer.Replacer._locate_replacement_file(object)
self.assertEqual(result, 'bar/replacement_map.json')
@mock.patch('os.path.exists')
@mock.patch('weechat.string_eval_path_home')
@mock.patch('weechat.info_get')
def test_locate_replacement_file_old_home(self, info_get, eval_path_home,
path_exists):
info_get.side_effect = ('foo', 'bar')
eval_path_home.side_effect = ('baz', )
path_exists.side_effect = (False, False, True)
result = replacer.Replacer._locate_replacement_file(object)
self.assertEqual(result, 'baz/replacement_map.json')
@mock.patch('os.path.exists')
@mock.patch('weechat.string_eval_path_home')
@mock.patch('weechat.info_get')
def test_locate_replacement_default_home_31(self, info_get, eval_path_home,
path_exists):
info_get.side_effect = ('foo', 'bar', 0x3010000)
eval_path_home.side_effect = ('baz', 'old/replacement_map.json')
path_exists.side_effect = (False, False, False)
result = replacer.Replacer._locate_replacement_file(object)
self.assertEqual(result, 'old/replacement_map.json')
@mock.patch('os.path.exists')
@mock.patch('weechat.string_eval_path_home')
@mock.patch('weechat.info_get')
def test_locate_replacement_default_home_32(self, info_get, eval_path_home,
path_exists):
info_get.side_effect = ('foo', 'bar', 0x3020000, 'new')
eval_path_home.side_effect = ('baz', )
path_exists.side_effect = (False, False, False)
result = replacer.Replacer._locate_replacement_file(object)
self.assertEqual(result, 'new/replacement_map.json')
if __name__ == '__main__':
unittest.main()
|
SBTMLab/AIM_2021
|
main/sensing.py
|
<reponame>SBTMLab/AIM_2021
import RPi.GPIO as GPIO
import spidev
import time
import numpy as np
# 형광분석법, 마스크먼지 측정
class sensing():
def __init__(self, ultraviolet_pin:int, visible_pin:int, light_channel=0):
self.ultraviolet_pin = ultraviolet_pin
self.visible_pin = visible_pin
self.light_channel = light_channel
self.spi = spidev.SpiDev()
self.spi.open(0,0)
self.spi.max_speed_hz = 1350000
self.dust_before = 0
self.dust_after = 0
def turn_LED_on(self, sec, brightness, visible=False, freq=1000.0):
if visible==True:
LED_pin = self.visible_pin
else:
LED_pin = self.ultraviolet_pin
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_pin, GPIO.OUT)
pwm = GPIO.PWM(LED_pin, freq)
pwm.start(brightness) # 0.0~100.0
time.sleep(sec)
pwm.stop()
GPIO.cleanup()
def analog_read(self):
r = self.spi.xfer2([1, (8+self.light_channel) << 4,0])
adc_out = ((r[1]&3)<<8) + r[2]
return adc_out
def light_sensor(self, accumulate_time:int):
data_list = list()
for _ in range(accumulate_time):
data = self.analog_read()
data_list.append(data)
time.sleep(1)
data_array = np.array(data_list)
return np.median(data_array)
# light_sensor 함수를 이용해서 self.dust_before와 self.dust_after에 값을 준 뒤에 실행!
def dust_variance(self):
return self.dust_after - self.dust_before
def dust_clear(self):
self.dust_before = 0
self.dust_after = 0
if __name__ == '__main__':
rasp = sensing(ultraviolet_pin=18, visible_pin=17, light_channel=0)
rasp.turn_LED_on(sec=100, brightness=70, visible=True)
# print(rasp.light_sensor(accumulate_time=20))
|
SBTMLab/AIM_2021
|
main/main.py
|
from bs4 import BeautifulSoup as bs
import requests
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pandas as pd
import cv2
from classification_model import classification_model
background_color = (211, 200, 86)
font_color = (255, 255, 255)
model = classification_model()
light_magnitude = None
dust_before = None
dust_after = None
reference_pos = np.random.randint(low=0, high=10, size=(20, 2))
reference_neg = np.random.randint(low=20, high=30, size=(30, 2))
rivo_weight, dust_weight = 1, 2
while True:
announce = np.full((700, 1000, 3), background_color, np.uint8)
text = "Press 'u' to check pathogen in your mask"
cv2.putText(announce, text, (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
text = "Press 'd' to check dust in your mask"
cv2.putText(announce, text, (50, 200), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
text = "Press 'k' to run weighted KNN algorithm"
cv2.putText(announce, text, (50, 350), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
text = "Press 'w' to check today's dust info"
cv2.putText(announce, text, (50, 500), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
text = "Press 'q' to exit"
cv2.putText(announce, text, (50, 650), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
cv2.imshow("announce", announce)
key = cv2.waitKey()
cv2.destroyWindow("announce")
if key == ord("u"):
announce_u = np.full((100, 1300, 3), background_color, np.uint8)
text = "Make sure the excel file is in the same directory and press any key"
cv2.putText(announce_u, text, (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
cv2.imshow("announce", announce_u)
cv2.waitKey()
light_magnitude = model.read_spectroscope(file_directory='20211024.xlsx', lower_bound=510, upper_bound=540)
elif key == ord("d"):
announce_d = np.full((200, 1300, 3), background_color, np.uint8)
text = "Press f if this is the first time you check dust in your mask"
cv2.putText(announce_d, text, (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
text = "Press s if this is the second time you check dust in your mask"
cv2.putText(announce_d, text, (50, 100), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
cv2.imshow("announce", announce_d)
text = "After press f or s, Enter dust info in console"
cv2.putText(announce_d, text, (50, 150), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
cv2.imshow("announce", announce_d)
key_d = cv2.waitKey()
dust_info = float(input("Enter dust info: \n"))
print("go back to the window")
if key_d == ord("f"):
dust_before = dust_info
elif key_d == ord("s"):
dust_after = dust_info
elif key == ord("k"):
announce_k = np.full((250, 1500, 3), background_color, np.uint8)
text = "Make sure riboflavin and dust have been measured and press any key"
cv2.putText(announce_k, text, (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
text = "(dust has to be measured twice)"
cv2.putText(announce_k, text, (50, 100), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
text = "(If there is no measurement, press f)"
cv2.putText(announce_k, text, (50, 150), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
cv2.imshow("announce", announce_k)
key_k = cv2.waitKey()
if key_k == ord("f"):
continue
dust_variance = dust_before - dust_after
data = np.array([light_magnitude, dust_variance])
model.weighted_KNN(K=5,
data=data,
reference=[reference_pos, reference_neg],
weight=np.array([rivo_weight, dust_weight]))
model.visualize()
elif key == ord("w"):
dust_list = list(model.get_dust_info())
if dust_list[0] == "좋음":
dust_list[0] = "good"
elif dust_list[0] == "보통":
dust_list[0] = "so so"
else:
dust_list[0] = "bad"
if dust_list[1] == "좋음":
dust_list[1] = "good"
elif dust_list[1] == "보통":
dust_list[1] = "so so"
else:
dust_list[1] = "bad"
announce_k = np.full((200, 1000, 3), background_color, np.uint8)
text = "fine dust: " + dust_list[0] + ", " + "ultra fine dust: " + dust_list[1]
cv2.putText(announce_k, text, (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
cv2.imshow("announce", announce_k)
cv2.waitKey()
elif key == ord("q"):
break
else:
err_announce = np.full((100, 700, 3), background_color, np.uint8)
err_text = "wrong input!! press any key"
cv2.putText(err_announce, err_text, (50, 50), cv2.FONT_HERSHEY_TRIPLEX, 1, font_color, 2, cv2.LINE_AA)
cv2.imshow("err_announce", err_announce)
cv2.waitKey()
|
SBTMLab/AIM_2021
|
main/classification_model.py
|
from bs4 import BeautifulSoup as bs
import requests
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pandas as pd
# dust info, KNN, visualize
class classification_model():
def __init__(self):
self.data = None
self.reference = None
self.weight = None
self.reference_pos = None
self.reference_neg = None
self.result = None
self.fine_dust = None
self.ultra_fine_dust = None
self.fine_dust_text = None
self.ultra_fine_dust_text = None
def get_dust_info(self):
html = requests.get('https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=서울특별시 서대문구 미세먼지')
soup = bs(html.text,'html.parser')
dust_data = str(soup.find('div',{'class':'detail_info lv2'}).findAll('dd')[0].contents[0])
ultra_html = requests.get('https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=서울특별시 서대문구 초미세먼지')
ultra_soup = bs(ultra_html.text,'html.parser')
ultra_dust_data = str(ultra_soup.find('div',{'class':'detail_info lv2'}).findAll('dd')[0].contents[0])
'''
self.fine_dust = dust_data[0].find('span',{'class':'num'}).text.split('㎍')[0]
self.ultra_fine_dust = dust_data[1].find('span',{'class':'num'}).text.split('㎍')[0]
self.fine_dust_text = dust_data[0].text.split('㎥')[-1]
self.ultra_fine_dust_text = dust_data[1].text.split('㎥')[-1]
return int(self.fine_dust), int(self.ultra_fine_dust), self.fine_dust_text, self.ultra_fine_dust_text
'''
return dust_data, ultra_dust_data
def read_spectroscope(self, file_directory, lower_bound, upper_bound):
read_data = pd.read_excel(file_directory, header=None, skiprows=7)
# print(read_data)
light_data = read_data[read_data[0] >= lower_bound]
light_data = light_data[light_data[0] <= upper_bound]
light_data_list = light_data[1].values.tolist()
light_array = np.array(light_data_list)
return light_array.mean()
def weighted_KNN(self, K: int, data: np.array, reference: list, weight: np.array):
self.data = data # shape: (n_data, n_feature)
self.reference = reference # len(reference) == 2, shape of element: (n_reference, n_feature)
self.weight = weight # shape: (n_feature, )
self.reference_pos = self.reference[0]
self.reference_neg = self.reference[1]
# got only one data or reference
if self.data.ndim == 1:
self.data = np.expand_dims(self.data, axis=0)
if self.reference_pos.ndim == 1:
self.reference_pos = np.expand_dims(self.reference_pos, axis=0)
if self.reference_neg.ndim == 1:
self.reference_neg = np.expand_dims(self.reference_neg, axis=0)
# for broadcasting
self.data = np.expand_dims(self.data, axis=1)
self.reference_pos = np.expand_dims(self.reference_pos, axis=0)
self.reference_neg = np.expand_dims(self.reference_neg, axis=0)
# weighted L1 distance
distance_pos = np.abs(self.data - self.reference_pos) * self.weight
distance_neg = np.abs(self.data - self.reference_neg) * self.weight
distance_total = np.concatenate([distance_pos, distance_neg], axis=1).sum(axis=-1)
# distance sorting & classification
distance_argsort = np.argsort(distance_total, axis=-1)[..., :K]
distance_neg_cnt = (distance_argsort >= self.reference_pos.shape[1]).sum(axis=-1)
self.result = np.where(distance_neg_cnt > (K-1)/2, 1, 0) # integer K has to be an odd number and smaller than number of references
return self.result
def visualize(self):
plt.style.use('seaborn')
self.data = self.data.squeeze()
if self.data.ndim == 1:
self.data = np.expand_dims(self.data, axis=0)
self.reference_pos = self.reference_pos.squeeze()
if self.reference_pos.ndim == 1:
self.reference_pos = np.expand_dims(self.reference_pos, axis=0)
self.reference_neg = self.reference_neg.squeeze()
if self.reference_neg.ndim == 1:
self.reference_neg = np.expand_dims(self.reference_neg, axis=0)
cmap = cm.get_cmap('rainbow', lut=2)
n_feature = self.weight.shape[0]
if n_feature == 2:
fig, ax = plt.subplots(figsize=(10, 5))
ax.scatter(self.reference_pos[..., 0], self.reference_pos[..., 1], color=cmap(0), alpha=0.3)
ax.scatter(self.reference_neg[..., 0], self.reference_neg[..., 1], color=cmap(1), alpha=0.3)
for data_idx, data in enumerate(self.data):
ax.scatter(data[0], data[1], color=cmap(self.result[data_idx]), marker='*')
ax.set_xlabel("Riboflavin", fontsize=15)
ax.set_ylabel("Dust", fontsize=15)
# for legend
ax.scatter([], [], color=cmap(0), label='positive')
ax.scatter([], [], color=cmap(1), label='negative')
ax.scatter([], [], color='k', marker='*', label='data')
ax.scatter([], [], color='k', marker='o', label='reference')
ax.legend(loc='upper left',
bbox_to_anchor=(1, 1),
ncol=2)
elif n_feature == 3:
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(projection='3d')
fig.subplots_adjust(bottom=0, top=1,
left=0, right=1)
ax.set_xlabel("Riboflavin", fontsize=20, labelpad=20)
ax.set_ylabel("Dust", fontsize=20, labelpad=20)
ax.set_zlabel("damaged", fontsize=20, labelpad=20)
ax.scatter(self.reference_pos[..., 0], self.reference_pos[..., 1], self.reference_pos[..., 2],
color=cmap(0),
alpha=0.3,
s=50)
ax.scatter(self.reference_neg[..., 0], self.reference_neg[..., 1], self.reference_neg[..., 2],
color=cmap(1),
alpha=0.3,
s=50)
for data_idx, data in enumerate(self.data):
ax.scatter(data[0], data[1], data[2],
color=cmap(self.result[data_idx]),
marker='*',
s=50)
# for legend
ax.scatter([], [], [], color=cmap(0), label='positive')
ax.scatter([], [], [], color=cmap(1), label='negative')
ax.scatter([], [], [], color='k', marker='*', label='data')
ax.scatter([], [], [], color='k', marker='o', label='reference')
plt.legend(loc="upper left")
fig.tight_layout()
plt.show()
if __name__ == "__main__":
reference_pos = np.random.randint(low=0, high=10, size=(20, 2))
reference_neg = np.random.randint(low=20, high=30, size=(30, 2))
data = np.random.randint(low=0, high=30, size=(2, ))
model = classification_model()
'''model.weighted_KNN(K=5,
data=data,
reference=[reference_pos, reference_neg],
weight=np.array([1, 3]))
model.visualize()'''
print(model.get_dust_info())
print(model.read_spectroscope(file_directory='20211024.xlsx', lower_bound=510, upper_bound=540))
|
anuar12/relational_pose
|
lib/models/pose_resnet.py
|
<reponame>anuar12/relational_pose
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by <NAME> (<EMAIL>)
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import logging
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
import torch.utils.checkpoint as checkpoint
BN_MOMENTUM = 0.1
logger = logging.getLogger(__name__)
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(
in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False
)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,
bias=False)
self.bn3 = nn.BatchNorm2d(planes * self.expansion,
momentum=BN_MOMENTUM)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class RNOutputModel(nn.Module):
def __init__(self, f_hid, size_out):
super(RNOutputModel, self).__init__()
self.size_out = size_out
self.fc2 = nn.Linear(f_hid, f_hid)
self.fc2_bn = nn.BatchNorm1d(f_hid)
self.fc3 = nn.Linear(f_hid, size_out)
def forward(self, x):
x = self.fc2(x).permute(0, 2, 1)
x = self.fc2_bn(x).permute(0, 2, 1)
x = F.relu(x)
x = self.fc3(x)
#x = x.view(1, (self.inp_dim_size**2)*self.size_out)
return x
class GModule(nn.Module):
def __init__(self, f, f_hid):
super(GModule, self).__init__()
self.g_fc1 = nn.Linear(2*(f+2), f_hid)
self.g_fc2 = nn.Linear(f_hid, f_hid)
self.g_fc3 = nn.Linear(f_hid, f_hid)
#self.g_fc4 = nn.Linear(f_hid, f_hid)
self.g_fc1_bn = nn.BatchNorm1d(f_hid)
self.g_fc2_bn = nn.BatchNorm1d(f_hid)
self.g_fc3_bn = nn.BatchNorm1d(f_hid)
#self.g_fc4_bn = nn.BatchNorm1d(f_hid)
def forward(self, x):
x_ = self.g_fc1(x).permute(0, 2, 1)
x_ = self.g_fc1_bn(x_).permute(0, 2, 1)
x_ = F.relu(x_)
x_ = self.g_fc2(x_).permute(0, 2, 1)
x_ = self.g_fc2_bn(x_).permute(0, 2, 1)
x_ = F.relu(x_)
x_ = self.g_fc3(x_).permute(0, 2, 1)
x_ = self.g_fc3_bn(x_).permute(0, 2, 1)
x_ = F.relu(x_)
#x_ = self.g_fc4(x_).permute(0, 2, 1)
#x_ = self.g_fc4_bn(x_).permute(0, 2, 1)
#x_ = F.relu(x_)
return x_
class RelationalNetwork(nn.Module):
def __init__(self, b, d, f, f_hid, is_cuda=True):
"""
b - batch size
d - dimension of the image (assuming it's square)
h - height of the feature map
w - width of the feature map
f - number of features (corresponds to number of joints)
"""
super(RelationalNetwork, self).__init__()
self.f_hid = f_hid
self.g = GModule(f, f_hid)
self.affine_aggregate = nn.Linear(d * d, 1)
#aself.f_fc1 = nn.Linear(f_hid, f_hid)
#self.f_fc1_bn = nn.BatchNorm1d(f_hid)
self.coord_oi = torch.FloatTensor(b, 2)
self.coord_oj = torch.FloatTensor(b, 2)
if is_cuda:
self.coord_oi = self.coord_oi.cuda()
self.coord_oj = self.coord_oj.cuda()
self.coord_oi = Variable(self.coord_oi)
self.coord_oj = Variable(self.coord_oj)
# prepare coord tensor
def cvt_coord(i, d):
return [( (i+1) / d - d/2) / (d/2), ( (i+1) % d - d/2) / (d/2)]
self.coord_tensor = torch.FloatTensor(b, d**2, 2)
if is_cuda:
self.coord_tensor = self.coord_tensor.cuda()
self.coord_tensor = Variable(self.coord_tensor)
np_coord_tensor = np.zeros((b, d**2, 2))
for i in range(d**2):
np_coord_tensor[:, i, :] = np.array(cvt_coord(i, d))
self.coord_tensor.data.copy_(torch.from_numpy(np_coord_tensor))
self.fcout = RNOutputModel(f_hid, f) # TODO: argument is number of joints
def custom(self, module):
def custom_forward(*inputs):
inputs = module(inputs[0])
return inputs
return custom_forward
def forward(self, x):
# x.shape = (b x n_channels x d x d)
b = x.size()[0]
n_channels = x.size()[1]
d = x.size()[2]
# x_flat = (64 x 25 x 24)
x_flat = x.view(b, n_channels, d * d).permute(0, 2, 1)
# add coordinates
if b != self.coord_tensor.shape: # due to last batch != cfg.BATCH_SIZE
self.coord_tensor = self.coord_tensor[:b, ...]
x_flat = torch.cat([x_flat, self.coord_tensor], 2)
# cast all pairs against each other
x_i = torch.unsqueeze(x_flat, 1) # (b x 1 x d^2 x f+2)
x_i = x_i.repeat(1, d**2, 1, 1) # (b x d^2 x d^2 x f+2)
x_j = torch.unsqueeze(x_flat, 2) # (b x d^2 x 1 x f+2)
x_j = x_j.repeat(1, 1, d**2, 1) # (b x d^2 x d^2 x f+2)
# concatenate all together
x_full = torch.cat([x_i, x_j], 3) # (b x d^2 x d^2 x 2*(f+2))
# reshape for passing through network
x_ = x_full.view(b, d * d * d * d, 2*(n_channels+2))
x_ = checkpoint.checkpoint(self.custom(self.g), x_)
# reshape again and sum
x_g = x_.view(b, d * d, d * d, self.f_hid)
#x_g = x_g.sum(2).squeeze()
x_g = x_g.permute(0, 1, 3, 2)
x_g = self.affine_aggregate(x_g).squeeze()
x_g = x_g.view(b, d * d, self.f_hid)
"""f"""
x_f = self.f_fc1(x_g).permute(0, 2, 1)
x_f = self.f_fc1_bn(x_f).permute(0, 2, 1)
x_f = F.relu(x_f)
out = self.fcout(x_f)
out = out.view(b, d, d, n_channels).permute(0, 3, 1, 2)
return out
class PoseResNet(nn.Module):
def __init__(self, block, layers, cfg, **kwargs):
self.inplanes = 64
extra = cfg.MODEL.EXTRA
self.deconv_with_bias = extra.DECONV_WITH_BIAS
super(PoseResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64, momentum=BN_MOMENTUM)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
# used for deconv layers
self.deconv_layers = self._make_deconv_layer(
extra.NUM_DECONV_LAYERS,
extra.NUM_DECONV_FILTERS,
extra.NUM_DECONV_KERNELS,
)
self.final_layer = nn.Conv2d(
in_channels=extra.NUM_DECONV_FILTERS[-1],
out_channels=cfg.MODEL.NUM_JOINTS,
kernel_size=extra.FINAL_CONV_KERNEL,
stride=1,
padding=1 if extra.FINAL_CONV_KERNEL == 3 else 0
)
self.rn = RelationalNetwork(cfg.TRAIN.BATCH_SIZE_PER_GPU,
int(cfg.MODEL.HEATMAP_SIZE[0]), # * 0.875),
cfg.MODEL.NUM_JOINTS,
128,
is_cuda=True)
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion, momentum=BN_MOMENTUM),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def _get_deconv_cfg(self, deconv_kernel, index):
if deconv_kernel == 4:
padding = 1
output_padding = 0
elif deconv_kernel == 3:
padding = 1
output_padding = 1
elif deconv_kernel == 2:
padding = 0
output_padding = 0
return deconv_kernel, padding, output_padding
def _make_deconv_layer(self, num_layers, num_filters, num_kernels):
assert num_layers == len(num_filters), \
'ERROR: num_deconv_layers is different len(num_deconv_filters)'
assert num_layers == len(num_kernels), \
'ERROR: num_deconv_layers is different len(num_deconv_filters)'
layers = []
for i in range(num_layers):
kernel, padding, output_padding = \
self._get_deconv_cfg(num_kernels[i], i)
planes = num_filters[i]
layers.append(
nn.ConvTranspose2d(
in_channels=self.inplanes,
out_channels=planes,
kernel_size=kernel,
stride=2,
padding=padding,
output_padding=output_padding,
bias=self.deconv_with_bias))
layers.append(nn.BatchNorm2d(planes, momentum=BN_MOMENTUM))
layers.append(nn.ReLU(inplace=True))
self.inplanes = planes
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.deconv_layers(x)
x = self.final_layer(x)
#x = F.interpolate(x, size=(42, 42), mode='bilinear')
#for_vis = x.data.cpu()[0, :3, :, :]
#for_vis = np.transpose(for_vis, (1, 2, 0))
#print(for_vis.shape)
#plt.imshow(for_vis)
#plt.show()
#plt.close()
x = self.rn(x)
#x = F.interpolate(x, size=(48, 48), mode='bilinear')
return x
def init_weights(self, pretrained=''):
if os.path.isfile(pretrained):
logger.info('=> init deconv weights from normal distribution')
for name, m in self.deconv_layers.named_modules():
if isinstance(m, nn.ConvTranspose2d):
logger.info('=> init {}.weight as normal(0, 0.001)'.format(name))
logger.info('=> init {}.bias as 0'.format(name))
nn.init.normal_(m.weight, std=0.001)
if self.deconv_with_bias:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
logger.info('=> init {}.weight as 1'.format(name))
logger.info('=> init {}.bias as 0'.format(name))
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
logger.info('=> init final conv weights from normal distribution')
for m in self.final_layer.modules():
if isinstance(m, nn.Conv2d):
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
logger.info('=> init {}.weight as normal(0, 0.001)'.format(name))
logger.info('=> init {}.bias as 0'.format(name))
nn.init.normal_(m.weight, std=0.001)
nn.init.constant_(m.bias, 0)
pretrained_state_dict = torch.load(pretrained)
logger.info('=> loading pretrained model {}'.format(pretrained))
self.load_state_dict(pretrained_state_dict, strict=False)
else:
logger.info('=> init weights from normal distribution')
for m in self.modules():
if isinstance(m, nn.Conv2d):
# nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
nn.init.normal_(m.weight, std=0.001)
# nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.ConvTranspose2d):
nn.init.normal_(m.weight, std=0.001)
if self.deconv_with_bias:
nn.init.constant_(m.bias, 0)
#elif isinstance(m, nn.Linear):
# nn.init.normal_(m.weight, std=0.001)
# nn.init.constant_(m.bias, 0)
resnet_spec = {
18: (BasicBlock, [2, 2, 2, 2]),
34: (BasicBlock, [3, 4, 6, 3]),
50: (Bottleneck, [3, 4, 6, 3]),
101: (Bottleneck, [3, 4, 23, 3]),
152: (Bottleneck, [3, 8, 36, 3])
}
def get_pose_net(cfg, is_train, **kwargs):
num_layers = cfg.MODEL.EXTRA.NUM_LAYERS
block_class, layers = resnet_spec[num_layers]
model = PoseResNet(block_class, layers, cfg, **kwargs)
if is_train and cfg.MODEL.INIT_WEIGHTS:
model.init_weights(cfg.MODEL.PRETRAINED)
return model
|
mclt0568/Discord.py-bot-system
|
bot_Main.py
|
<reponame>mclt0568/Discord.py-bot-system
# Copyright (c) 2018 mclt0568 (For more information see LICENCE)
import bot_config as cfg
import bot_log as log
import bot_check as check
#Init
config = cfg.init(r"C:\Users\USER\Desktop\Python Project\DISCORDBOTS2")
config.initdirs()
INITCFG = config.initconfig()
INITSTR = config.initstrs()
logoption = log.log_option(r"C:\Users\USER\Desktop\Python Project\DISCORDBOTS2")
logs = log.logs(logoption.getfileinfo())
logs.log("Hello world")
|
mclt0568/Discord.py-bot-system
|
bot_check.py
|
<reponame>mclt0568/Discord.py-bot-system
# Copyright (c) 2018 mclt0568 (For more information see LICENCE)
|
mclt0568/Discord.py-bot-system
|
bot_log.py
|
# Copyright (c) 2018 mclt0568 (For more information see LICENCE)
import sys
import bot_config as cfg
from time import gmtime, strftime
from datetime import datetime
class log_option:
def __init__ (self,_path):
global INITCFG
config = cfg.init(_path)
INITCFG = config.initconfig()
self.path = _path
"""settings about the logs"""
def set_bracket(self,open_bracket:str,close_bracket:str):
"""the breakets while displaing the time, date, information etc"""
global BRACKETS
BRACKETS = [open_bracket,close_bracket]
return BRACKETS
def set_filenames(self,filename_prefix:str,filename_suffix):
"""the prefix and suffix of the file name that saves the logs to"""
global FILENAME
FILENAME = [filename_prefix,filename_suffix]
return FILENAME
def set_writemode(self,mode="a",encoding="utf8"):
"""set the write mode for log files"""
global WRITEMODE
WRITEMODE = {
"mode":mode,
"encoding":encoding
}
return WRITEMODE
def getfileinfo(self):
global INITCFG
fileinfo = [self.path,INITCFG["logcount"]]
return fileinfo
class logs:
def __init__(self,fileinfo,_BRACKETS=["[","]"],_FILENAME=["BOT_LOG",".txt"],_WRITEMODE={"mode":"a","encoding":"utf8"}):
self.BRACKETS = _BRACKETS
self.FILENAME = _FILENAME
self.WRITEMODE = _WRITEMODE
self.FILEINFO = fileinfo
self.count = self.update_file()
def update_file(self):
try:
with open(self.FILEINFO[0]+"\\logs\\"+self.FILEINFO[1],"r") as a:
data = str(int(a.read())+1)
with open(self.FILEINFO[0]+"\\logs\\"+self.FILEINFO[1],"w+") as a:
a.write(data)
return str(int(data)-1)
except Exception:
with open(self.FILEINFO[0]+"\\logs\\"+self.FILEINFO[1],"w+") as a:
a.write("0")
return 0
def log(self,text,tags:list=[]):
time_now = self.BRACKETS[0]+str(datetime.now())+self.BRACKETS[1]
prefix = ""
prefix += (time_now+self.BRACKETS[0]+"LOG"+self.BRACKETS[1])
for item in tags:
prefix += self.BRACKETS[0]+item+self.BRACKETS[1]
output_text = prefix + text + "\n"
sys.stdout.write(output_text)
filename = self.FILENAME[0] + str(self.count) + self.FILENAME[1]
with open(self.FILEINFO[0]+"\\logs\\"+filename,self.WRITEMODE["mode"],encoding=self.WRITEMODE["encoding"]) as w:
w.write(output_text)
def log_error(self,text,tags:list=[]):
time_now = self.BRACKETS[0]+str(datetime.now())+self.BRACKETS[1]
prefix = ""
prefix += (time_now+self.BRACKETS[0]+"ERROR"+self.BRACKETS[1])
for item in tags:
prefix += self.BRACKETS[0]+item+self.BRACKETS[1]
output_text = prefix + text + "\n"
sys.stdout.write(output_text)
filename = self.FILENAME[0] + str(self.count) + self.FILENAME[1]
with open(self.FILEINFO[0]+"\\logs\\"+filename,self.WRITEMODE["mode"],encoding=self.WRITEMODE["encoding"]) as w:
w.write(output_text)
def log_warn(self,text,tags:list=[]):
time_now = self.BRACKETS[0]+str(datetime.now())+self.BRACKETS[1]
prefix = ""
prefix += (time_now+self.BRACKETS[0]+"WARN"+self.BRACKETS[1])
for item in tags:
prefix += self.BRACKETS[0]+item+self.BRACKETS[1]
output_text = prefix + text + "\n"
sys.stdout.write(output_text)
filename = self.FILENAME[0] + str(self.count) + self.FILENAME[1]
with open(self.FILEINFO[0]+"\\logs\\"+filename,self.WRITEMODE["mode"],encoding=self.WRITEMODE["encoding"]) as w:
w.write(output_text)
def log_event(self,text,tags:list=[]):
time_now = self.BRACKETS[0]+str(datetime.now())+self.BRACKETS[1]
prefix = ""
prefix += (time_now+self.BRACKETS[0]+"EVENT"+self.BRACKETS[1])
for item in tags:
prefix += self.BRACKETS[0]+item+self.BRACKETS[1]
output_text = prefix + text + "\n"
sys.stdout.write(output_text)
filename = self.FILENAME[0] + str(self.count) + self.FILENAME[1]
with open(self.FILEINFO[0]+"\\logs\\"+filename,self.WRITEMODE["mode"],encoding=self.WRITEMODE["encoding"]) as w:
w.write(output_text)
if __name__ == "__main__":
print("Please import to other file.")
input("Press Enter to Exit...")
|
hamzaalalach/casting-cap-api
|
src/app.py
|
import os
import sys
from flask import Flask, request, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
# To be able to recognize relative imports
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from models import setup_db, create_all, Actor, Movie
from auth import AuthError, requires_auth
ELEMENTS_PER_PAGE = 10
def get_elements_paginated(elements, page):
start = (page - 1) * ELEMENTS_PER_PAGE
end = start + ELEMENTS_PER_PAGE
formatted_elements = [element.format() for element in elements]
return formatted_elements[start:end]
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__)
CORS(app)
setup_db(app)
@app.after_request
def after_request(response):
response.headers.add('Access-Controll-Allow-Headers',
'Content-Type, Authorization, true')
response.headers.add('Access-Controll-Allow-Methods',
'GET, PATCH, POST, DELETE, OPTIONS')
return response
@app.route('/actors')
@requires_auth('get:actors')
def get_actors():
all_actors = Actor.query.order_by('id').all()
page = request.args.get('page', 1, int)
selected_actors = get_elements_paginated(all_actors, page)
if len(selected_actors) == 0:
abort(404)
return jsonify({
'total_actors': len(selected_actors),
'actors': selected_actors,
'success': True
})
@app.route('/actors', methods=['POST'])
@requires_auth('post:actors')
def create_actor():
body = request.get_json()
try:
actor = Actor(body['name'],
body['age'],
body['gender'])
actor.insert()
return jsonify({
'success': True,
'created': actor.id
})
except BaseException:
print(sys.exc_info())
abort(422)
@app.route('/actors/<id>', methods=['DELETE'])
@requires_auth('delete:actors')
def delete_actor(id):
actor = Actor.query.filter_by(id=id).one_or_none()
if not actor:
abort(404)
try:
actor.delete()
return jsonify({
'deleted': id,
'success': True
})
except BaseException:
abort(422)
@app.route('/actors/<id>', methods=['PATCH'])
@requires_auth('patch:actors')
def edit_actor(id):
actor = Actor.query.filter_by(id=id).one_or_none()
if not actor:
abort(404)
try:
body = request.get_json()
print(body)
age = body.get('age')
name = body.get('name')
gender = body.get('gender')
# Make sure we only change values if provided in request body
if age:
actor.age = age
if name:
actor.name = name
if gender:
actor.gender = gender
actor.update()
return jsonify({
'success': True,
'edited': id
})
except BaseException:
print(sys.exc_info())
abort(422)
@app.route('/movies')
@requires_auth('get:movies')
def get_movies():
all_movies = Movie.query.order_by('id').all()
page = request.args.get('page', 1, int)
selected_movies = get_elements_paginated(all_movies, page)
if len(selected_movies) == 0:
abort(404)
return jsonify({
'total_movies': len(selected_movies),
'movies': selected_movies,
'success': True
})
@app.route('/movies', methods=['POST'])
@requires_auth('post:movies')
def create_movie():
body = request.get_json()
try:
movie = Movie(body['title'],
body['release_date'])
movie.insert()
return jsonify({
'success': True,
'created': movie.id
})
except BaseException:
print(sys.exc_info())
abort(422)
@app.route('/movies/<id>', methods=['DELETE'])
@requires_auth('delete:movies')
def delete_movie(id):
movie = Movie.query.filter_by(id=id).one_or_none()
if not movie:
abort(404)
try:
movie.delete()
return jsonify({
'deleted': id,
'success': True
})
except BaseException:
abort(422)
@app.route('/movies/<id>', methods=['PATCH'])
@requires_auth('patch:movies')
def edit_movie(id):
movie = Movie.query.filter_by(id=id).one_or_none()
if not movie:
abort(404)
try:
body = request.get_json()
title = body.get('title')
# Make sure we only change values if provided in request body
release_date = body.get('release_date')
if title:
movie.title = title
if release_date:
movie.release_date = release_date
movie.update()
return jsonify({
'success': True,
'edited': id
})
except BaseException:
print(sys.exc_info())
abort(422)
# Handle errors used across the app
@app.errorhandler(422)
def unprocessable(error):
return jsonify({
'success': False,
'error': 422,
'message': 'unprocessable'
}), 422
@app.errorhandler(404)
def not_found(error):
return jsonify({
'success': False,
'error': 404,
'message': 'resource not found'
}), 404
@app.errorhandler(405)
def not_allowed(error):
return jsonify({
'success': False,
'error': 405,
'message': 'method not allowed'
}), 405
@app.errorhandler(401)
def unauthorized(error):
return jsonify({
'success': False,
'error': 401,
'message': 'unauthorized'
}), 401
@app.errorhandler(500)
def internal_server_error(error):
return jsonify({
'success': False,
'error': 500,
'message': 'internal server error'
}), 500
@app.errorhandler(AuthError)
def auth_error(auth_res):
return jsonify({
'success': False,
'error': auth_res.error['code'],
'message': auth_res.error['description']
}), auth_res.status_code
return app
app = create_app()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
|
hamzaalalach/casting-cap-api
|
src/test_app.py
|
<reponame>hamzaalalach/casting-cap-api<filename>src/test_app.py<gh_stars>0
import unittest
import json
import os
from flask_sqlalchemy import SQLAlchemy
from app import create_app
from models import setup_db, Movie, Actor
def get_last_element_id(element):
elements = element.query.order_by('id').all()
return str(elements[len(elements) - 1].format()['id'])
def get_auth_header(token_for):
return {'Authorization': 'Bearer ' + os.environ.get(token_for)}
class CapstoneTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app()
self.client = self.app.test_client
self.database_name = "capstone_test"
self.database_path = "postgres://postgres:0000@{}/{}".format(
'localhost:5432', self.database_name)
setup_db(self.app, self.database_path)
with self.app.app_context():
self.db = SQLAlchemy()
self.db.init_app(self.app)
self.db.create_all()
self.new_actor = {
'name': '<NAME>',
'age': 40,
'gender': 'Male'
}
self.new_movie = {
'title': 'The Hobbit: The Battle of the Five Armies',
'release_date': '1 December 2014'
}
def tearDown(self):
pass
def test_get_actors_200(self):
res = self.client().get('/actors',
headers=get_auth_header('PRODUCER'))
data = json.loads(res.data)
self.assertEqual(res.status_code, 200)
self.assertTrue(data['actors'])
self.assertEqual(data['total_actors'], 1)
self.assertTrue(data['success'])
def test_get_actors_404(self):
res = self.client().get('/actors?page=1000',
headers=get_auth_header('PRODUCER'))
self.assertEqual(res.status_code, 404)
def test_post_actors_200(self):
res = self.client().post('/actors', json=self.new_actor,
headers=get_auth_header('PRODUCER'))
data = json.loads(res.data)
last_id = get_last_element_id(Actor)
self.assertEqual(res.status_code, 200)
self.assertTrue(data['success'])
self.assertEqual(data['created'], int(last_id))
def test_post_actors_422(self):
res = self.client().post('/actors', json={},
headers=get_auth_header('PRODUCER'))
data = json.loads(res.data)
self.assertEqual(res.status_code, 422)
self.assertFalse(data['success'])
def test_patch_actors_200(self):
last_id = get_last_element_id(Actor)
res = self.client().patch(
'/actors/' + last_id,
json={
'age': 67},
headers=get_auth_header('PRODUCER'))
data = json.loads(res.data)
actor = Actor.query.get(last_id)
self.assertEqual(res.status_code, 200)
self.assertEqual(actor.age, 67)
self.assertTrue(data['success'])
self.assertEqual(data['edited'], last_id)
def test_patch_actors_404(self):
res = self.client().patch('/actors/1000',
headers=get_auth_header('PRODUCER'))
self.assertEqual(res.status_code, 404)
def test_delete_actors_200(self):
last_id = get_last_element_id(Actor)
res = self.client().delete(
'/actors/' + last_id,
headers=get_auth_header('PRODUCER'))
data = json.loads(res.data)
actor = Actor.query.filter_by(id=last_id).one_or_none()
self.assertEqual(res.status_code, 200)
self.assertEqual(data['deleted'], last_id)
self.assertTrue(data['success'])
self.assertIsNone(actor)
def test_delete_actors_404(self):
res = self.client().delete('/actors/1000',
headers=get_auth_header('PRODUCER'))
data = json.loads(res.data)
self.assertEqual(res.status_code, 404)
self.assertFalse(data['success'])
def test_get_movies_200(self):
res = self.client().get('/movies',
headers=get_auth_header('PRODUCER'))
data = json.loads(res.data)
self.assertEqual(res.status_code, 200)
self.assertTrue(data['movies'])
self.assertEqual(data['total_movies'], 1)
self.assertTrue(data['success'])
def test_get_movies_404(self):
res = self.client().get('/movies?page=1000',
headers=get_auth_header('PRODUCER'))
self.assertEqual(res.status_code, 404)
def test_post_movies_200(self):
res = self.client().post('/movies', json=self.new_movie,
headers=get_auth_header('PRODUCER'))
data = json.loads(res.data)
last_id = get_last_element_id(Movie)
self.assertEqual(res.status_code, 200)
self.assertTrue(data['success'])
self.assertEqual(data['created'], int(last_id))
def test_post_movies_422(self):
res = self.client().post('/movies', json={},
headers=get_auth_header('PRODUCER'))
data = json.loads(res.data)
self.assertEqual(res.status_code, 422)
self.assertFalse(data['success'])
def test_patch_movies_200(self):
last_id = get_last_element_id(Movie)
res = self.client().patch(
'/movies/' + last_id,
json={
'release_date': '30 December 2018'},
headers=get_auth_header('PRODUCER'))
data = json.loads(res.data)
movie = Movie.query.get(last_id)
self.assertEqual(res.status_code, 200)
self.assertEqual(movie.release_date, '30 December 2018')
self.assertTrue(data['success'])
self.assertEqual(data['edited'], last_id)
def test_patch_movies_404(self):
res = self.client().patch('/movies/1000',
headers=get_auth_header('PRODUCER'))
self.assertEqual(res.status_code, 404)
def test_delete_movies_200(self):
last_id = get_last_element_id(Movie)
res = self.client().delete(
'/movies/' + last_id,
headers=get_auth_header('PRODUCER'))
data = json.loads(res.data)
movie = Movie.query.filter_by(id=last_id).one_or_none()
self.assertEqual(res.status_code, 200)
self.assertEqual(data['deleted'], last_id)
self.assertTrue(data['success'])
self.assertIsNone(movie)
def test_delete_movies_404(self):
res = self.client().delete('/movies/1000',
headers=get_auth_header('PRODUCER'))
data = json.loads(res.data)
self.assertEqual(res.status_code, 404)
self.assertFalse(data['success'])
def test_missing_auth_header_401(self):
res = self.client().get('/actors')
data = json.loads(res.data)
self.assertEqual(res.status_code, 401)
self.assertEqual(data['error'], 'authorization_header_missing')
def test_wrong_bearer_token_401(self):
res = self.client().get(
'/actors',
headers={
'Authorization': 'Bearer somewrongtoken'})
data = json.loads(res.data)
self.assertEqual(res.status_code, 401)
self.assertEqual(data['message'], 'unauthorized')
def test_assistant_get_movies_200(self):
res = self.client().get('/movies',
headers=get_auth_header('ASSISTANT'))
data = json.loads(res.data)
self.assertEqual(res.status_code, 200)
self.assertTrue(data['movies'])
self.assertTrue(data['success'])
def test_assistant_delete_movies_403(self):
res = self.client().delete('/movies/1000',
headers=get_auth_header('ASSISTANT'))
data = json.loads(res.data)
self.assertEqual(res.status_code, 403)
self.assertEqual(data['message'], 'Permission not found.')
def test_director_patch_movies_200(self):
last_id = get_last_element_id(Movie)
res = self.client().patch(
'/movies/' + last_id,
json={
'release_date': '30 December 2050'},
headers=get_auth_header('DIRECTOR'))
data = json.loads(res.data)
movie = Movie.query.get(last_id)
self.assertEqual(res.status_code, 200)
self.assertEqual(movie.release_date, '30 December 2050')
self.assertTrue(data['success'])
if __name__ == "__main__":
unittest.main()
|
anbclausen/hacktoberfest
|
WebsiteBlocker.py
|
import time
from datetime import datetime as dt
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
hosts_temp = "hosts"
redirect = "127.0.0.1"
web_sites_list = ["www.google.com", "google.com"] #here add any website for block
while True:
if dt(dt.now().year, dt.now().month, dt.now().day, 9) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day,22):
print("Working hours")
with open(hosts_path,"r+") as file:
content = file.read()
for website in web_sites_list:
if website in content:
pass
else:
file.write(redirect+" "+website+"\n")
else:
print("Free time")
with open(hosts_path,"r+") as file:
content = file.readlines()
file.seek(0)
for line in content:
if not any(website in line for website in web_sites_list):
file.write(line)
file.truncate()
time.sleep(10)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.