I decided to plan it using a flowchart, as I couldn't get my head around the programming easily without visualising it.
Here's the first draft and I'm pleased how it turned out:
This image was made at lucidchart.com - so easy to use!
Sporadic record of my adventures either teaching Computer Science, playing with my Raspberry Pi, or using computers generally.
#program to analyse electricity use over time by hour.
#open a file
#for each hour:
#read it line by line
#bucket into hour
#get total
#get average for each hour
#enhancements to follow: daily charts, date range charts, movie!
import csv
import os
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
startDay = 20
startMonth = 12
while True:
elecByHour=[]
dailyTotal=0
dailyReadings=0
for i in range (0,24): #for each hour
with open ('feeds.csv', 'rb') as csvfile:
rawelecdata = csv.DictReader(csvfile)
j=0
hourelectot=0
for row in rawelecdata:
if int(row['created_at'][11:13])==i and int(row['created_at'][8:10])==startDay and int(row['created_at'][5:7])==startMonth:
hourelectot += float(row['field1'])
j +=1
print(i,hourelectot/j,j) #useful to for debugging
elecByHour.append(hourelectot/j) #add average for the current hour to list
#calculate average for day:
dailyTotal = dailyTotal + hourelectot
dailyReadings = dailyReadings + j
dailyAverage = dailyTotal/dailyReadings
#plot the graph:
y = (elecByHour)
N = len(y)
x = range(N)
width = 1/1.5
plt.xlabel ('Time of Day / hr')
plt.ylabel ('kW')
plt.ylim((0,6))
plt.title('Consumption for '+ str(startDay) + '/' + str(startMonth) + ' Average = ' + str(dailyAverage)+'kW')
plt.bar(x, y, width, color="blue")
plt.savefig('elecByHour' + str(startMonth) + str(startDay) + '.png')
plt.close()
#os.system('xviewer elecByHour.png &')
startDay += 1
nested loop of expanding rising circles. Feels like an amphitheatre inside. |
Simple cylinder - circles on top of circles |
This one was weird - a cylinder with different block types in each layer. Unfortunately 2 of them were lava and water. |
One massive circle. |
from mcpi.minecraft import Minecraft
import math
mc = Minecraft.create()
#get players position
x,y,z=mc.player.getPos()
#move out of the way, there's something coming
mc.player.setPos (x,y+50,z)
r=15 #radius factor
for q in range (1,4): #nested loop for when you want multiple circles
for i in range(0,r*6): #sets how many blocks comprise the shape
j = float(i)/(r*3) #gives max j of 2 (to give 2*pi radians for trig))
blockXPos = r*math.cos(j*math.pi) #sets x coordinate of block
blockZPos = r*math.sin(j*math.pi) #sets z coordinate of block
mc.setBlock(blockXPos+x,y+q,blockZPos+z,1) #places a block in the circle
Its something called a quadric surface: |
find . -name "*.jpg" -size -150k -delete
#!/usr/bin/python
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
import httplib, urllib
import Adafruit_DHT
from time import sleep
# Parse command line parameters.
sensor_args = { '11': Adafruit_DHT.DHT11,
'22': Adafruit_DHT.DHT22,
'2302': Adafruit_DHT.AM2302 }
if len(sys.argv) == 3 and sys.argv[1] in sensor_args:
sensor = sensor_args[sys.argv[1]]
pin = sys.argv[2]
else:
print 'usage: sudo ./Adafruit_DHT.py [11|22|2302] GPIOpin#'
print 'example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO #4'
sys.exit(1)
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
# Un-comment the line below to convert the temperature to Fahrenheit.
# temperature = temperature * 9/5.0 + 32
# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
#Pushing data to Thingspeak
# python
if humidity is not None and temperature is not None:
print 'Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity)
else:
print 'Failed to get reading. Try again!'
sys.exit(1)
params = urllib.urlencode({'field1': temperature, 'field2': humidity,'key':'92P5L3PGPTT8ZE8N'})
headers = {"Content-type": "application/x-www-form-urlencoded","Accept":"text/plain"}
conn = httplib.HTTPConnection("api.thingspeak.com:80")
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
conn.close()
if humidity is not None and temperature is not None:
print 'Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity)
else:
print 'Failed to get reading. Try again!'
sys.exit(1)
sleep(60)
[{"id":"d82e83d.f27d18","type":"inject","z":"2fc3a5ef.d03c5a","name":"LED on","topic":"","payload":"1","payloadType":"string","repeat":"","crontab":"","once":false,"x":295,"y":112,"wires":[["24897f1c.db768","1b8bd14c.e4742f"]]},{"id":"795f97e3.86a068","type":"inject","z":"2fc3a5ef.d03c5a","name":"LED off","topic":"","payload":"0","payloadType":"string","repeat":"","crontab":"","once":false,"x":297,"y":187,"wires":[["24897f1c.db768","1b8bd14c.e4742f"]]},{"id":"24897f1c.db768","type":"rpi-gpio out","z":"2fc3a5ef.d03c5a","name":"Yellow LED","pin":"11","set":true,"level":"0","out":"out","x":497,"y":146,"wires":[]},{"id":"4a42382a.b5bdc8","type":"debug","z":"2fc3a5ef.d03c5a","name":"LED status","active":true,"console":"false","complete":"payload","x":622,"y":286,"wires":[]},{"id":"1b8bd14c.e4742f","type":"change","z":"2fc3a5ef.d03c5a","name":"Create Human Readable Output","rules":[{"t":"change","p":"payload","from":"0","to":"LED is OFF","re":false},{"t":"change","p":"payload","from":"1","to":"LED is ON","re":false}],"action":"","property":"","from":"","to":"","reg":false,"x":356,"y":287,"wires":[["4a42382a.b5bdc8"]]}]
(datetime.datetime(2016, 1, 14, 21, 34, 13, 517280), u'10.5')
(datetime.datetime(2016, 1, 15, 4, 9, 13, 518325), u'1.9')
Tide is currently: falling
Tidal Range = -8.6
Current Tide : 9.55460304533
('Next: ', (datetime.datetime(2016, 1, 3, 6, 18, 23, 116073), u'4.3'), ' is ', datetime.timedelta(0, 21180, 2472), ' away. /n Previous: ', (datetime.datetime(2016, 1, 2, 23, 49, 23, 115191), u'8.1'), ' was ', datetime.timedelta(0, 2159, 998410), ' ago.')
('Sum of both gaps is ', datetime.timedelta(0, 23340, 882))
('Tide is Currently: ', 'falling')
('tide difference = ', -3.8)
('lower tide value', 4.299999999999999)
('Normalised Time =', 2159, 23340, 0.29060405051843885)
0.958070971113
('Current tide : ', 7.940669690228617)
#version 1.0
#This program pulls tide data from the ports of Jersey Website
#Under a licence from the UKHO
#
#It then calculates the current tide using a simplified sinusoidal harmonic approximation
#By finding the two tide data points either side of now and working out the current tide height
import urllib2
from bs4 import BeautifulSoup
from time import sleep
import datetime as dt
import math
#open site and grab html
rawhtml = urllib2.urlopen("http://www.ports.je/Pages/tides.aspx").read(40000)
soup = BeautifulSoup(rawhtml, "html.parser")
#get the tide data (it's all in tags)
rawtidedata = soup.findAll('td')
#parse all data points (date, times, heights) to one big list
#format of the list is [day,tm,ht,tm,ht,tm,lt,tm,lt]
n=0
parsedtidedata=[]
for i in rawtidedata:
parsedtidedata.append(rawtidedata[n].get_text())
n += 1
#extract each class of data (day, time , height) to a separate list (there are 10 data items for each day)
tidetimes=[]
tideheights=[]
tideday=[]
lastdayofmonth=int(parsedtidedata[-10])
for n in range(0,lastdayofmonth*10,10):
tideday.append(parsedtidedata[n])
tidetimes.extend([parsedtidedata[n+1],parsedtidedata[n+3],parsedtidedata[n+5],parsedtidedata[n+7]])
tideheights.extend([parsedtidedata[n+2],parsedtidedata[n+4],parsedtidedata[n+6],parsedtidedata[n+8]])
#get time now:
currentTime = dt.datetime.now()
#create a list of all the tide times as datetime objects:
dtTideTimes=[]
tideDataList=[]
for j in range (0,lastdayofmonth*4):
#print tidetimes[j][0:2], tidetimes[j][3:6]
if tidetimes[j]=='**':
dtTideTimes.append('**')
else:
dtTideTimes.append(dt.datetime.now().replace(day=int(j/4+1), hour=int(tidetimes[j][0:2]), minute=int(tidetimes[j][3:5])))
#make a tuple for each data point and add it to a list
tupleHolder =(dtTideTimes[j], tideheights[j])
tideDataList.append(tupleHolder)
#print what we've got so far
# print tideDataList[j]
#find the two closest times in the list to now:
gap1 = abs(tideDataList[0][0] - currentTime)
gap2 = abs(tideDataList[0][0] - currentTime)
nearest1 = tideDataList[0]
#print gap1
for j in range (0,lastdayofmonth*4):
if (tideDataList[j][0] !="**"):
gapx = abs(tideDataList[j][0] - currentTime)
#check if the data point is the first or second nearest to now.
#Generates the datapoints either side of now
if (gapx <= gap1):
nearest1 = tideDataList[j]
gap1 = gapx
if (gap1 < gapx and gapx <= gap2):
nearest2 = tideDataList[j]
gap2 = gapx
#print (nearest1, gap1)
#print (nearest2, gap2)
#print (gap1+gap2)
#and now the maths begins
#print ('tide height 1 = ', nearest1[1])
#print ('tide height 2 = ', nearest2[1])
#need to get them in order of time: (this works)
if nearest1[0] > nearest2[0]:
nextDataPoint = nearest1
prevDataPoint = nearest2
gapToNext = gap1
gapToPrev = gap2
else:
nextDataPoint = nearest2
prevDataPoint = nearest1
gapToNext = gap2
gapToPrev = gap1
gapSum = gapToNext + gapToPrev
print('Next: ', nextDataPoint,' is ',gapToNext, ' away. /n Previous: ', prevDataPoint, ' was ', gapToPrev, ' ago.')
print('Sum of both gaps is ', gapSum) #this works
#is the tide rising or falling?
tideDifference = float(nextDataPoint[1])-float(prevDataPoint[1])
if (tideDifference<0 data-blogger-escaped-0="prev" data-blogger-escaped-:="" data-blogger-escaped-all="" data-blogger-escaped-code="" data-blogger-escaped-currently:="" data-blogger-escaped-currenttide="" data-blogger-escaped-data="" data-blogger-escaped-difference=", tideDifference) #this works
lowerTide = (float(nearest1[1]) + float(nearest2[1]) - abs(tideDifference))/2
print (" data-blogger-escaped-doesn="" data-blogger-escaped-else:="" data-blogger-escaped-falling="" data-blogger-escaped-for="" data-blogger-escaped-ide="" data-blogger-escaped-is="" data-blogger-escaped-lower="" data-blogger-escaped-lowertide="" data-blogger-escaped-math.cos="" data-blogger-escaped-math.pi="" data-blogger-escaped-normalisedtime="" data-blogger-escaped-ormalised="" data-blogger-escaped-pi="next" data-blogger-escaped-print="" data-blogger-escaped-scaled="" data-blogger-escaped-t="" data-blogger-escaped-this="" data-blogger-escaped-tide="" data-blogger-escaped-tidedifference="" data-blogger-escaped-tidestate="" data-blogger-escaped-time=", gapToPrev.seconds, gapSum.seconds, normalisedTime)
print (math.cos(normalisedTime))
if tideState == " data-blogger-escaped-to="" data-blogger-escaped-urrent="" data-blogger-escaped-value="" data-blogger-escaped-work="" data-blogger-escaped-works="">
#
import urllib2
from bs4 import BeautifulSoup
from time import sleep
import datetime as dt
#open site and grab html
rawhtml = urllib2.urlopen("http://www.ports.je/Pages/tides.aspx").read(40000)
soup = BeautifulSoup(rawhtml, "html.parser")
#get the tide data (it's all in tags)
rawtidedata = soup.findAll('td')
#parse all data points (date, times, heights) to one big list
#format of the list is [day,tm,ht,tm,ht,tm,lt,tm,lt]
n=0
parsedtidedata=[]
for i in rawtidedata:
parsedtidedata.append(rawtidedata[n].get_text())
n += 1
#extract each class of data (day, time , height) to a separate list (there are 10 data items for each day):
tidetimes=[]
tideheights=[]
tideday=[]
lastdayofmonth=int(parsedtidedata[-10])
for n in range(0,lastdayofmonth*10,10):
tideday.append(parsedtidedata[n])
tidetimes.extend([parsedtidedata[n+1],parsedtidedata[n+3],parsedtidedata[n+5],parsedtidedata[n+7]])
tideheights.extend([parsedtidedata[n+2],parsedtidedata[n+4],parsedtidedata[n+6],parsedtidedata[n+8]])
#get time now:
currentTime = dt.datetime.now()
#create a list of all the tide times as datetime objects:
dtTideTimes=[]
tideDataList=[]
for j in range (0,lastdayofmonth*4):
#print tidetimes[j][0:2], tidetimes[j][3:6]
if tidetimes[j]=='**':
dtTideTimes.append('**')
else:
dtTideTimes.append(dt.datetime.now().replace(day=int(j/4+1), hour=int(tidetimes[j][0:2]), minute=int(tidetimes[j][3:5])))
#create a tuple of time and height, and add each tuple to a list
tupleHolder =(dtTideTimes[j], tideheights[j])
tideDataList.append(tupleHolder)
#print what we've got so far
for j in range (0,lastdayofmonth*4):
print tideDataList[j]
#find the two closest data points to now in the list:
gap1 = abs(tideDataList[0][0] - currentTime)
nearest1 = tideDataList[0]
print gap1
for j in range (0,lastdayofmonth*4):
if (tideDataList[j][0] !="**"):
gap2 = abs(tideDataList[j][0] - currentTime)
print tideDataList[j][0], gap2, nearest1
if (gap2 < gap1):
nearest2 = nearest1
nearest1 = tideDataList[j]
gap1 = gap2
print (nearest1, nearest2)
#this nearly works!!! Gave the two nearest high tides, not nearest high and low.