repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex8_gauss_int.py
|
<reponame>josephlewis42/personal_codebase<filename>python/Genetic Programming/Examples/pyevolve_ex8_gauss_int.py
from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import Mutators
# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
score = 0.0
# iterate over the chromosome
for value in chromosome:
if value==0:
score += 0.1
return score
def run_main():
# Genome instance
genome = G1DList.G1DList(40)
# The gauss_mu and gauss_sigma is used to the Gaussian Mutator, but
# if you don't specify, the mutator will use the defaults
genome.setParams(rangemin=0, rangemax=10, gauss_mu=4, gauss_sigma=6)
genome.mutator.set(Mutators.G1DListMutatorIntegerGaussian)
# The evaluator function (objective function)
genome.evaluator.set(eval_func)
# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
#ga.selector.set(Selectors.GRouletteWheel)
ga.setGenerations(800)
# Do the evolution, with stats dump
# frequency of 10 generations
ga.evolve(freq_stats=150)
# Best individual
print ga.bestIndividual()
if __name__ == "__main__":
run_main()
|
josephlewis42/personal_codebase
|
python/gamebot/ini_reader.py
|
<gh_stars>1-10
#!/usr/bin/env python
'''Provides NumberList and FrequencyDistribution, classes for statistics.
NumberList holds a sequence of numbers, and defines several statistical
operations (mean, stdev, etc.) FrequencyDistribution holds a mapping from
items (not necessarily numbers) to counts, and defines operations such as
Shannon entropy and frequency normalization.
Copyright 2011 <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
import ConfigParser
import os
__author__ = "<NAME>"
__copyright__ = "Copyright 2011, <NAME>"
__license__ = "GPL"
__version__ = ""
CONFIG_FILE = 'config_file.ini'
config = ConfigParser.ConfigParser()
#Creates and parses an ini file for the
if os.path.exists(CONFIG_FILE):
config.read(CONFIG_FILE)
else:
config.add_section('SMTP')
config.add_section('POP')
config.set('SMTP', 'username', '<EMAIL>')
config.set('SMTP', 'password', '<PASSWORD>')
config.set('SMTP', 'hostname', 'smtp.gmail.com')
config.set('SMTP', 'port', '587')
config.set('POP', 'username', '<EMAIL>')
config.set('POP', 'password', '<PASSWORD>')
config.set('POP', 'hostname', 'pop.<EMAIL>')
config.set('POP', 'port', '995')
config.set('POP', 'ssl', 'True')
# Writing our configuration file to 'example.cfg'
with open(CONFIG_FILE, 'wb') as configfile:
config.write(configfile)
def setup_fetcher(email_fetcher):
'''sets up an email fetcher from the given information in the ini.
'''
email_fetcher.configure_pop(
config.get('POP', 'username'),
config.get('POP', 'password'),
config.get('POP', 'hostname'),
config.getint('POP', 'port'),
config.getboolean('POP', 'ssl')
)
email_fetcher.configure_smtp(
config.get('SMTP', 'username'),
config.get('SMTP', 'password'),
config.get('SMTP', 'hostname'),
config.getint('SMTP', 'port'),
)
|
josephlewis42/personal_codebase
|
python/timed_message.py
|
<reponame>josephlewis42/personal_codebase
#!/usr/bin/env python
import datetime
import re
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
gmail_user = "<EMAIL>"
gmail_pwd = "password"
def mail(to, subject, body):
msg = MIMEMultipart('alternative')
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
if '<html>' in body:
msg.attach(MIMEText(re.sub(r'<.*?>', '', body), 'plain'))
msg.attach(MIMEText(body, 'html'))
else:
msg.attach(MIMEText(body, 'plain'))
m = smtplib.SMTP("smtp.gmail.com", 587)
m.ehlo()
m.starttls()
m.ehlo()
m.login(gmail_user, gmail_pwd)
m.sendmail(gmail_user, to, msg.as_string())
m.quit()
if __name__ == "__main__":
while datetime.datetime.today() < datetime.datetime(2011, 5, 24):
time.sleep(10)
mail("<EMAIL>", "subject", "<html><b>body</b> nonbold</html>")
|
josephlewis42/personal_codebase
|
python/randall/alife_randall_checkout/ai_webserver/actor_map.py
|
# actor_map.py -- Displays the internal map of an actor.
#
# Copyright 2011 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
self.send_200()
if not SESSION or 'login' not in SESSION.keys() or not SESSION['login']:
self.wfile.write("You are not logged in...<script type='text/javascript'>window.location = 'login.py'</script>")
else:
try:
w = SESSION['world']
a = SESSION['actor']
page = w[a].internal_map.gen_HTML()
self.wfile.write(page)
except KeyError, e:
self.wfile.write("Error: Couldn't find the key specified: %s" %(e))
except Exception, e:
self.wfile.write("Error: %s" %(e))
|
josephlewis42/personal_codebase
|
python/reprap-franklin/display.py
|
#!/usr/bin/env python
'''Provides a main GUI for the RepRap Franklin.
Copyright 2011 <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
from Tkinter import *
import tkMessageBox
import tkFileDialog
import time
import firmware
import inputs
import reprap
__author__ = "<NAME>"
__copyright__ = "Copyright 2011 <NAME> <<EMAIL>>, GPL2 license."
__license__ = "GPL"
__version__ = "20110311"
#Filetypes for tk open/save dialogs.
GCODE_FILETYPE = ("GCode Files", ".gcode")
PS_FILETYPE = ("Post Script", ".ps")
ALL_FILETYPE = ("All Files", ".*")
class Display:
'''A GUI display for the program.'''
waittime = 0.1 #Time to sleep between drawing cycles.
def speed_closer(self, time):
'''Creates and returns a function for setting the wait_time to
a certain value.
Paramaters:
time - The time to create the function for setting waittime to.
Return:
A function that sets waittime to the given time.
'''
def settime():
self.waittime = time
self.notify("Setting delay to: %s, this may take a moment." % (time))
return settime
def timer(self):
'''Called by inputs to delay their inputs for a user determined
amount of time. Also pauses if the emulated RepRap is paused.
'''
time.sleep(self.waittime)
while self.rep.paused:
time.sleep(1)
def save(self):
'''Saves the print bed view as a post-script file.'''
loc = tkFileDialog.asksaveasfilename(defaultextension=".ps", filetypes=[PS_FILETYPE])
if not loc:
self.notify("Save image canceled.")
return
try:
f = open(loc, 'w')
f.write( self.canvas.postscript() )
self.notify("Saved image to %s" % (loc))
except IOError, e:
self.notify("Couldn't save image: %s." % (e))
def file_input(self):
loc = tkFileDialog.askopenfilename(filetypes=[GCODE_FILETYPE, ALL_FILETYPE])
if not loc:
return
f = inputs.file_input.FileInput(self.rep, loc, self.timer)
f.start()
self.notify("Using file %s as input." % (loc))
def unix_input(self):
'''Setus up the input as a unix socket.'''
loc = tkFileDialog.askopenfilename()
if not loc:
return
f = inputs.unix_socket.UNIXSocketInput(self.rep, loc, self.timer)
f.start()
self.notify("Using file %s as input." % (loc))
def firmware_changer(self, fw):
'''Takes in a class and returns a function to change to the
firmware represented by the given class.
'''
def change_firmware():
self.rep.current_firmware = fw(self.rep)
self.notify("Changed firmware to %s" % fw.title)
return change_firmware
def toggle_paused(self):
'''Toggles the paused state of the RepRap.'''
self.rep.paused = not self.rep.paused
if self.rep.paused:
self.notify("Paused")
else:
self.notify("Un-Paused")
def setup_reprap(self):
'''Draw the text and dividing lines on the bed.'''
self.rep = reprap.RepRap()
bed = self.rep.bed #Shorten future commands by nine chars.
#Place to draw the output.
self.canvas = Canvas(self.root, width=bed.bed_width, height=bed.bed_height, bg="#6BB56B")
self.canvas.pack(side=TOP)
bed.canvas = self.canvas
bed.reset() #Draw dividing lines for displays.
def clear_canvas(self):
#print dir(self.rep.bed.xy_canvas)
self.rep.bed.canvas.delete(ALL)
self.rep.bed.reset()
def notify(self, text):
'''Notifies the user of an event.'''
t = time.strftime("%H:%M:%S")
text = "%s - %s\n" % (t, text)
self.notify_panel.insert(END, text)
self.notify_panel.see(END)
def __init__(self):
root = Tk(className=" RepRap Franklin")
self.root = root
#Setup Menus
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="Display", menu=filemenu)
filemenu.add_command(label="Save As...", command=self.save)
filemenu.add_command(label="Clear", command=self.clear_canvas)
filemenu.add_command(label="Quit", command=exit)
repmenu = Menu(menu)
menu.add_cascade(label="RepRap", menu=repmenu)
#Add all the possible firmwares.
fw_menu = Menu(repmenu)
repmenu.add_cascade(label="Change Firmware", menu=fw_menu)
for i in firmware.full.Firmware.__subclasses__():
fw_menu.add_command(label=i.title, command=self.firmware_changer(i))
repmenu.add_separator()
repmenu.add_command(label="Pause", command=self.toggle_paused)
#Input menu (select gcode source)
inputmenu = Menu(menu)
menu.add_cascade(label="Input Source", menu=inputmenu)
inputmenu.add_command(label="File...", command=self.file_input)
inputmenu.add_command(label="UNIX Socket...", command=self.unix_input)
#Speed menu
speed_menu = Menu(menu)
menu.add_cascade(label="Delay", menu=speed_menu)
for i in [0, 0.005, 0.01, 0.1, 0.2, 0.5, 1, 2, 5]:
speed_menu.add_command(label="%s seconds" % i, command=self.speed_closer(i))
#Notification panel for the user.
self.notify_panel = Text(root, height=5)
self.notify_panel.pack(side=BOTTOM)
self.setup_reprap()
self.notify(__copyright__)
mainloop()
if __name__ == "__main__":
d = Display()
|
josephlewis42/personal_codebase
|
python/reprap-franklin/reprap.py
|
#!/usr/bin/env python
'''Provides a RepRap Object for the RepRap Franklin.
This is used as the abstract RepRap and has a set of toolheads, a
firmware, a printing bed and other small components, like fans.
Copyright 2011 <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
import firmware
import toolheads
class _PrintBed:
''' A printing bed representation.
TODO Add ability to turn on/off lines from certain toolheads.
To start printing to a canvas just set the canvas variable to a
Tk.Canvas instance.
'''
lines = [] #All of the lines on the canvas.
layer = [] #The current z layer's lines.
layer_z = 0.0 #The z value of the current layer.
canvas = None #The canvas for the printer.
#Physical properties
temperature = 22.22 #Room temp.
pressure = 0 #Holding pressure in bar.
#Dimensions (mm)
dim_x = 250
dim_y = 250
dim_z = 125
scale = 1.5 #This many px = 1 mm, can't be below 1 for sanity.
bed_width = None
bed_height = None
def __init__(self):
#Setup scaling.
self.bed_height = (self.dim_y + self.dim_z) * self.scale
self.bed_width = (self.dim_x + self.dim_z) * self.scale
self.max_y = self.dim_y * self.scale #Max y value
self.max_x = self.dim_x * self.scale #Max x value
def reset(self):
#Clears the bed and re-draws the border lines.
if self.canvas != None:
y = self.dim_y * self.scale #Max y value
x = self.dim_x * self.scale #Max x value
#Horizontal Line
self.canvas.create_line((0, y, self.bed_width, y), fill="black")
#Vertical Line
self.canvas.create_line((x, 0, x, self.bed_height), fill="black")
#Denoting the areas.
self.canvas.create_text(10, 10, text="XY")
self.canvas.create_text(x+10, 10, text="YZ")
self.canvas.create_text(10, y+10, text="XZ")
self.canvas.create_text(x+45,y+10, text="Current Layer")
def add_line(self, coord1, coord2, toolhead):
#Scale the coordinates properly.
coord1.scale(self.scale)
coord2.scale(self.scale)
self.lines.append((coord1, coord2, toolhead))
x1 = coord1.x
y1 = coord1.y
z1 = coord1.z
x2 = coord2.x
y2 = coord2.y
z2 = coord2.z
#Immediately draw to the canvas.
if self.canvas != None:
#XY
self.canvas.create_line((x1, y1, x2, y2), fill=toolhead.color, width=toolhead.width)
#YZ
self.canvas.create_line((self.bed_width-z1, y1, self.bed_width-z2, y2), fill=toolhead.color, width=toolhead.width)
#XZ
self.canvas.create_line((x1, self.bed_height-z1, x2, self.bed_height-z2), fill=toolhead.color, width=toolhead.width)
#Draw lines for the current layer in the corner.
if z2 != self.layer_z: #If the z layer has moved, erase the corner.
for line in self.layer:
self.canvas.delete(line)
self.layer_z = z2
self.layer = []
x1 += self.max_x - (self.max_x / 4.0) #Cut 1/4 off all edges.
x2 += self.max_x - (self.max_x / 4.0)
y1 += self.max_y - (self.max_y / 4.0)
y2 += self.max_y - (self.max_y / 4.0)
j = self.canvas.create_line((x1,y1,x2,y2), fill=toolhead.color, width=toolhead.width)
self.layer.append(j)
class Chamber:
'''A chamber representation for the RepRap'''
temperature = 22.22 #Room temp.
class RepRap:
'''A reprap model, has a print bed, firmware and toolheads.'''
#Physical properties.
fan = False #On = True
stop = False
idle_hold_on = True
paused = False
def __init__(self):
'''Sets up the RepRap and some nice variables:
current_firmware: An initalized instance of a pice of firmware.
bed: The print bed.
chamber: The chamber for the device.
possible_toolheads: The toolheads in each slot of the machine,
corresponds to the T number in GCode.
current_toolhead: A pointer to the currently used toolhead,
automatically 0.
'''
self.current_firmware = firmware.full.Firmware(self)
self.bed = _PrintBed()
self.chamber = Chamber()
self.possible_toolheads = [toolheads.basic.BasicExtruder(),]
self.current_toolhead = self.possible_toolheads[0]
def change_toolhead(self, number):
'''Changes to toolhead N if possible.'''
try:
self.current_toolhead = self.possible_toolheads[number]
except Exception, e:
print ("Couldn't change toolhead: %s" % e)
def move_toolhead(self, c1, c2):
'''Moves the toolhead from coordinates 1 to 2, drawing
along the way if applicable.
'''
if self.current_toolhead.extrude_rate > 0:
self.bed.add_line(c1, c2, self.current_toolhead)
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex18_gp.py
|
from pyevolve import Util
from pyevolve import GTree
from pyevolve import GSimpleGA
from pyevolve import Consts
import math
rmse_accum = Util.ErrorAccumulator()
def gp_add(a, b): return a+b
def gp_sub(a, b): return a-b
def gp_mul(a, b): return a*b
def gp_sqrt(a): return math.sqrt(abs(a))
def eval_func(chromosome):
global rmse_accum
rmse_accum.reset()
code_comp = chromosome.getCompiledCode()
for a in xrange(0, 5):
for b in xrange(0, 5):
evaluated = eval(code_comp)
target = math.sqrt((a*a)+(b*b))
rmse_accum += (target, evaluated)
return rmse_accum.getRMSE()
def main_run():
genome = GTree.GTreeGP()
genome.setParams(max_depth=4, method="ramped")
genome.evaluator += eval_func
ga = GSimpleGA.GSimpleGA(genome)
ga.setParams(gp_terminals = ['a', 'b'],
gp_function_prefix = "gp")
ga.setMinimax(Consts.minimaxType["minimize"])
ga.setGenerations(50)
ga.setCrossoverRate(1.0)
ga.setMutationRate(0.25)
ga.setPopulationSize(800)
ga(freq_stats=10)
best = ga.bestIndividual()
print best
if __name__ == "__main__":
main_run()
|
josephlewis42/personal_codebase
|
python/OpenCalc/Lib/Code/Functions/Log_Exp.py
|
'''
Holds Logarithmic and Exponential Functions
@Author = <NAME> <<EMAIL>>
@Date = 2010-03-03 (Originally)
@License = GPL
==Changelog==
2010-03-03 - Original of this document, so far it is a wrapper for the python log and exponential math functions, soon I hope it to be more
'''
#Import Statements
import math
#Define Constants
E = math.e
#Define Functions
def exp(base, exp):
'''
Raise the base to the exponent
'''
return base**exp
def log(num, base=10):
'''
Return the log of x to given base if no base is provided, use 10
'''
return math.log(num,base)
def natlog(num):
'''
Return the natural log of a number
'''
return math.log(num)
def ln(num):
'''
Return the natrual log of a number (TI-83)
'''
return math.log(num)
def sqrt(num):
'''
Return the square root of a number
'''
return math.sqrt(num)
def root(num, root):
'''
Return a root of the number:
Original Code
'''
x = num**(1.0/root)
return x
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex3_schaffer.py
|
from pyevolve import G1DList, GSimpleGA, Selectors
from pyevolve import Initializators, Mutators, Consts
import math
# This is the Schaffer F6 Function
# This function has been conceived by Schaffer, it's a
# multimodal function and it's hard for GAs due to the
# large number of local minima, the global minimum is
# at x=0,y=0 and there are many local minima around it
def schafferF6(genome):
t1 = math.sin(math.sqrt(genome[0]**2 + genome[1]**2));
t2 = 1.0 + 0.001*(genome[0]**2 + genome[1]**2);
score = 0.5 + (t1*t1 - 0.5)/(t2*t2)
return score
def run_main():
# Genome instance
genome = G1DList.G1DList(2)
genome.setParams(rangemin=-100.0, rangemax=100.0, bestrawscore=0.0000, rounddecimal=4)
genome.initializator.set(Initializators.G1DListInitializatorReal)
genome.mutator.set(Mutators.G1DListMutatorRealGaussian)
# The evaluator function (objective function)
genome.evaluator.set(schafferF6)
# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.selector.set(Selectors.GRouletteWheel)
ga.setMinimax(Consts.minimaxType["minimize"])
ga.setGenerations(8000)
ga.setMutationRate(0.05)
ga.setPopulationSize(100)
ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria)
# Do the evolution, with stats dump
# frequency of 10 generations
ga.evolve(freq_stats=250)
# Best individual
best = ga.bestIndividual()
print best
print "Best individual score: %.2f" % best.getRawScore()
if __name__ == "__main__":
run_main()
|
josephlewis42/personal_codebase
|
Euler/pymath.py
|
<reponame>josephlewis42/personal_codebase
'''
A small, general-purpose math library for Python
- <NAME>
'''
import math
import random
def factor(n):
''' Finds the factors of the given number.'''
result = set()
for i in range(1, int(n ** 0.5) + 1):
div, mod = divmod(n, i)
if mod == 0:
result |= {i, div}
return result
def prime(n):
''' Finds if n is a prime number. Optionally n can be a set, will
return a set containing all primes in that list.'''
try:
return n == 1 or len(factor(n)) == 2
except Exception:
return [x for x in n if prime(x)]
def prime_factors(n):
'''Returns the prime factors of the given number.'''
return prime(factor(n))
def has_multiple(i, multiples):
'''True if i is divisible by any number in the array multiples an
even number of times.
'''
for p in multiples:
if i == p or i % p:
return True
return False
def gen_fib(largest, last = 2, prev = 1, li = [1,2]):
''' Generates the fibonacci numbers up to the largest given.'''
if last + prev > largest:
return li
li.append(last + prev)
return gen_fib(largest, last+prev, last, li)
def palindrome(number):
'''Returns true if the number is a palindrome'''
backwards = "".join(reversed(str(number)))
return backwards == str(number)
def gcd(a, b):
'''Returns the greatest common divisor of the two numbers.
Using the Euclidian method.'''
mod = 1
while mod != 0:
div,mod = divmod(a,b)
a = b
b = mod
return a
def lcm(a, b):
'''Returns the leaste common multiple of the two numbers.'''
return abs(a * b) / gcd(a, b)
def lcm_array(nums):
''' Returns the least common multiple of a list of numbers.'''
return reduce(lambda x, y: lcm(x,y), nums)
def sum_of_squares(nums):
return sum([x ** 2 for x in nums])
def square_of_sum(nums):
return sum(nums) ** 2
def n_primes(n):
'''Returns the first n primes.'''
i = 0
primes = set()
while len(primes) != n:
i += 1
if prime(i):
primes.add(i)
return primes
def primes_below(n):
'''Finds a list of all primes below the given number. Using
Sieve's Algorithm.'''
if n < 2:
return []
if n == 2:
return [2]
n = n + 1 # find the primes below n
marked = set()
primes = []
for x in range(2, n):
if not x in marked:
primes.append(x)
for y in range(x, n, x):
marked.add(y)
return primes
def quadratic(a, b, c, x=0):
'''Returns the values for c such that the quadratic equation is
solved. Only returns real solutions. Returns None for
complex numbers.'''
c = c - x
sltns = b**2 - 4 * a * c
if sltns > 0:
sltn1 = (-b + math.sqrt(sltns))/(2.0 * a)
sltn2 = (-b - math.sqrt(sltns))/(2.0 * a)
return (sltn1, sltn2)
if sltns == 0:
sltn1 = (-b + math.sqrt(sltns))/(2.0 * a)
return (sltn1, sltn1)
return None
def pythagorean_triple(perim):
'''Returns a pythagorean triple such that the sum of a,b,c is
the given number. The triples won't be primitive.'''
#perim = 2n + 1 + 2n(n+1) + 2n(n+1) + 1
#perim = 4n**2 + 6n + 2
# n = 15
q = quadratic(4, 6, 2, perim)
n = q[0] if q[0] > q[1] else q[1]
a = 2 * n + 1
b = 2 * n * (n + 1)
c = 2 * n * (n + 1) + 1
return (a,b,c)
def are_coprime(a,b):
'''Determines if the two numbers are coprime.'''
return gcd(a,b) == 1
def is_pythagorean(a,b,c):
return (a**2 + b**2) == c**2
def primitive_pythagorean_triples(perim):
'''Returns a pythagorean triple such that the sum of a,b,c is the given
number. Returns none if it does not exist.
'''
results = []
for c in range(2, perim):
for b in range(1, perim - c):
a = perim - b - c
if a > b:
continue
if is_pythagorean(a,b,c):
results.append([a,b,c])
return results
def split_2d_array_to_1d(array, up=False, down=False, left=False, right=True, diagonal_up=False, diagonal_down=False):
'''
Splits a 2d array in to a bunch of 1d arrays, the array should be in the format [row][col]
'''
result = []
if up:
for col in range(len(array)):
tmp = []
row = 0
try:
tmp.append(array[row][col])
row += 1
except IndexError:
result.append(tmp)
if down:
for col in range(len(array)):
tmp = []
row = 0
try:
tmp.append(array[row][col])
row += 1
except IndexError:
result.append([x for x in reversed(tmp)])
if left:
for a in array:
result.append([x for x in reversed(a)])
if right:
for a in array:
result.append(a)
if diagonal_up:
maxrow = len(array)
maxcol = len(array[1])
# try going down
for row in range(len(array)):
tmp = []
col = 0
try:
while row >= 0 and col >= 0 and row < maxrow and col < maxcol:
tmp.append(array[row][col])
row -= 1
col += 1
except IndexError:
pass
result.append(tmp)
# then across
for col in range(1,len(array[len(array) - 1])):
tmp = []
row = len(array) - 1
try:
while row >= 0 and col >= 0 and row < maxrow and col < maxcol:
tmp.append(array[row][col])
row -= 1
col += 1
except IndexError:
pass
result.append(tmp)
if diagonal_down:
maxrow = len(array)
maxcol = len(array[1])
# try going down
for row in range(maxrow):
tmp = []
col = 0
try:
while row >= 0 and col >= 0 and row < maxrow and col < maxcol:
tmp.append(array[row][col])
row += 1
col += 1
except IndexError:
pass
result.append(tmp)
# then across
for col in range(1,maxcol):
tmp = []
row = 0
try:
while row >= 0 and col >= 0 and row < maxrow and col < maxcol:
tmp.append(array[row][col])
row += 1
col += 1
except IndexError:
pass
result.append(tmp)
return result
def greatest_product(numbers, length_of_chain):
'''Finds the greatest product that can be found in the list of
numbers.
'''
largest = None
for i in range(len(numbers) - length_of_chain + 1):
num = numbers[i]
for k in range(1,length_of_chain):
num *= numbers[i + k]
if num > largest or i == 0:
largest = num
return largest
def triangluar_number(n):
'''Generates the nth triangular number.'''
return (n * (n + 1)) / 2
def print_prob(how_often, *args):
if random.random() < (1.0 / how_often):
print args
def factorial(n):
'''Calculates n factorial.'''
total = 1
for i in range(n, 1, -1):
total *= i
return total
def choose(n, k):
'''Calculates n choose k'''
return factorial(n) / (factorial(k) * factorial(n - k))
def to_word(number, suffix=''):
'''changes a word to an english number.'''
number = str(number)
pre = number[:-3]
if len(pre != 0):
prefix = to_word
whole_tens = ['ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
ones = ['','one','two','three','four','five','six','seven','eight','nine']
tens_one = ['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
suffixes = ['','thousand','million','billion','trillion']
|
josephlewis42/personal_codebase
|
python/OpenCalc/Lib/Code/Frontend.py
|
#!/usr/bin/python
import wx.html as html
import Parser
import wx
import Graph
class events():
'''
This class holds all of the events for the main gui and their helper methods.
'''
def submit_function(self, event):
index = self.functions_list_box.GetSelection()
fx = Graph.function(self.function_text_ctrl.GetValue(),
self.function_name_text_ctrl.GetValue())
fx.will_graph = self.function_show_checkbox.GetValue()
fx.line_color = self.function_color_combo_box.GetValue()
fx.line_style = self.function_style_combo_box.GetValue()
#Set the function
Graph.function_list[index] = fx
#Update the box
self.setup_functions_list()
event.Skip()
def update_function_editor(self, event):
#Get selected f(x) location
index = event.GetSelection()
#Get the correct function from the tupple
fx = Graph.function_list[index]
#Set all values
self.function_text_ctrl.SetValue(fx.function_value)
self.function_color_combo_box.SetValue(fx.line_color)
self.function_style_combo_box.SetValue(fx.line_style)
self.function_name_text_ctrl.SetValue(fx.function_name)
self.function_show_checkbox.SetValue(fx.will_graph)
event.Skip()
def LoadPage(self, event): # wxGlade: CalcWidget.<event_handler>
print "Event handler `LoadPage' not implemented"
event.Skip()
def input_key_press(self, event):
'''
Checks for the enter key, if it has been pressed then the program will
submit the value that is in the pad input box
'''
keycode = event.GetKeyCode()
#If user pressed enter or return spawn the submit input event
if keycode == wx.WXK_RETURN or keycode == wx.WXK_NUMPAD_ENTER:
self.Submit_Input(event)
event.Skip()
def show_tab(self, event): # wxGlade: CalcWidget.<event_handler>
print "Event handler `show_tab' not implemented!"
event.Skip()
def clear_pad(self, event): # wxGlade: CalcWidget.<event_handler>
self.output_text_ctrl.Clear()
event.Skip()
def save_graph_as(self, event): # wxGlade: CalcWidget.<event_handler>
print "Event handler `save_graph_as' not implemented!"
event.Skip()
def Submit_Input(self, event):
'''
Parse the input for the pads
'''
if self.input_text_ctrl.GetValue() != "":
#Parse the data
self.output_text_ctrl.AppendText("==" + self.input_text_ctrl.GetValue() + "\n")
self.output_text_ctrl.AppendText(str(Parser.parse(self.input_text_ctrl.GetValue()))+"\n")
#If an error happens above the text will NOT be cleared, allowing the
#user to correct their mistake easily.
self.input_text_ctrl.Clear()
event.Skip()
def LoadPage(self, event):
'''
Load the main html page.
'''
self.html_window.LoadPage("./Lib/Function Lookup/index.html")
def switch_to_pad(self, event):
'''
Switch to the pad tab
'''
self.notebook_manager.SetSelection(0)
event.Skip()
def write(self,text):
#Used to print stdout to output control
self.output_text_ctrl.AppendText(text+"\n")
def switch_to_functions(self, event):
'''
Switch to the functions tab
'''
self.notebook_manager.SetSelection(1)
event.Skip()
def switch_to_graphs(self, event):
'''
Switch to the graphs tab
'''
self.notebook_manager.SetSelection(2)
event.Skip()
def toggle_fullscreen(self, event):
'''
Toggles the window being fullscreen.
TODO : Test this function
'''
self.main_window.ShowFullScreen(True, style=wx.FULLSCREEN_ALL)
def setup_functions_list(self):
'''
Add all of the functions as well as their text to the listbox
'''
#Clear Box
self.functions_list_box.Clear()
#Get all function titles
titles = Graph.get_function_titles()
#Add title to list
for title in titles:
self.functions_list_box.Append(title)
def graph(self):
'''
Graphs the current functions and plots the user has entered.
'''
#Get x range for y to be calculated off of
x = Graph.get_x_range(Graph.xmin,Graph.xmax,Graph.x_increment)
#Get all functions to plot
functions_to_plot = Graph.get_on_functions()
for fx in functions_to_plot:
fx.update_function(x)
#Now set up and plot the functions
fig = self.graph_2d_plot_panel.get_figure()
axes = fig.gca()
# clear the axes and replot everything
axes.cla()
for fx in functions_to_plot:
axes.plot(fx.x_values, fx.y_values,fx.get_color()+fx.get_line_style(), linewidth=1.0, label=fx.function_name)
#Set the limits for the graph TODO get this working
#axes.set_xlim((-100,100))
axes.set_ylim(-1,1)
def on_resize_window(self, event):
'''
Changes the position of the window divider (help frame, and tabs) when
the window is resized, being that the help window will take all the
space otherwise.
'''
frame_size = event.GetSize()
self.main_window.SetSize(frame_size)
width = frame_size.GetWidth()
self.main_window.SetSashPosition(width - 300, redraw=True)
event.Skip()
def notebook_page_changed(self, event): # wxGlade: CalcWidget.<event_handler>
'''
Called when the tabs change, if graphing tab, update graph
'''
if self.notebook_manager.GetSelection() == 2:
self.graph() #TODO try to speed this up
event.Skip()
def _do_bindings(self):
'''
Does all of the custom bindings left out by wxGlade when the project is
generated.
'''
#Bind the pad input control with the enter key
self.input_text_ctrl.Bind(wx.EVT_KEY_DOWN, self.input_key_press)
#Bind window resize with a recalculation of the divider placement
wx.EVT_SIZE(self, self.on_resize_window)
def setup(self):
'''
This function sets up the program in the proper way, and
inits all components.
'''
#Bind all of the extras
self._do_bindings()
#Load the main web page
self.LoadPage("")
#Disallow any of the panels from disappearing
self.main_window.SetMinimumPaneSize(1)
#Add functions to the listbox
self.setup_functions_list()
#self.graph()
|
josephlewis42/personal_codebase
|
python/randall/alife_randall_checkout/ai_webserver/actor_chooser.py
|
# actor_chooser.py
#
# Copyright 2011 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
self.send_200()
if not SESSION or 'login' not in SESSION.keys() or not SESSION['login']:
self.wfile.write("You are not logged in...<script type='text/javascript'>window.location = 'login.py'</script>")
else:
if 'actor' not in SESSION.keys():
try:
SESSION['actor'] = SESSION['world'].actors[0].name
except IndexError:
import warnings
warnings.warn("Can't find the world OR an actor in it.")
if POST_DICT and 'actor' in POST_DICT.keys():
#Change actor on successful post.
SESSION['actor'] = POST_DICT['actor']
#Handle AJAX refresh query.
if 'load' in QUERY_DICT.keys():
page = '''
<script type="text/javascript" src="assets/jquery.js"></script>
<h3>Actor Panel:</h3> <div id="progresscontainer">
<h4>Choose Actor:</h4>
<form id="actorselect">
<select name="actor" onchange="$.post('actor_chooser.py', $('#actorselect').serialize());">
'''
try:
for item in SESSION['world'].actors:
page += "<option>%s</option>"%(item.name)
except KeyError:
pass
page += '''</select></form>'''
#Generate the normal links for the actor.
page += '''<hr>
<a href="actor_map.py" target="_blank">Map</a>
<a href="pavlov.py" target="_blank">Association</a>'''
page += "</div>"
self.wfile.write(page)
#Handle page query.
else:
self.wfile.write('''
<html>
<head>
<script type="text/javascript" src="assets/jquery.js"></script>
<link rel="StyleSheet" href="assets/login.css" type="text/css" />
</head>
<body class="widget">
</body>
</html>
''')
|
josephlewis42/personal_codebase
|
python/reprap-franklin/toolheads/__init__.py
|
import toolhead
#Include all other toolheads here
import basic
|
josephlewis42/personal_codebase
|
python/OpenCalc/Main (copy).py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Sat Feb 27 13:35:04 2010
import wx
# begin wxGlade: extracode
import wx.html as html
from Lib.Code import Parser
import sys
# end wxGlade
class CalcWidget(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: CalcWidget.__init__
kwds["style"] = wx.CAPTION|wx.CLOSE_BOX|wx.MINIMIZE_BOX|wx.MAXIMIZE_BOX|wx.SYSTEM_MENU|wx.RESIZE_BORDER|wx.FULL_REPAINT_ON_RESIZE|wx.TAB_TRAVERSAL|wx.CLIP_CHILDREN
wx.Frame.__init__(self, *args, **kwds)
self.main_window = wx.SplitterWindow(self, -1, style=wx.SP_3DBORDER|wx.SP_BORDER|wx.SP_LIVE_UPDATE)
self.help_browser_panel = wx.Panel(self.main_window, -1)
self.main_panel = wx.Panel(self.main_window, -1)
self.notebook_manager = wx.Notebook(self.main_panel, -1, style=0)
self.pad_panel = wx.Panel(self.notebook_manager, -1)
# Menu Bar
self.main_menubar = wx.MenuBar()
wxglade_tmp_menu = wx.Menu()
self.switch_to_pad_menu_item = wx.MenuItem(wxglade_tmp_menu, wx.NewId(), "&Switch To Pad\tCtrl+Shift+P", "Switches to the pad", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendItem(self.switch_to_pad_menu_item)
wxglade_tmp_menu.AppendSeparator()
self.clear_pad_menu_item = wx.MenuItem(wxglade_tmp_menu, wx.NewId(), "&Clear\tCtrl+K", "Clears the pad.", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendItem(self.clear_pad_menu_item)
self.main_menubar.Append(wxglade_tmp_menu, "&Pad")
self.graph_menu = wx.Menu()
self.save_graph = wx.MenuItem(self.graph_menu, wx.NewId(), "Save As", "", wx.ITEM_NORMAL)
self.graph_menu.AppendItem(self.save_graph)
self.main_menubar.Append(self.graph_menu, "&Graph")
self.SetMenuBar(self.main_menubar)
# Menu Bar end
self.main_statusbar = self.CreateStatusBar(1, wx.ST_SIZEGRIP)
self.output_text_ctrl = wx.TextCtrl(self.pad_panel, -1, "", style=wx.TE_MULTILINE)
self.input_text_ctrl = wx.TextCtrl(self.pad_panel, -1, "")
self.button_3 = wx.Button(self.pad_panel, -1, "&Submit")
self.functions_panel = wx.Panel(self.notebook_manager, -1)
self.graphs_panel = wx.Panel(self.notebook_manager, -1)
self.table_panel = wx.Panel(self.notebook_manager, -1)
self.bitmap_button_1 = wx.BitmapButton(self.help_browser_panel, -1, wx.Bitmap("/home/joseph/Python/Calc/Lib/Icons/go-home.png", wx.BITMAP_TYPE_ANY))
self.panel_2 = wx.Panel(self.help_browser_panel, -1)
self.label_1 = wx.StaticText(self.help_browser_panel, -1, "Help Browser", style=wx.ALIGN_CENTRE)
self.html_window = html.HtmlWindow(self.help_browser_panel, -1)
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_MENU, self.switch_to_pad, self.switch_to_pad_menu_item)
self.Bind(wx.EVT_MENU, self.clear_pad, self.clear_pad_menu_item)
self.Bind(wx.EVT_MENU, self.save_graph_as, self.save_graph)
self.Bind(wx.EVT_BUTTON, self.Submit_Input, self.button_3)
self.Bind(wx.EVT_BUTTON, self.LoadPage, self.bitmap_button_1)
# end wxGlade
def __set_properties(self):
# begin wxGlade: CalcWidget.__set_properties
self.SetTitle("OpenCalc")
self.SetSize((640, 509))
self.main_statusbar.SetStatusWidths([-1])
# statusbar fields
main_statusbar_fields = ["OpenCalc 10.0 Stable"]
for i in range(len(main_statusbar_fields)):
self.main_statusbar.SetStatusText(main_statusbar_fields[i], i)
self.bitmap_button_1.SetSize(self.bitmap_button_1.GetBestSize())
# end wxGlade
def __do_layout(self):
# begin wxGlade: CalcWidget.__do_layout
main_sizer = wx.BoxSizer(wx.VERTICAL)
help_browser_sizer = wx.BoxSizer(wx.VERTICAL)
help_browser_title_sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_3 = wx.BoxSizer(wx.VERTICAL)
sizer_3.Add(self.output_text_ctrl, 1, wx.ALL|wx.EXPAND, 5)
sizer_3.Add(self.input_text_ctrl, 0, wx.ALL|wx.EXPAND, 5)
sizer_3.Add(self.button_3, 0, wx.ALL|wx.ALIGN_RIGHT, 5)
self.pad_panel.SetSizer(sizer_3)
self.notebook_manager.AddPage(self.pad_panel, "Pad")
self.notebook_manager.AddPage(self.functions_panel, "Functions")
self.notebook_manager.AddPage(self.graphs_panel, "Graphs")
self.notebook_manager.AddPage(self.table_panel, "Tables")
sizer_2.Add(self.notebook_manager, 1, wx.EXPAND, 0)
self.main_panel.SetSizer(sizer_2)
help_browser_title_sizer.Add(self.bitmap_button_1, 0, 0, 0)
help_browser_title_sizer.Add(self.panel_2, 1, wx.EXPAND, 0)
help_browser_title_sizer.Add(self.label_1, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 8)
help_browser_sizer.Add(help_browser_title_sizer, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 1)
help_browser_sizer.Add(self.html_window, 1, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
self.help_browser_panel.SetSizer(help_browser_sizer)
self.main_window.SplitVertically(self.main_panel, self.help_browser_panel)
main_sizer.Add(self.main_window, 1, wx.EXPAND, 0)
self.SetSizer(main_sizer)
self.Layout()
self.Centre()
# end wxGlade
self.LoadPage("")
self.input_text_ctrl.Bind(wx.EVT_KEY_DOWN, self.input_key_press)
self.main_window.SetMinimumPaneSize(1)
def input_key_press(self, event):
#If the user presses return or enter in the pad input area
keycode = event.GetKeyCode()
#If user pressed enter or return spawn the submit input event
if keycode == wx.WXK_RETURN or keycode == wx.WXK_NUMPAD_ENTER:
self.Submit_Input(event)
event.Skip()
def show_tab(self, event): # wxGlade: CalcWidget.<event_handler>
print "Event handler `show_tab' not implemented!"
event.Skip()
def clear_pad(self, event): # wxGlade: CalcWidget.<event_handler>
self.output_text_ctrl.Clear()
event.Skip()
def save_graph_as(self, event): # wxGlade: CalcWidget.<event_handler>
print "Event handler `save_graph_as' not implemented!"
event.Skip()
def Submit_Input(self, event): # wxGlade: CalcWidget.<event_handler>
if self.input_text_ctrl.GetValue() != "":
#Parse the data
self.output_text_ctrl.AppendText("==" + self.input_text_ctrl.GetValue() + "\n")
self.output_text_ctrl.AppendText(str(Parser.parse(self.input_text_ctrl.GetValue()))+"\n")
#If an error happens above the text will NOT be cleared, allowing the
#user to correct their mistake easily.
self.input_text_ctrl.Clear()
event.Skip()
def LoadPage(self, event): # wxGlade: CalcWidget.<event_handler>
self.html_window.LoadPage("./Lib/Function Lookup/index.html")
def switch_to_pad(self, event): # wxGlade: CalcWidget.<event_handler>
self.notebook_manager.SetSelection(0)
event.Skip()
def write(self,text):
#Used to print stdout to output control
self.output_text_ctrl.AppendText(text+"\n")
event.Skip()
# end of class CalcWidget
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
Main_Frame = CalcWidget(None, -1, "")
app.SetTopWindow(Main_Frame)
#Redirect stdout to the pad
sys.stdout=Main_Frame
Main_Frame.Show()
app.MainLoop()
|
josephlewis42/personal_codebase
|
python/webkit_browser/simple_webkit_browser_with_tabs.py
|
<reponame>josephlewis42/personal_codebase<filename>python/webkit_browser/simple_webkit_browser_with_tabs.py
#!/usr/bin/env python
'''
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of the nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright 2010-08-21 <NAME> <<EMAIL>>
'''
import gtk
import webkit
#Constants
BROWSER_NAME = "Simple Browser"
class MyWebBrowser(gtk.VBox):
def __init__(self):
#Init the program, essentially just create the gtk environment
self.label = gtk.Label("") #Holds the title
#Create the vbox to hold the menubar and gtkwindow
self.vbox = gtk.VBox(False, 2)
self.view = webkit.WebView()
self.view.open("http://www.google.com/")
self.view.connect('title-changed', self.update_title_bar)
self.view.connect('document-load-finished', self.doc_load_finished)
self.sw = gtk.ScrolledWindow()
self.sw.add(self.view)
self.make_menu_bar()
self.vbox.pack_end(self.sw)
def make_menu_bar(self):
'''Makes the menu bar for the program, pretty simple really.'''
#Make the hbox to fit everything in.
self.menu_box = gtk.HBox(False, 5)
#Make the back button and set it up.
self.back_button = gtk.Button(stock=gtk.STOCK_GO_BACK)
self.menu_box.pack_start(self.back_button, False, False, 0)
self.back_button.connect("pressed",self.page_back)
#Make the forward button and set it up.
self.forward_button = gtk.Button(stock=gtk.STOCK_GO_FORWARD)
self.menu_box.pack_start(self.forward_button, False, False, 0)
self.forward_button.connect("pressed",self.page_forward)
#The Refresh button
#The home button
#The url entry box
self.url_entry = gtk.Entry()
self.menu_box.pack_start(self.url_entry, True, True, 0)
#The go button
self.go_button = gtk.Button("Go")
self.menu_box.pack_start(self.go_button, False, False, 0)
self.go_button.connect("pressed",self.go_to_url)
self.vbox.pack_start(self.menu_box, False, False, 0)
def go_to_url(self, event):
'''Goes to the url provided in the input box. Also adds www
and http, if needed.'''
url = self.url_entry.get_text()
#if not url.startswith("www.") and not url.startswith("http://"):
# url = "http://www."+url
if not url.startswith("http://"):
url = "http://"+url
self.view.open(url)
def update_title_bar(self, webview, frame, title):
'''Updates the title bar when a webpage title is changed.'''
self.label.set_label(title)
def doc_load_finished(self, webview, unknown):
'''Changes browser settings when a url is loaded, like location bar, and
title.'''
#Set the title for the page
self.label.set_label(str(self.view.get_property("title")))
#Set the new uri
self.url_entry.set_text( self.view.get_property("uri") )
def page_back(self, event):
'''Go back a page.'''
self.view.go_back()
def page_forward(self, event):
'''Go forward a page.'''
self.view.go_forward()
class MyNotebook(gtk.Notebook):
def __init__(self):
gtk.Notebook.__init__(self)
#set the tab properties
#self.set_property('homogeneous', True)
def new_tab(self):
#Create a new browser to put in the tab
browser = MyWebBrowser()
browser_label = browser.label
browser_vbox = browser.vbox
browser_vbox.show_all()
nbpages = self.get_n_pages()
self.append_page(browser_vbox)
#we create a "Random" image to put in the tab
image = gtk.Image()
nbpages = self.get_n_pages()
icon = gtk.STOCK_ABOUT
image.set_from_stock(icon, gtk.ICON_SIZE_DIALOG)
#self.append_page(image)
#creation of a custom tab. the left image and
#the title are made of the stock icon name
#we pass the child of the tab so we can find the
#tab back upon closure
label, tochild = self.create_tab_label(browser_label, browser_vbox)
label.show_all()
browser.label = tochild
self.set_tab_label_packing(image, True, True, gtk.PACK_START)
#self.set_tab_label(image, label)
self.set_tab_label(browser_vbox, label)
image.show_all()
self.set_current_page(nbpages)
def create_tab_label(self, title, tab_child):
box = gtk.HBox()
title = gtk.Label("Tab")
closebtn = gtk.Button()
#the close button is made of an empty button
#where we set an image
image = gtk.Image()
image.set_from_stock(gtk.STOCK_CLOSE, gtk.ICON_SIZE_MENU)
closebtn.connect("clicked", self.close_tab, tab_child)
closebtn.set_image(image)
closebtn.set_relief(gtk.RELIEF_NONE)
box.pack_start(title, True, True)
box.pack_end(closebtn, False, False)
return box, title
def close_tab(self, widget, child):
pagenum = self.page_num(child)
if pagenum != -1:
self.remove_page(pagenum)
child.destroy()
def on_destroy(win):
gtk.main_quit()
def on_delete_event(widget, event):
gtk.main_quit()
def new_tab(widget):
notebook.new_tab()
if __name__ == "__main__":
window = gtk.Window()
window.set_title( BROWSER_NAME )
window.resize(600,400)
box = gtk.VBox()
button = gtk.Button("New Tab")
box.pack_start(button,False)
button.connect("clicked", new_tab)
notebook = MyNotebook()
box.pack_start(notebook)
window.add(box)
window.connect("destroy", on_destroy)
window.connect("delete-event", on_delete_event)
window.show_all()
gtk.main()
|
josephlewis42/personal_codebase
|
python/randall/alife_randall_checkout/randallai/AI/body.py
|
<filename>python/randall/alife_randall_checkout/randallai/AI/body.py
#!/usr/bin/env python
'''
Copyright (c) 2011 <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
import threading
import time
import pavlov
class Organ():
'''
The organ class represents a bodily need in a creature, for example
hunger, it's value is between 0 and 100 and updated using the
update_function supplied.
This class can trigger events when the value reaches certain levels.
These levels must be added to the dictionary "events" with the key
being the condition sent to the pavlov.ResponseNetwork class
supplied and value being a tuple of size 2 .
For example:
"hello":(2,20)
Would trigger the event "hello" when this particular emotion was
between (and including) 2 and 20.
Alternatively you could use the add_event function.
WARNING:
If you see warnings from this class something has gone horribly
wrong, but it will continue to function, albeit probably wrongly.
The creature may begin to act sporatically or even violently, or may
even commit suicide.
'''
value = 0
last_value = 0
events = {}
name = "Defined at init"
def __init__(self, name, update_function, pavlovrn):
''' Initializes the Organ.
Paramaters:
name -- The name of the organ for identification and warning
purposes. (String)
update_function -- The function called when the organ needs
it's value updated, should return a number
between 0 and 100 inclusive. (Function)
pavlovrn -- An implementation of the pavlov.ResponseNetwork class.
(pavlov.ResponseNetwork)
Raises:
TypeError "ERROR: Wrong type of pavlov.ResponseNetwork class", this
happens if the pavlov.ResponseNetwork class is not an instance
of pavlov.ResponseNetwork.
'''
self.name = name
self.update_function = update_function
if isinstance(pavlovrn, pavlov.ResponseNetwork):
self.response_network = pavlovrn
else:
raise TypeError, "ERROR: Wrong type of pavlov.ResponseNetwork class"
def update(self):
'''Updates the value of this Organ by calling the update
function. If the value is less than 0 it will be made to be
equal to 0 and if it is > 100 the value will be set to 100.
'''
try:
#Try providing the current value.
try:
v = self.update_function(self.value)
except TypeError:
v = self.update_function()
#Check for illegal values.
if v < 0:
v = 0
if v > 100:
v = 100
self.last_value = self.value
self.value = v
except TypeError:
print("ERROR: The update function for %s is not a function!" % (self.name))
raise
except ValueError:
print("ERROR: The update function for %s didn't return a number." % (self.name))
raise
self.send_events()
def send_events(self):
'''Sends events for values set in the events dictionary by the
user.
This class can trigger events when the value reaches certain levels.
These levels must be added to the dictionary "events" with the key
being the condition sent to the pavlov.ResponseNetwork class
supplied and value being a tuple of size 2 .
For example:
"hello":(2,20)
Would trigger the event "hello" when this particular emotion was
between (and including) 2 and 20.
Alternatively you could use the add_event function.
NOTE:
This function is called periodically by the Body class, it
does not need to be done manually unless desired.
'''
for cond in self.events.keys():
low, high = self.events[cond]
if self.value in range(low, high + 1):
self.response_network.condition(cond)
def add_event(self, low, high, event_name):
'''A convenience function for adding events to the emotion.
Paramaters:
low -- The low number to trigger the event.
high -- The high number to stop triggering the event at.
event_name -- The event sent to the pavlov.ResponseNetwork class.
'''
self.events[event_name] = (low, high)
def autogen_events(self, step=10, start=0, stop=101):
'''
Autogenerates events for ranges starting at start ending at stop
every stop numbers and adds them to the response_network neuron
list. Returns a list of these events.
Example:
>>> autogen_events(10, 20, 50)
['name_20','name_30','name_40']
Where name is the name of this emotion.
Event name_20 would be triggered from 20-29, name_30 30-49 and
name_40 from 40-49.
'''
new_events = range(start, stop, step)
#Add the maximum so we can get to the stop.
new_events.append(stop)
newnames = []
x = 0
while x < len(new_events) - 1:
#Generate the name of this event.
e_name = "%s_%d" % (self.name, new_events[x])
newnames.append(e_name)
#Generate new neurons
self.response_network.register_con_res(e_name)
#Generate it locally, subtract from the high so there aren't
#conflicts in ranges.
self.add_event(new_events[x], new_events[x+1] - 1, e_name)
x += 1
return newnames
def get_value(self):
'''A getter that is used by any function that needs a dynamic way
to get the value. (I'm looking at you maslow!)
'''
return self.value
class Body(threading.Thread):
'''A simple container for organs.
To add organs, just append them to the variable "organs".'''
organs = []
_update_time = None
_awake = True #True if thread is running, false to kill it.
def __init__(self, update_time=1, begin=True):
'''Sets up the body.
Paramaters:
update_time -- A function that returns a float as the number of
seconds until the organs update and fire events,
or just a float. | DEFAULT:1 | (function, float)
begin -- Whether or not to start the thred as soon as done
initializing. If false, the thread won't ever trigger
events or check for value correctness unless you
manually start it by calling start()
DEFAULT: True (boolean)
'''
self._update_time = update_time
threading.Thread.__init__(self)
if begin:
self.start()
def run(self):
self._awake = True
while self._awake:
#Handle update times for functions and numbers.
if hasattr(self._update_time, '__call__'):
ut = float(self._update_time())
else:
ut = self._update_time
#Wait so we don't hog the cpu
time.sleep(ut)
#Have all the organs fetch new values
#and fire events to the pavlov network.
for organ in self.organs:
organ.update()
def sleep(self):
'''Kills the thread.'''
self._awake = False
def __len__(self):
'''Returns the number of organs registered.'''
return len(self.organs)
def __getitem__(self, key):
'''Emulates a list or dictionary, called with the name of the
organ, or an index. Raises IndexError if not found.
Example:
>>> <Body>['eyes']
<class Organ at 0x0000007b>
>>> <Body>[0]
<class Organ at 0x0000002a>
>>> <Body>[None]
IndexError
'''
#Check for strings
try:
for n in self.organs:
if n.name == key:
return n
except TypeError:
pass
#Check for indexes
try:
return self.organs[key]
except TypeError:
pass
#else raise error
raise IndexError
def append(self, o):
'''Adds the given organ (o) to the body.'''
self.organs.append(o)
|
josephlewis42/personal_codebase
|
python/game_of_life/conway.py
|
#!/usr/bin/env python
''' Conway's game of life in python.
Copyright 2011-09-30 <NAME> <<EMAIL>> MIT License
1. Any live cell with fewer than two live neighbours dies.
2. Any live cell with two or three live neighbours lives.
3. Any live cell with more than three live neighbours dies.
4. Any dead cell with exactly three live neighbours becomes alive.
-- Wikipedia.
'''
import random
import time
ROWSCOLS = None # Number of rows and columns in the game.
grid = None # A grid with 0s and 1s, 0 is no cell, 1 is a cell.
def printgrid():
'''Prints out the given grid after blanking the screen.'''
print 10 * "\n"
print "+"+ "-" * ROWSCOLS + "+" # Border top
for r in grid:
line = "|" # Border Left
for c in r:
if c:
line += "0" # Cell
else:
line += " "
print line + "|" # Border Right
print "+"+ "-" * ROWSCOLS + "+" # Border Bottom
def do_life():
'''calculates the next grid'''
grid_len = range(0,ROWSCOLS)
grid2 = [[0 for i in grid_len] for i in grid_len]
for r in grid_len:
for c in grid_len:
if grid[r][c]:
increment(grid2, r, c)
for r in grid_len:
for c in grid_len:
g = grid2[r][c]
if g < 2 or g > 3:
grid[r][c] = 0
elif g == 3:
grid[r][c] = 1
def increment(grid, row, col):
'''Increments the life count for all cells around this one.'''
for r,c in [(row, col+1), (row, col-1),
(row+1, col), (row-1, col),
(row+1, col+1), (row-1, col-1),
(row+1, col-1), (row-1, col+1)]:
grid[r % ROWSCOLS][c % ROWSCOLS] += 1
def start_life():
'''Randomly fills the game.'''
for i in range(0, ROWSCOLS**2 / 4):
r = random.randint(0, ROWSCOLS-1)
c = random.randint(0, ROWSCOLS-1)
grid[r][c] = 1
if __name__ == "__main__":
try:
print("=Conways Game of Life=")
k = int(input("How many turns should I run before I reset (200 is nice)? "))
ROWSCOLS = int(input("How many rows and columns of life should there be (35 is nice)? "))
t = float(input("How many frames per secould should I run (10 is nice)? "))
except Exception:
print("Hey! Play nice, enter a number!")
exit(1)
grid = [[0 for i in range(0, ROWSCOLS)] for i in range(0, ROWSCOLS)]
j = 0
while True:
if not j:
start_life()
j = k # Number of turns to run before restart.
j -= 1
do_life()
printgrid()
time.sleep(1/t)
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex2_realgauss.py
|
<gh_stars>1-10
from pyevolve import GSimpleGA
from pyevolve import G1DList
from pyevolve import Selectors
from pyevolve import Initializators, Mutators
# Find negative element
def eval_func(genome):
score = 0.0
for element in genome:
if element < 0: score += 0.1
return score
def run_main():
# Genome instance
genome = G1DList.G1DList(20)
genome.setParams(rangemin=-6.0, rangemax=6.0)
# Change the initializator to Real values
genome.initializator.set(Initializators.G1DListInitializatorReal)
# Change the mutator to Gaussian Mutator
genome.mutator.set(Mutators.G1DListMutatorRealGaussian)
# The evaluator function (objective function)
genome.evaluator.set(eval_func)
# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.selector.set(Selectors.GRouletteWheel)
ga.setGenerations(100)
# Do the evolution
ga.evolve(freq_stats=10)
# Best individual
print ga.bestIndividual()
if __name__ == "__main__":
run_main()
|
josephlewis42/personal_codebase
|
python/spellcheck/spell_checker.py
|
<filename>python/spellcheck/spell_checker.py
#!/usr/bin/env python
'''A simple spell checker for Python, modified version of <NAME>'s
http://norvig.com/spell-correct.html
Created by: <NAME> <joehms22 [at] gmail [dot] com> 2012-09-19
'''
import re
import collections
DICTIONARY_FILE = "american-english"
class Checker:
known_words = set()
check_cache = {}
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def __init__(self):
''' Sets up the checker. '''
with open(DICTIONARY_FILE) as fp:
self.populate_dict(fp)
def populate_dict(self, fp):
''' Populates the known-words dictionary. '''
# normalize everything in the aspell dict
doc = fp.read()
doc = doc.lower()
doc = re.sub(r'[^\w\s]+', '', doc)
for word in doc.split():
self.known_words.add(word)
def get_doc_dict(self, document_words_list):
'''Gets a word->frequency dict for the words in the given doc.'''
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
def check_word(self, word, doc_dict={}):
''' Checks the given word against the dictionary, returns a "corrected"
one. '''
word = word.lower()
try:
return self.check_cache[word]
except KeyError:
pass # faster than if in
if word in self.known_words:
return word
candidates = self.known([word]) or self.known(self.edits1(word)) or self.known_edits2(word) or [word]
nuword = max(candidates, key=doc_dict.get)
if len(candidates) == 1:
self.check_cache[word] = nuword
return nuword
twitterizations = {"":"", "4":"for", "2":"to", "txt":"text"}
def edits1(self, word):
twitterizations = [word.replace(k,v) for k,v in self.twitterizations.items()]
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in splits if b]
transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
replaces = [a + c + b[1:] for a, b in splits for c in self.alphabet if b]
inserts = [a + c + b for a, b in splits for c in self.alphabet]
return set(deletes + transposes + replaces + inserts + twitterizations)
def known_edits2(self, word):
return set(e2 for e1 in self.edits1(word) for e2 in self.edits1(e1) if e2 in self.known_words)
def known(self, words):
return set(w for w in words if w in self.known_words)
|
josephlewis42/personal_codebase
|
python/PersonalFileServer/Site/index.py
|
self.send_200()
self.wfile.write('''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Upload/Download</title>
<style TYPE="text/css">
body {
background-color:#ADD8E6;
text-align:center;
margin:0px;
padding:0px;
font-family:airal,helvetica;
}
.main{
display:block;
background-color:#E5E5E5;
margin-left:auto;
margin-right:auto;
padding:10px;
width:800px;
}
</style>
<script type="text/javascript">
function getNameFromPath(strFilepath) {
var objRE = new RegExp(/([^\\/\\\\]+)$/);
var strName = objRE.exec(strFilepath);
if (strName == null) {
return null;
}
else {
return strName[0];
}
}
function setName()
{
document.getElementById('filename').value = getNameFromPath(document.getElementById('up').value);
}
</script>
</head>
<body>
<div class="main">
<H1>Upload / Download Files</H1>
<form action="upload.py" enctype="multipart/form-data" method="post">
<input type="file" name="myfile" size="chars" id="up">
<input name="filename" id="filename" type="hidden"></input>
<input type="submit" value="Send" onclick="setName()">
</form>
<hr>
<h2>Download</h2>
<ul>
''')
import os
j = os.listdir("Downloads")
for item in j:
self.wfile.write("<li><a href='download.py?f=%s'>%s</a></li>" % (item,item))
self.wfile.write('''
</ul>
</div>
</body>
</html>''')
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex1_simple.py
|
from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import Statistics
from pyevolve import DBAdapters
# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(genome):
score = 0.0
# iterate over the chromosome
# The same as "score = len(filter(lambda x: x==0, genome))"
for value in genome:
if value==0:
score += 1
return score
def run_main():
# Genome instance, 1D List of 50 elements
genome = G1DList.G1DList(50)
# Sets the range max and min of the 1D List
genome.setParams(rangemin=0, rangemax=10)
# The evaluator function (evaluation function)
genome.evaluator.set(eval_func)
# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
# Set the Roulette Wheel selector method, the number of generations and
# the termination criteria
ga.selector.set(Selectors.GRouletteWheel)
ga.setGenerations(500)
ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria)
# Sets the DB Adapter, the resetDB flag will make the Adapter recreate
# the database and erase all data every run, you should use this flag
# just in the first time, after the pyevolve.db was created, you can
# omit it.
sqlite_adapter = DBAdapters.DBSQLite(identify="ex1", resetDB=True)
ga.setDBAdapter(sqlite_adapter)
# Do the evolution, with stats dump
# frequency of 20 generations
ga.evolve(freq_stats=20)
# Best individual
print ga.bestIndividual()
if __name__ == "__main__":
run_main()
|
josephlewis42/personal_codebase
|
Euler/008.py
|
#!/usr/bin/env python
'''
Find the greatest product of five consecutive digits in the 1000-digit number.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
'''
nums = "73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450"
m = 0
for i in range(len(nums) - 4):
t = int(nums[i]) * int(nums[i + 1]) * int(nums[i + 2]) * int(nums[i + 3]) * int(nums[i + 4])
if t > m:
print i
m = t
print m
|
josephlewis42/personal_codebase
|
Euler/003.py
|
<filename>Euler/003.py
#!/usr/bin/env python
'''
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
import pymath
print max(pymath.prime(pymath.factor(600851475143)))
|
josephlewis42/personal_codebase
|
python/reprap-franklin/inputs/file_input.py
|
<gh_stars>1-10
#!/usr/bin/env python
import threading
import time
class FileInput( threading.Thread ):
def __init__(self, reprap, source, delay=None):
self.reprap = reprap
self.source = source
self.delay = delay
threading.Thread.__init__(self)
self.daemon = True
def run(self):
with open(self.source) as src:
for line in src:
self.reprap.current_firmware.execute_gcode(line)
if callable(self.delay):
self.delay()
else:
time.sleep( float(self.delay) )
print("Done reading from file.")
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex4_sigmatrunc.py
|
from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import Initializators, Mutators
from pyevolve import Scaling
from pyevolve import Consts
import math
def eval_func(ind):
score = 0.0
var_x = ind[0]
var_z = var_x**2+2*var_x+1*math.cos(var_x)
return var_z
def run_main():
# Genome instance
genome = G1DList.G1DList(1)
genome.setParams(rangemin=-60.0, rangemax=60.0)
# Change the initializator to Real values
genome.initializator.set(Initializators.G1DListInitializatorReal)
# Change the mutator to Gaussian Mutator
genome.mutator.set(Mutators.G1DListMutatorRealGaussian)
# Removes the default crossover
genome.crossover.clear()
# The evaluator function (objective function)
genome.evaluator.set(eval_func)
# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.setMinimax(Consts.minimaxType["minimize"])
pop = ga.getPopulation()
pop.scaleMethod.set(Scaling.SigmaTruncScaling)
ga.selector.set(Selectors.GRouletteWheel)
ga.setGenerations(100)
# Do the evolution
ga.evolve(10)
# Best individual
print ga.bestIndividual()
if __name__ == "__main__":
run_main()
|
josephlewis42/personal_codebase
|
python/reprap-franklin/firmware/full.py
|
#!/usr/bin/env python
'''Provides a fullly implemented GCode parser for Franklin.
Commands can be passed in one at a time through the execute_gcode
function, returncodes will be returned.
Copyright 2011 <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
import string
#Implements a full gcode parser.
class GCode:
'''Takes a single line of GCode, and parses it in to its parts.
==All of the below types have a default None value.==
cmd_type - The type of command, G,M,T
checksum - The checksum of the command.
checksum_pass - Whether or not the checksum is correct. (boolean)
comment - The comment for the line of GCode
cmd - The command i.e. G28
line_number - The line number of the current command.
S,P,X,Y,Z,I,J,F,R,Q,E,N - Optional arguments, values will be None
or int/float.
'''
cmd_type = None
checksum = None
checksum_pass = None
comment = None
cmd = None
line_number = None
#Paramaters.
S = P = X = Y = Z = I = J = F = R = Q = E = N = G = M = T = None
def grab_int(self, string):
'''Grabs the paramater from a code as an int, if not possible
returns None.
'''
try:
return int(string[1:])
except:
return None
def __init__(self, code):
'''Creates a GCode object from a line of GCode.'''
#Cut off comment.
if ';' in code:
code, self.comment = code.split(";", 2)
#Cut off checksum.
if '*' in code:
code, cs = code.split("*", 2)
self.checksum = int(cs)
#Verify the checksum
v = 0
for c in code:
v = v ^ ord(c)
self.checksum_pass = (v == self.checksum)
#Make sure this isn't an END statment
if code.startswith("END"):
return
#Make sure all letters have spaces in front of them.
for c in string.ascii_letters:
code = code.replace(c, ' %s'%(c))
#Split in to individual paramaters.
cmds = code.split()
for c in cmds:
if c.startswith('N'): #Line number command.
n = self.grab_int(c)
self.line_number = n
self.N = n
elif c[0] == 'G':
self.G = self.grab_int(c)
self.cmd_type = 'G'
self.cmd = c
elif c[0] == 'M':
self.M = self.grab_int(c)
self.cmd_type = 'M'
self.cmd = c
elif c[0] == 'T':
self.T = self.grab_int(c)
self.cmd_type = 'T'
self.cmd = c
else: #All other types are floats.
try:
t = c[0]
val = float(c[1:])
exec("self.%s = %s" % (t, val))
except ValueError as exc: #Empty string causes, but how does that happen?
print("\n\nError while parsing %s: %s" % (c, exc))
except SyntaxError, e:
print ("ERROR: SyntaxError %s" % (e))
print (" : %s" % (c))
print (" : %s" % (code))
class Coords:
'''A representation of x,y,z and e coordinates for the RepRap'''
x = 0
y = 0
z = 0
e = 0
def __init__(self, gc=None, co=None):
'''Creates a new coordinate system with all zero coordinates,
unless a paramater is passed.
gc - An instance of GCode, X,Y,Z,E values are taken from here.
'''
if gc:
self.setup(gc)
if co:
self.x = co.x
self.y = co.y
self.z = co.z
self.e = co.e
def copy(self):
'''Returns a copy of the current coordinates.'''
return Coords(co=self)
def __str__(self):
return "X:%s Y:%s Z:%s E:%s" % (self.x, self.y, self.z, self.e)
def setup(self, gc):
'''Sets the variables from a GCode instance.'''
if gc.X:
self.x = gc.X
if gc.Y:
self.y = gc.Y
if gc.Z:
self.z = gc.Z
if gc.E:
self.e = gc.E
def offset(self, other):
'''Offsets these coordinates from another, extrude value
is copied.'''
self.x += other.x
self.y += other.y
self.z += other.z
self.e = other.e
def in_to_mm(self):
'''Multiplies all coordinates by 25.4, the number of mm in an
inch.
'''
self.scale(25.4) #Num of mm in an in
def scale(self, factor):
'''Scales all coordinates by factor, including e.'''
self.x *= factor
self.y *= factor
self.z *= factor
self.e *= factor
class Firmware (object):
'''The firmware baseclass, all GCodes are implemented here as
functions that take in a GCode class as their paramater.
The function need not return any value, but if it does it needs
to be a string, not newline terminated. If nothing is returned
an ok is sent back to the machine.
'''
title = ""
origin = Coords() #Origin of the machine.
display = Coords() #Center of display.
display.x = 125 #Center of grid (mm)
display.y = 125 #Center of grid (mm)
last = Coords() #The last location the toolhead was at.
last.offset(origin) #Set current location to origin.
line_number = 0 #The current line number.
absolute = True #Type of positioning Flase is Relative.
units_mm = True #Are the units in mm:True in:False
STEPS_PER_MM = 2 #Number of steps per mm
#Default debugging level for RepRap
debug_echo = False
debug_info = True
debug_errors = True
#Information about the RepRap Firmware
#Extruder count will be generated at runtime and appended at the end.
FIRMWARE_INFO = "PROTOCOL_VERSION:0.1 FIRMWARE_NAME:FiveD MACHINE_TYPE:Mendel"
def __init__(self, reprap):
'''Starts the firmware with the given reprap.'''
self.reprap = reprap
def debug(self, msg):
'''Prints a debugging message.'''
if self.debug_info:
print ("DEBUG: %s" % (msg))
def error(self, msg):
'''Print an error message if errors is on.'''
if self.debug_errors:
print("ERROR: %s" % (msg))
def warning(self, msg):
'''Print a warning message.'''
if self.debug_errors:
print ("WARNING: %s" % (msg))
def mm(self, value):
'''If the current units are not mm, converts to mm.'''
if not self.units_mm:
return 25.4 * value
def steps(self, value):
'''Returns the number of steps that a distance comprises of.
Any unit conversions are done here.
'''
return self.STEPS_PER_MM * self.mm(value)
def G0(self, gc):
co = self.last.copy() #Start off with last values.
co.setup(gc) #Set up for the given values.
if not self.units_mm:
co.in_to_mm()
#If we are offsetting from origin.
if self.absolute:
co.offset(self.origin)
else: #If we are offsetting from last position.
co.offset(self.last)
#Draw line from the last place to the current place, pass
#duplicate coordinate systems though so the printbed
#can scale without messing us up.
dco = self.display.copy()
dco.offset(co)
dcl = self.display.copy()
dcl.offset(self.last)
self.reprap.move_toolhead(dco, dcl)
#Set the current location to last.
self.last = co
if self.debug_echo:
self.debug("G0/G1: Move to %s" % (self.last))
pass
G1 = G0 #The rep-rap firmware uses the same code for G0/G1
def G28(self, gc):
self.debug("G28: Move to origin.")
if gc.X or gc.Y or gc.Z:
if gc.X:
self.last.x = self.origin.x
if gc.Y:
self.last.y = self.origin.y
if gc.Z:
self.last.z = self.origin.z
else:
self.last = self.origin.copy()
def G4(self, gc):
self.debug("G4: Dwelling")
def G20(self, gc): #Units to inches.
self.debug("G20: Setting units to Inches")
self.units_mm = False
def G21(self, gc): #Units to mm.
self.debug("G21: Setting units to Milimeters")
self.units_mm = True
def G90(self, gc):
self.debug("G90: Setting absolute positioning.")
self.absolute = True
def G91(self, gc):
self.debug("G91: Setting relative positioning.")
self.relative = True
def G92(self, gc):
#Must move before debug.
self.origin.setup(gc)
self.debug("G92: Setting new position: %s" % (self.origin))
def M0(self, gc):
self.debug("M0: Stop")
self.reprap.stop = True
def M84(self, gc):
self.debug("M84: Stop idle hold.")
self.reprap.idle_hold_on = False
def M104(self, gc):
self.debug("M104: Set temperature (fast) %s" % (gc.S))
self.reprap.current_toolhead.temperature = int(gc.S)
def M105(self, gc):
self.debug("M104: Get extruder temperature.")
tt = self.reprap.current_toolhead.temperature
bt = self.reprap.bed.temperature
return "ok T:%s B:%s" % (int(tt), int(bt))
def M106(self, gc):
self.debug("M106: Fan on.")
self.reprap.fan = True
def M107(self, gc):
self.debug("M106: Fan off.")
self.reprap.fan = False
def M108(self, gc):
self.debug("M108: Set extruder speed to %s." % (gc.S))
self.error("M108: DEPRECATION WARNING: Use M113 instead.")
if gc.S:
self.reprap.current_toolhead.extrude_rate = gc.S
def M109(self, gc):
self.debug("M109: Set extruder temperature to %s." % (int(gc.S)))
if gc.S:
self.reprap.current_toolhead.temperature = int(gc.S)
def M110(self, gc):
self.debug("M110: Set current line number to %s." % (gc.N))
if gc.N:
self.line_number = int(gc.N)
def M111(self, gc):
self.debug("M111: Set debug level: %s" % (gc.S))
if gc.S:
self.debug_echo = int(gc.S) >> 0 & 1
self.debug_errors = int(gc.S) >> 2 & 1
self.debug_info = int(gc.S) >> 1 & 1
def M112(self, gc):
self.debug("M112: Emergency stop.")
self.error("M112: Emergency stop.")
self.reprap.stop = True
def M113(self, gc):
self.debug("M113: Set extruder PWM")
self.reprap.current_toolhead.extrude_rate = 10
if gc.S:
self.reprap.current_toolhead.extrude_rate = int(gc.S * 10)
def M114(self, gc):
self.debug("M114: Get current position: %s." % (self.last))
return "ok C: %s" % (self.last)
def M115(self, gc):
nt = len(self.reprap.possible_toolheads) #Number of toolheads
output = "ok %s EXTRUDER_COUNT:%s" % (self.FIRMWARE_INFO, nt)
self.debug("M115: Get firmware version and capabilities.")
self.debug(" >> %s" % (output))
return output
def M116(self, gc):
self.debug("M116: Wait.")
def M117(self, gc):
self.debug("M117: Get zero position.")
return "ok C: X:0 Y:0 Z:0 E:0"
def M126(self, gc):
self.debug("M126: Open valve.")
self.reprap.current_toolhead.open_valve()
def M127(self, gc):
self.debug("M126: Close valve.")
self.reprap.current_toolhead.close_valve()
def M140(self, gc):
self.debug("M140: Set bed temperature to %s (fast)." % (int(gc.S)))
if gc.S:
self.reprap.bed.temperature = int(gc.S)
def M141(self, gc):
self.debug("M141: Set chamber temperature to %s (fast)." % (int(gc.S)))
if gc.S:
self.reprap.chamber.temperature = int(gc.S)
def M142(self, gc):
self.debug("M142: Set holding pressure to %s." % (int(gc.S)))
if gc.S:
self.reprap.bed.pressure = int(gc.S)
def M226(self, gc):
self.debug("M226: GCode initiated pause.")
self.reprap.paused = True
def M227(self, gc):
self.debug("M227: Enable reverse and prime, does nothing.")
def M228(self, gc):
self.debug("M228: Disalbe auto reverse and prime, does nothing.")
def M229(self, gc):
self.debug("M229: Enable reverse and prime, does nothing.")
def M230(self, gc):
self.debug("M230: Disable/Enable wait for temp change, does nothing.")
def T(self, gc):
try:
new_toolhead = self.reprap.possible_toolheads[gc.T]
self.debug("T: Select tool #%s, %s" % (gc.T, new_toolhead.name))
self.reprap.current_toolhead = new_toolhead
except:
self.error("T: ERROR: Couldn't select the given toolhead, does it exist?")
def illegal_use_command(self, gc):
'''Use this as a command replacement for any commands that
aren't implemented in your hardware.
EXAMPLE: If M111 isn't allowed in your firmware, do:
>>> M111 = illegal_use_command
>>> M111(gc)
The command M111 is not legal for this firmware!
>>>
'''
self.warning("The command %s is not legal for this firmware!" % gc.cmd)
def execute_gcode(self, cmd):
'''Executes a single gcode command (cmd).'''
gc = GCode(cmd) #Create a GCode representation of the cmd.
#If the user wants echo debugging.
if self.debug_echo:
print(cmd)
if gc.cmd_type == 'T':
self.T(gc)
elif gc.cmd != None:
try:
retcode = eval("self.%s(gc)" % (gc.cmd))
if retcode != None:
return retcode + "\n"
except AttributeError, e:
print ("ERROR: %s is not a valid command." % (gc.cmd))
print ("%s" % (e))
return "ok\n"
class FullWare (Firmware):
title = "Full Implementation"
|
josephlewis42/personal_codebase
|
python/stpetersburg.py
|
<gh_stars>1-10
#!/usr/bin/python
'''stpetersburg.py -- A saint petersburg simulator.
2011/02/25 15:36:28
Copyright 2011 <NAME> <<EMAIL>>
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 random
def play():
total_won = 0
payoff_matrix = {}
print("Iter:\tFlips:\tWinnings:\tWon?")
for i in range(iterations):
winnings = 0
flips = flip(max_game) #Flip the coin until tails.
#Determine winnings based upon the wager multiplier and flips.
if flips:
winnings = multiplier**(flips)
#Stats
total_won += winnings
if flips in payoff_matrix.keys():
payoff_matrix[flips] = payoff_matrix[flips] + 1
else:
payoff_matrix[flips] = 1
print("%i\t%i\t%i\t\t%s" % (i, flips, winnings, winnings >= initial_wager))
#Do some basic stats.
avg_won = float(total_won) / iterations
print ("Avg. Winnings:\t%d" % (avg_won))
print ("Flips x Frequency")
for k in payoff_matrix.keys():
print("%s x %s" % (k, payoff_matrix[k]))
print ("Money Won: %s" % (total_won))
print ("Money Waged: %s" % (iterations * initial_wager))
def flip(max_flip):
'''Flips a coin until max_flip is reached or the coin turns up
tails. Returns the number of flips that came up heads.
If max_flip is -1 flipping will continue until a tails is reached.
'''
numflips = 0
while numflips != max_flip:
numflips += 1
if random.randint(0,1): #0 = heads 1 = Tails:
return numflips
return numflips
def ask_int(question, default):
'''Asks the user for an int printing out the default and question.
'''
num = raw_input(question + " (Default: %s)\n" % (str(default)))
if num == '':
return default
return int(num)
if __name__ == "__main__":
print __doc__ #Notify the user of the license (top of file)
#Set up simulation
iterations = ask_int("How many iterations?", 100000)
initial_wager = ask_int("What is the initial wager?", 2)
multiplier = ask_int("What is the multiplier per win?", 2)
max_game = ask_int("What is the bound on the number of games -1 for infinity?", -1)
#Start simulation
play()
|
josephlewis42/personal_codebase
|
python/OpenCalc/Lib/Code/Variables.py
|
<gh_stars>1-10
#!/usr/bin/python
#Define A-Z
a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0
h = 0
i = 0
j = 0
k = 0
l = 0
m = 0
n = 0
o = 0
p = 0
q = 0
r = 0
s = 0
t = 0
u = 0
v = 0
w = 0
x = 0
y = 0
z = 0
|
josephlewis42/personal_codebase
|
python/apropos.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Fri Oct 29 10:43:01 2010
import wx
# begin wxGlade: extracode
# end wxGlade
class MainFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MainFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.label_1 = wx.StaticText(self, -1, "Program Search", style=wx.ALIGN_CENTRE)
self.text_ctrl_1 = wx.TextCtrl(self, -1, "")
self.label_2 = wx.StaticText(self, -1, "Results:")
self.text_ctrl_2 = wx.TextCtrl(self, -1, "Enter search terms above:\nPrograms will appear here.", style=wx.TE_MULTILINE|wx.TE_READONLY)
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_TEXT, self.enter_search_text, self.text_ctrl_1)
# end wxGlade
def __set_properties(self):
# begin wxGlade: MainFrame.__set_properties
self.SetTitle("Program Search")
self.SetSize((500, 250))
# end wxGlade
def __do_layout(self):
# begin wxGlade: MainFrame.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_1.Add(self.label_1, 0, wx.EXPAND, 0)
sizer_1.Add(self.text_ctrl_1, 0, wx.ALL|wx.EXPAND, 5)
sizer_1.Add(self.label_2, 0, wx.LEFT, 5)
sizer_1.Add(self.text_ctrl_2, 1, wx.ALL|wx.EXPAND, 5)
self.SetSizer(sizer_1)
self.Layout()
# end wxGlade
def show_help_text(self):
text='''Enter a query above, program names will appear below.
Ex: calculator, tells you the different calculators on your system.
This is a frontend for the apropos command.
Created by: <NAME> <<EMAIL>>'''
self.text_ctrl_2.Clear()
#print new search query
self.text_ctrl_2.AppendText(text)
def enter_search_text(self, event): # wxGlade: MainFrame.<event_handler>
import subprocess
process = subprocess.Popen(["apropos", self.text_ctrl_1.GetValue()], stdout=subprocess.PIPE)
output, unused_err = process.communicate()
#clear output
self.text_ctrl_2.Clear()
#print new search query
self.text_ctrl_2.AppendText(output)
event.Skip()
'''
#if text none, replace with default msg
if self.text_ctrl_1.GetValue() == "":
self.show_help_text()
#if text, search
else:
import subprocess
process = subprocess.Popen(["apropos", self.text_ctrl_1.GetValue()], stdout=subprocess.PIPE)
output, unused_err = process.communicate()
retcode = process.poll()
#clear output
self.text_ctrl_2.Clear()
#print new search query
self.text_ctrl_2.AppendText(output)
event.Skip()
'''
# end of class MainFrame
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MainFrame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
frame_1.show_help_text()
app.MainLoop()
|
josephlewis42/personal_codebase
|
python/get_firefox_bookmarks.py
|
#!/usr/bin/python
# get_firefox_bookmarks.py
#
# Copyright 2010 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
'''
Gets firefox bookmarks and saves them to ~/Backup/Firefox Bookmarks as a
json document that can be restored in firefox manually later.
Bookmarks > Organize Bookmarks [Import/Export]
'''
print 'Retrieveing Firefox Bookmarks, please shut down Firefox before doing this operation.'
import os
#Get folder location
firefoxdir = os.path.expanduser("~/.mozilla/firefox")
os.chdir(firefoxdir)
#Get Profile information
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('profiles.ini')
firefoxdir += "/" + config.get("Profile0", "Path") + "/bookmarkbackups"
os.chdir(firefoxdir)
#Get json documents in file
list = os.listdir(firefoxdir)
#Get the most recent bookmark save file
list.sort()
list.reverse()
firefoxdir += "/" + list[0]
savedir = os.path.expanduser("~/Backup/Firefox Bookmarks/")
#copy it to savedir
import shutil
shutil.copy(firefoxdir, savedir)
|
josephlewis42/personal_codebase
|
Euler/012.py
|
<gh_stars>1-10
#!/usr/bin/env python
u'''
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
'''
import pymath
i = 1
while True:
triangle = pymath.triangluar_number(i)
if len(pymath.factor(triangle)) > 500:
print triangle
break
i += 1
pymath.print_prob(1000, "1000 done")
|
josephlewis42/personal_codebase
|
python/randall/alife_randall_checkout/ai_webserver/pavlov.py
|
# pavlov.py
#
# Copyright 2011 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
self.send_200()
if not SESSION or 'login' not in SESSION.keys() or not SESSION['login']:
self.wfile.write("You are not logged in...<script type='text/javascript'>window.location = 'login.py'</script>")
#Handle AJAX query.
elif 'reload' in QUERY_DICT.keys():
try:
w = SESSION['world']
a = SESSION['actor']
content = w[a].response_network.export_HTML_table()
#Make bars for used emotions
page = '''<h3>Pavlov Response Network:</h3>
<div id="progresscontainer">
%s
</div>''' % (content)
self.wfile.write(page)
except KeyError, e:
self.wfile.write("Error: Couldn't find the key specified: %s" %(e))
except Exception, e:
self.wfile.write("Error: %s" %(e))
#Handle page query.
else:
page = '''
<html>
<head>
<script type="text/javascript" src="assets/jquery.js"></script>
<script type="text/javascript" src="assets/reloader.js"></script>
<link rel="StyleSheet" href="assets/login.css" type="text/css" />
</head>
<body onLoad="javascript:Update(2000, 'body', 'pavlov.py?reload=true');" style="background-color:#fff;" class="widget pavlov">
Loading...
</body>
</html>
'''
self.wfile.write(page)
|
josephlewis42/personal_codebase
|
python/email_attachment_extractor.py
|
#!/usr/bin/env python3
import email.parser
import os
import sys
import base64
import binascii
import sys
def extract(rootdir):
fileList = []
for root, subFolders, files in os.walk(rootdir):
for file in files:
fileList.append(os.path.join(root,file))
for path in fileList:
if not path.endswith(".eml"):
continue
fp = email.parser.BytesFeedParser()
fp.feed(open(path, "rb").read())
message = fp.close()
print("Checking {}".format(path))
for message in message.walk():
fn = message.get_filename()
if fn == None:
continue
try:
try:
with open(fn, 'wb') as out:
out.write(message.get_payload(decode=True))
except (TypeError, binascii.Error):
with open(fn, 'wb') as out:
print(message.get_payload())
out.write(bytes(message.get_payload(), message.get_charset()))
except Exception:
print("Error extracting item from {}".format(path))
if __name__ == "__main__":
if len(sys.argv) == 1:
print("usage: {} path/to/.eml/files".format(sys.argv[0]))
exit(1)
extract(sys.argv[1])
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex6_dbadapter.py
|
<gh_stars>1-10
from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import DBAdapters
from pyevolve import Statistics
# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
score = 0.0
# iterate over the chromosome
for value in chromosome:
if value==0:
score += 0.5
return score
# Genome instance
genome = G1DList.G1DList(100)
genome.setParams(rangemin=0, rangemax=10)
# The evaluator function (objective function)
genome.evaluator.set(eval_func)
# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome, 666)
ga.setGenerations(80)
ga.setMutationRate(0.2)
# Create DB Adapter and set as adapter
#sqlite_adapter = DBAdapters.DBSQLite(identify="ex6", resetDB=True)
#ga.setDBAdapter(sqlite_adapter)
# Using CSV Adapter
#csvfile_adapter = DBAdapters.DBFileCSV()
#ga.setDBAdapter(csvfile_adapter)
# Using the URL Post Adapter
# urlpost_adapter = DBAdapters.DBURLPost(url="http://whatismyip.oceanus.ro/server_variables.php", post=False)
# ga.setDBAdapter(urlpost_adapter)
# Do the evolution, with stats dump
# frequency of 10 generations
ga.evolve(freq_stats=10)
# Best individual
#print ga.bestIndividual()
|
josephlewis42/personal_codebase
|
python/OpenCalc/Lib/Code/Functions/OpenCalc.py
|
<gh_stars>1-10
'''
Description Of Module
@Author = <NAME><<EMAIL>>
@Date = 2010-2-24
@License = GPL
==Changelog==
2010-2-24 - First version made by <NAME>
'''
#Import Statements
#Define Constants
#Define Functions
def isNum(var):
if(type(var).__name__ == 'int' or type(var).__name__ == 'float'):
return True
else:
return False
|
josephlewis42/personal_codebase
|
python/markov.py
|
#!/usr/bin/env python3
'''
Provides common functions used through the similarity engines.
Copyright 2012 <NAME> <<EMAIL>> | <<EMAIL>>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2012-10-28 - Initial Work
'''
import random
import pickle
import re
START_WORD = "<START>"
TERMINAL_WORD = "<END>"
def document_to_terms(doc):
'''Parses a document in to a list of strings.'''
doc = doc.lower()
doc = re.sub(r"""[^\w\s]+""", '', doc)
return doc.split()
class TwoGramCorpus():
words = None
def __init__(self, fp=None):
if fp:
self.words = pickle.load(fp)
else:
self.words = {}
def save(self, fp):
pickle.dump(self.words, fp, 1)
def load_file(self, fp):
for sentence in fp.read().split("."):
self.load_line(document_to_terms(sentence))
def load_line(self, line):
if len(line) == 0:
return
line.append(TERMINAL_WORD)
lastword = START_WORD
for word in line:
self.add_2gram(lastword, word)
lastword = word
def add_2gram(self, first, second):
firstlist = None
try:
firstlist = self.words[first]
except KeyError:
self.words[first] = {second : 1}
return
try:
firstlist[second] += 1
except KeyError:
firstlist[second] = 1
def __str__(self):
return str(self.words)
def __unicode__(self):
return str(self.words)
def _random_prob_word(self, start):
''' chooses a random word that follows the given one
with the probability of the frequency it occurs.
'''
rest = self.words[start]
total_possible = sum(rest.values())
chosen = random.randint(1,total_possible)
for word, value in rest.items():
chosen -= value
if chosen <= 0:
return word
return None
def generate_sentence(self):
# choose a random start word.
sentence = []
lastword = self._random_prob_word(START_WORD)
while lastword != TERMINAL_WORD:
sentence.append(lastword)
lastword = self._random_prob_word(lastword)
return " ".join(sentence) + "."
def generate(self, num_sentences):
sentences = []
for i in range(num_sentences):
sentences.append(self.generate_sentence())
return " ".join(sentences)
if __name__ == "__main__":
tgc = TwoGramCorpus()
tgc.load_file(open('/home/joseph/Desktop/books2/pg2.txt'))
print(tgc.generate(3))
|
josephlewis42/personal_codebase
|
wheel_of_fortune_ai/wheelmatch.py
|
<gh_stars>1-10
import re
class WheelMatch:
letters = set(['a','t','e'])
looking = ['a','.','e','.','.','.','a']
def matches(self, word):
if len(word) != len(self.looking):
return False
for i, letter in enumerate(self.looking):
if letter == '.':
if word[i] in self.letters:
return False
else:
if word[i] != letter:
return False
return True
if __name__ == "__main__":
wm = WheelMatch()
wordlist = open('/usr/share/dict/american-english').readlines()
wordlist = [word.strip().lower() for word in wordlist]
for i in range(100):
for word in wordlist:
if wm.matches(word):
print words
|
josephlewis42/personal_codebase
|
Euler/015.py
|
<reponame>josephlewis42/personal_codebase
'''Starting in the top left corner of a 2x2 grid, and only being able to move to
the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20x20 grid?
'''
# there are a total of n * 2 steps you must take where n is length of a side,
# therefore let's say you choose only the down steps, leaving the rest to be
# across:
import pymath
print(pymath.choose(40,20))
|
josephlewis42/personal_codebase
|
python/randall/alife_randall_checkout/randallai/Randall.py
|
<reponame>josephlewis42/personal_codebase
#!/usr/bin/env python
'''
A simple AI mouse named Randall.
Copyright (c) 2011 <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
from AI import *
from AI import world
from AI import body
from AI import limbic
from AI import maslow
from AI import mapper
from AI import logos
import time
class Randall( world.Actor ):
'''Randall is an actor in a world, Actors have basic attributes and systems.
'''
def setup_organs(self):
self.my_body = body.Body()
#Hunger is a good thing...
def hunger_update(old):
return old + 2
stomach = body.Organ("stomach", hunger_update, self.response_network)
self.my_body.append(stomach)
#Thirst!
def thirst_update(old):
return old + 2
thirst = body.Organ("thirst", thirst_update, self.response_network)
self.my_body.append(thirst)
#What goes in must come out.
def bladder_update(old):
old_value = self.my_body["stomach"].last_value
new_value = self.my_body["stomach"].value
return old + ((new_value - old_value) / 2.0)
bladder = body.Organ("bladder", bladder_update, self.response_network)
self.my_body.append(bladder)
#Sleep, deep sleep.
def sleep(old):
return old + .25
s = body.Organ("sleep", sleep, self.response_network)
self.my_body.append(s)
def setup_emotions(self):
self.emotions = limbic.generate_plutchik_limbic(self.response_network)
#TODO fix emotions
def setup_mind(self):
mind = logos.Mind(self.needs, self, autostart=False)
logos.quick_search_and_go(['food', 'water'], mind)
self.mind = mind
def setup_needs(self):
needs = maslow.Heirarchy(maslow.PHYSIOLOGICAL, self.response_network) #Basic needs with updown registers
needs['food'].update_function = self.my_body["stomach"].get_value
needs['water'].update_function = self.my_body["thirst"].get_value
#needs['sleep'].update_function = self.my_body["sleep"].get_value
#needs['excretion'].update_function = self.my_body["bladder"].get_value
#Remove all without update function (reads: that we aren't using).
needs.clean_needs()
self.needs = needs
class map_functions:
def food(self, actor):
actor.my_body["stomach"].value = 0
return "Stomach for %s set to 0" % (actor.name)
def water(self, actor):
actor.my_body["thirst"].value = 0
return "Thirst for %s set to 0" % (actor.name)
def lever(self, actor): #Levers give food.
actor.my_body["stomach"].value = 0
return "Lever pressed: Stomach for %s set to 0" % (actor.name)
def newrandall():
'''Makes a new randall and returns the world he lives in.'''
import sys, os
m = map_functions()
mypath = os.path.abspath( __file__ )
mydirpath = mypath[:mypath.rfind(os.sep)]
#mygridpath = os.path.join(mydirpath, "AI","mazes","totem.map")
mygridpath = os.path.join(mydirpath, "AI","mazes","pavlov.map")
#mygridpath = os.path.join(mydirpath, "AI","mazes","617161.map")
mygrid = mapper.make_from_mapfile(mygridpath)
#mapper.map2HTML(mygridpath)
m = mapper.interface_from_grid(mygrid, m)
w = world.World(mygrid, m, move_time=1)
#world.DEBUGGING = True
r = Randall("Randall", w, 0,0)
w.append(r)
return w
if __name__ == "__main__":
w = newrandall()
try:
print "Press Control + C to quit."
while True:
time.sleep(1)
#j = m.fetch_news()
#if j:
# print j
except KeyboardInterrupt:
w.kill()
|
josephlewis42/personal_codebase
|
python/py_basic_ide/pyBASIC/__init__.py
|
from parser import tokenize_document, tokenize_from_file
from runner import run
def set_debug(bool):
print "DEBUG = ", bool
runner.debug = bool
|
josephlewis42/personal_codebase
|
wheel_of_fortune_ai/ngram.py
|
<reponame>josephlewis42/personal_codebase
#!/usr/bin/env python
import re
ngrams = {}
word_scores = {}
with open("w2_.txt") as ngram:
for line in ngram:
nwords, w1, w2 = line.split()
nwords = int(nwords)
try:
ngrams[w1].append((nwords, w2))
except:
ngrams[w1] = [(nwords, w2)]
start_words = ngrams.keys()
for key in start_words:
ngrams[key] = sorted(ngrams[key], reverse=True)
word_scores[key] = sum([tup[0] for tup in ngrams[key]])
def find_startword(regex):
return sorted([(get_word_score(word), word) for word in start_words if re.match(regex, word) != None], reverse=True)
def find_matches(startword, regex):
try:
return [tup for tup in ngrams[startword] if re.match(regex, tup[1]) != None]
except Exception, e:
print(e)
return []
def get_word_score(word):
try:
return word_scores[word]
except KeyError:
return 1
|
josephlewis42/personal_codebase
|
python/email_grabber/email.pyw
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Wed Mar 24 11:22:54 2010
import wx
# begin wxGlade: extracode
# end wxGlade
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.label_1 = wx.StaticText(self, -1, "URL:")
self.url = wx.TextCtrl(self, -1, "Put a URL Here")
self.input = wx.TextCtrl(self, -1, "OR put text here\n\nEmails will be output Below.", style=wx.TE_MULTILINE)
self.submit = wx.Button(self, -1, "Get From Text")
self.button_3 = wx.Button(self, -1, "Get From URL")
self.button_1 = wx.Button(self, -1, "Clear Text (Above)")
self.button_2 = wx.Button(self, -1, "Clear Emails (Below)")
self.output = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
self.save = wx.Button(self, wx.ID_SAVE, "")
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_BUTTON, self.process_input, self.submit)
self.Bind(wx.EVT_BUTTON, self.process_url, self.button_3)
self.Bind(wx.EVT_BUTTON, self.clear_web, self.button_1)
self.Bind(wx.EVT_BUTTON, self.clear_email, self.button_2)
self.Bind(wx.EVT_BUTTON, self.save_doc, self.save)
# end wxGlade
def __set_properties(self):
# begin wxGlade: MyFrame.__set_properties
self.SetTitle("Email Grabber <joehms22<EMAIL>> - GNU GPL V.3.0")
self.SetSize((640, 480))
# end wxGlade
def __do_layout(self):
# begin wxGlade: MyFrame.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.VERTICAL)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
sizer_4.Add(self.label_1, 0, 0, 0)
sizer_4.Add(self.url, 1, wx.EXPAND, 0)
sizer_2.Add(sizer_4, 0, wx.EXPAND, 0)
sizer_2.Add(self.input, 1, wx.EXPAND, 0)
sizer_3.Add(self.submit, 0, 0, 0)
sizer_3.Add(self.button_3, 0, 0, 0)
sizer_3.Add(self.button_1, 0, 0, 0)
sizer_3.Add(self.button_2, 0, 0, 0)
sizer_2.Add(sizer_3, 0, wx.EXPAND, 0)
sizer_2.Add(self.output, 1, wx.EXPAND, 0)
sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
sizer_1.Add(self.save, 0, 0, 0)
self.SetSizer(sizer_1)
self.Layout()
# end wxGlade
def process_input(self, event): # wxGlade: MyFrame.<event_handler>
import re
email_pattern = re.compile('([\w\-\.]+@(\w[\w\-]+\.)+[\w\-]+)')
# there are several matches per line
for match in email_pattern.findall(self.input.GetValue()):
self.output.AppendText(match[0] + ",\t")
#Clear url and text
self.input.Clear()
self.text_ctrl_1.Clear()
event.Skip()
def clear_web(self, event): # wxGlade: MyFrame.<event_handler>
self.input.Clear()
event.Skip()
def clear_email(self, event): # wxGlade: MyFrame.<event_handler>
self.output.Clear()
event.Skip()
def process_url(self, event): # wxGlade: MyFrame.<event_handler>
from urllib import urlopen
import re
email_pattern = re.compile('([\w\-\.]+@(\w[\w\-]+\.)+[\w\-]+)')
# there are several matches per line
for match in email_pattern.findall(urlopen(
self.url.GetValue()).read()):
self.output.AppendText(match[0] + ", ")
#Clear url and text
self.input.Clear()
self.url.Clear()
event.Skip()
def save_doc(self, event): # wxGlade: MyFrame.<event_handler>
import os
dlg = wx.FileDialog(self, "Save a file", os.getcwd(), "", "Text Files (*.txt)|*.txt|Comma Seperated Value Files (*.csv)|*.csv|All Files|*.*", wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
if dlg.GetFilterIndex() == 0:
path = path+".txt"
if dlg.GetFilterIndex() == 1:
path = path+".csv"
print "Saving at: %s" % (path)
file = open(path, 'w')
file.write(self.output.GetValue())
file.close()
dlg.Destroy()
event.Skip()
# end of class MyFrame
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
|
josephlewis42/personal_codebase
|
python/randall/alife_randall_checkout/randallai/AI/world.py
|
<reponame>josephlewis42/personal_codebase<filename>python/randall/alife_randall_checkout/randallai/AI/world.py<gh_stars>1-10
#!/usr/bin/env python
'''
The world provides a place for actors to interact. All Actors should
have some basic variables (cheifly location and hunger), these can
be accessed by the organs so the animal can "sense" what is going on
around it. Having the variables here also ensures that the Actors
don't know about them, and therefore nothing gets hard coded in to an
animal.
Copyright (c) 2011 <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
import mapper
import copy
import pavlov
import threading
import time
__version__ = 1.0
DEBUGGING = False
class Actor:
'''A simple instance of an actor.'''
image = None #The location of the actor's image.
world = None #The world in which the actor lives.
response_network = None #The condition-response mechanism for this animal
my_body = None #The organ systems for this Actor
emotions = None #The emotion systems for this Actor
internal_map = None #The map this actor has of the world it lives in.
needs = None #The needs of this Actor, maslow.Heirarchy
can_move = False #Set to false when the actor moves, reset by
#the world.
mind = None #logos.Mind controler.
_css_move_history = [] #Stores the css selectors of the past 100 moves.
def __init__(self, name, world, x, y, z=0, seed=100):
'''Initializes the actor.
Arguments:
seed - The seed to set the Actor's decision process to. Default: 100
x - The x location of the Actor in the world. (int)
y - The y location of the Actor in the world. (int)
z - The z location of the Actor in the world. (int) Default: 0
name - A string to be used as the Actor's name. (String)
'''
self.seed = seed
self.name = name
self.world = world
self.x = x
self.y = y
self.z = z
self.setup()
self._css_move_history.append(self.view_terrain().css_id)
def __str__(self):
return "%s At:(%i,%i,%i)" % (self.name, self.x, self.y, self.z)
def view_terrain(self):
'''Acts as a kind of eyes for an actor, returns the cell in the world
where the actor is located.'''
#Never give the actor the original, they might learn to use it to break
#or expand their matrix!
#return copy.deepcopy(self.world.terrain.cell_at(self.x, self.y, self.z))
return self.world.terrain.cell_at(self.x, self.y, self.z)
def move_to_cell(self, cell):
'''Move to the location at the given cell if possible.'''
return self.move_to(cell.x, cell.y, cell.z)
def move_to(self, x, y, z):
'''Moves the actor to the given x, y, z if possible.
Errors Raised:
AssertionError -- The Cell at x,y,z is not accessable from the
current location.
IndexError -- The cell at the supplied x,y,z is beyond the
edge of the world!
RuntimeWarning -- The Actor has moved too recently and is
unable to do it again at this time.
'''
here = self.world.map_grid.cell_at(self.x, self.y, self.z)
try:
there = self.world.map_grid.cell_at(x,y,z)
except IndexError:
raise IndexError("The cell at %i,%i,%i is out of bounds." % (x,y,z))
#Update the actor's current map.
self.internal_map.update_or_add(here)
#Are they touching, and accessable, and the actor can move
#at this time?
if self.world.map_grid.is_touching(here, there):
if self.world.map_grid.is_accessable(here, there):
if self.can_move:
self.x = x
self.y = y
self.z = z
self.can_move = False
if DEBUGGING:
print "%s moving to %s" % (self.name, str(there))
self._css_move_history.append(there.css_id)
if len(self._css_move_history) > 100:
self._css_move_history = self._css_move_history[-100:]
return
else:
raise RuntimeWarning("The actor %s moved too recently." % (self.name))
raise AssertionError("%s can't access cell %s from %s" % (self.name, str(there), str(here)))
def move_north(self):
'''Moves the actor north if possible.'''
self.move_to(self.x, self.y-1, self.z)
def move_south(self):
'''Moves the actor south if possible.'''
self.move_to(self.x, self.y+1, self.z)
def move_west(self):
'''Moves the actor west if possible.'''
self.move_to(self.x-1, self.y, self.z)
def move_east(self):
'''Moves the actor east if possible.'''
self.move_to(self.x+1, self.y, self.z)
def move_up(self):
'''Moves the actor up a floor if possible.'''
self.move_to(self.x, self.y, self.z-1)
def move_down(self):
'''Moves the actor down a floor if possible.'''
self.move_to(self.x, self.y, self.z+1)
def setup_map(self):
'''Override me if needed. Sets up a blank mapper.Map with the same
size as the world map, just filled with Nones. This is the one the
Actor uses in it's brain.
Sets: internal_map'''
self.internal_map = mapper.Grid(self.world.terrain._x,
self.world.terrain._y,
self.world.terrain._z,
name="%s's internal map"%(self.name))
def setup_pavlov(self):
'''Override me if needed. Sets up a blank pavlov.ResponseNetwork and
stores it to the response_network variable. The response_network has
been started.
Sets: response_network
'''
self.response_network = pavlov.ResponseNetwork(autostart=True, update_time=5)
def setup_organs(self):
raise NotImplementedError, "You didn't override the setup_organs function."
def setup_emotions(self):
'''Set up your emotions by overriding this class. At the end set
self.emotions to an instance of limbic.Limbic.'''
raise NotImplementedError, "You didn't override the setup_emotions function."
def setup_mind(self):
'''Set up the mind by overriding this class. At the end set
self.mind to an instance of logos.Mind'''
raise NotImplementedError, "You didn't override the setup_mind function."
def setup_needs(self):
'''Sets up the needs system for this creature, the self.needs should be
an instance of maslow.Heirarchy by the end of this method.'''
raise NotImplementedError, "You didn't override the setup_needs function."
def setup_special(self):
'''Put anything here that you need called at the end of the setup.'''
pass
def setup_threads(self):
'''Starts the threads on all of the classes, if they are allready
started does nothing.'''
if DEBUGGING:
print ('Starting Actor "%s"' % (self.name))
if not self.response_network.is_alive():
if DEBUGGING:
print " -> Response Network"
self.response_network.start()
if not self.my_body.is_alive():
if DEBUGGING:
print " -> Body"
self.my_body.start()
if not self.emotions.is_alive():
if DEBUGGING:
print " -> Emotions"
self.emotions.start()
if not self.mind.is_alive():
if DEBUGGING:
print " -> Mind"
self.mind.start()
if DEBUGGING:
print "[Success]"
def setup(self):
'''Sets up the Actor's basic systems, this in turn calls the setup
functions, after this is run all threads should be started.'''
self.setup_pavlov()
self.setup_map()
self.setup_organs()
self.setup_emotions()
self.setup_needs()
self.setup_mind()
self.setup_special()
self.setup_threads()
def interact(self, item_name):
'''Call with an item in the current cell to interact with it.'''
self.world.item_event_interface.interact(self, item_name)
def kill(self):
'''Kills the actor and its respective threads.'''
if DEBUGGING:
print 'Killing Actor "%s"' % (self.name)
if self.response_network.is_alive():
if DEBUGGING:
print " -> Response Network"
self.response_network.sleep()
if self.my_body.is_alive():
if DEBUGGING:
print " -> Body"
self.my_body.sleep()
if self.emotions.is_alive():
if DEBUGGING:
print " -> Emotions"
self.emotions.sleep()
if self.mind.is_alive():
if DEBUGGING:
print " -> Mind"
self.mind.sleep()
if DEBUGGING:
print "[Success]"
def fetch_move_history(self):
'''Clears and returns the move history for this actor.'''
a = self._css_move_history
self._css_move_history = []
return a
class World (threading.Thread):
'''A simple 3d world for actors to reside in.'''
actors = []
terrain = "Depreciated, use map_grid instead"
map_grid = None
item_event_interface = None
_awake = True
def __init__(self, map_grid, item_event_interface, move_time=1, autostart=True):
'''
Creates the world from a mapfile and class containing
instructions for that mapfile.
Paramaters:
map_grid --
item_event_interface --
move_time -- The amount of time to wait between Actor moves
can be a function or float or int. If it is a
function the function should either wait for a
certain amount of time then return 0 or return
the number of seconds to wait.
Default: 0.1 (Function, float, int)
autostart -- Should the World start as soon as it is
instanciated? If not the Actors will not be able
to move until its thread is started using the
start() function.
Default: True (boolean)
'''
self.terrain = map_grid
self.map_grid = map_grid
self.item_event_interface = item_event_interface
self.move_time = move_time
threading.Thread.__init__(self)
#Start the thread automagically if desired.
if autostart:
self.start()
def __getitem__(self, key):
'''Emulates a list or dictionary, called with the name of
the actor. Raises IndexError if not found.'''
#Check for strings
for e in self.actors:
if e.name == key:
return e
#Check for ints
return self.actors[key]
#else raise error
raise IndexError
def __len__(self):
'''Returns the number of actors.'''
return len(self.actors)
def keys(self):
'''Returns a list of all the names of the actors.'''
k = []
for e in self.actors:
k.append(e.name)
return k
def add_actor(self, actor):
'''Depreciated, use World.append instead'''
self.actors.apend(actor)
raise DeprecationWarning("Use World.append instead of World.add_actor")
def append(self, actor):
'''Appends an actor to the list.'''
self.actors.append(actor)
def run(self):
'''Waits for the amount of time specified by move_time then
resets the Actor's can_move to True allowing their bodies
to move again, that way they don't buzz around the world.'''
#Make sure awake is true before we start lest the developer
#tries to sleep then re-wake the thread for some reason.
self._awake = True
while self._awake:
#Handle update times for functions and numbers.
if hasattr(self.move_time, '__call__'):
ut = float( self.move_time() )
else:
ut = self.move_time
#Wait so we don't hog the CPU. What are we coming to? A
#world where AI doesn't rape your machine?
time.sleep(ut)
for a in self.actors:
a.can_move = True
def sleep(self):
self._awake = False
def kill(self):
'''Kills the world and all actors within.'''
self._awake = False
for a in self.actors:
a.kill()
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex9_g2dlist.py
|
from pyevolve import G2DList
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import Crossovers
from pyevolve import Mutators
# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
score = 0.0
# iterate over the chromosome
for i in xrange(chromosome.getHeight()):
for j in xrange(chromosome.getWidth()):
# You can use the chromosome.getItem(i, j) too
if chromosome[i][j]==0:
score += 0.1
return score
def run_main():
# Genome instance
genome = G2DList.G2DList(8, 5)
genome.setParams(rangemin=0, rangemax=100)
# The evaluator function (objective function)
genome.evaluator.set(eval_func)
genome.crossover.set(Crossovers.G2DListCrossoverSingleHPoint)
genome.mutator.set(Mutators.G2DListMutatorIntegerRange)
# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.setGenerations(800)
# Do the evolution, with stats dump
# frequency of 10 generations
ga.evolve(freq_stats=100)
# Best individual
print ga.bestIndividual()
if __name__ == "__main__":
run_main()
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex13_sphere.py
|
from pyevolve import G1DList
from pyevolve import Mutators, Initializators
from pyevolve import GSimpleGA, Consts
# This is the Sphere Function
def sphere(xlist):
total = 0
for i in xlist:
total += i**2
return total
def run_main():
genome = G1DList.G1DList(140)
genome.setParams(rangemin=-5.12, rangemax=5.13)
genome.initializator.set(Initializators.G1DListInitializatorReal)
genome.mutator.set(Mutators.G1DListMutatorRealGaussian)
genome.evaluator.set(sphere)
ga = GSimpleGA.GSimpleGA(genome, seed=666)
ga.setMinimax(Consts.minimaxType["minimize"])
ga.setGenerations(1500)
ga.setMutationRate(0.01)
ga.evolve(freq_stats=500)
best = ga.bestIndividual()
if __name__ == "__main__":
run_main()
|
josephlewis42/personal_codebase
|
Euler/006.py
|
<gh_stars>1-10
#!/usr/bin/env python
'''
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
'''
import pymath
print pymath.square_of_sum(range(1,101)) - pymath.sum_of_squares(range(1,101))
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex22_monkey.py
|
#===============================================================================
# Pyevolve version of the Infinite Monkey Theorem
# See: http://en.wikipedia.org/wiki/Infinite_monkey_theorem
# By <NAME>
#===============================================================================
from pyevolve import G1DList
from pyevolve import GSimpleGA, Consts
from pyevolve import Selectors
from pyevolve import Initializators, Mutators, Crossovers
import math
sentence = """
'Just living is not enough,' said the butterfly,
'one must have sunshine, freedom, and a little flower.'
"""
numeric_sentence = map(ord, sentence)
def evolve_callback(ga_engine):
generation = ga_engine.getCurrentGeneration()
if generation%50==0:
indiv = ga_engine.bestIndividual()
print ''.join(map(chr,indiv))
return False
def run_main():
genome = G1DList.G1DList(len(sentence))
genome.setParams(rangemin=min(numeric_sentence),
rangemax=max(numeric_sentence),
bestrawscore=0.00,
gauss_mu=1, gauss_sigma=4)
genome.initializator.set(Initializators.G1DListInitializatorInteger)
genome.mutator.set(Mutators.G1DListMutatorIntegerGaussian)
genome.evaluator.set(lambda genome: sum(
[abs(a-b) for a, b in zip(genome, numeric_sentence)]
))
ga = GSimpleGA.GSimpleGA(genome)
#ga.stepCallback.set(evolve_callback)
ga.setMinimax(Consts.minimaxType["minimize"])
ga.terminationCriteria.set(GSimpleGA.RawScoreCriteria)
ga.setPopulationSize(60)
ga.setMutationRate(0.02)
ga.setCrossoverRate(0.9)
ga.setGenerations(5000)
ga.evolve(freq_stats=100)
best = ga.bestIndividual()
print "Best individual score: %.2f" % (best.score,)
print ''.join(map(chr, best))
if __name__ == "__main__":
run_main()
|
josephlewis42/personal_codebase
|
wheel_of_fortune_ai/wheel.py
|
#!/usr/bin/env python
from __future__ import division
import common
import re
import ngram
# sort in to lengths
words = []
puzzle = []
guessed_letters = []
fullpuzzle = None
def setupPuzzle():
global puzzle
global guessed_letters
global fullpuzzle
print "To play, enter a full puzzle in lower case."
print "The computer will output its best guesses for the puzzle."
print "After that, input a letter, and the computer will guess again."
tmp = raw_input("Enter Puzzle: ")
if tmp == '':
exit()
fullpuzzle = None
try:
puzzle = [['.' for j in range(int(i))] for i in tmp.split()]
guessed_letters = []
except ValueError:
puzzle = tmp.lower()
fullpuzzle = tmp
puzzle = [['.' for j in range(len(i))] for i in tmp.split()]
def format_output(grams):
grams = sorted(grams, reverse=True)
return ["%s (%s)" % (tup[1], tup[0]) for tup in grams]
def guess_ngram(location = 0, last=None,allstart=False):
grams = []
if len(guessed_letters) != 0:
non_letters = "[^%s]" % ("".join(guessed_letters))
else:
non_letters = "."
regex = ("^%s$" % ("".join(puzzle[location]))).replace(".",non_letters)
if location == 0:
words = ngram.find_startword(regex)
if len(puzzle) == 1:
return format_output(words)
if not allstart:
words = words[:10]
else:
words = words[:50]
else:
words = ngram.find_matches(last, regex)[:5]
mult = 1
if words == []:
words = ngram.find_startword(regex)[:5]
mult = .5
if location == len(puzzle) - 1:
return words
for val, word in words:
for tup in guess_ngram(location + 1, word)[:5]:
grams.append(((tup[0] + val) * mult, word + " " + tup[1]))
if location != 0:
return grams
if len(grams) == 0:
return guess_ngram(0,None,0,True)
return format_output(grams)
def find_matching_words(location):
wordlist = set()
regex = "^%s$" % ("".join(puzzle[location]))
desired_length = len(puzzle[location])
for word in words:
if(len(word) == desired_length):
if(re.match(regex, word)):
wordlist.add(word)
return wordlist
def output_puzzle():
print("Puzzle: %s" % (" ".join(["".join(puz) for puz in puzzle]),))
if fullpuzzle != None:
print(" (%s)" % (fullpuzzle,))
def update_puzzle():
global puzzle
if fullpuzzle == None:
try:
update = raw_input("Update puzzle <letter> [wordnum,loc ...] (blank to end): ").split()
letter = update[0][0]
for pos in update[1:]:
wordnum, loc = map(int, pos.split(","))
puzzle[wordnum - 1][loc - 1] = letter
guessed_letters.append(letter)
return False
except IndexError:
return True
else:
letter = 'blank'
while len(letter) > 1:
letter = raw_input("Update puzzle <letter> (blank to end): ")
if letter == '':
return True
guessed_letters.append(letter)
count = 0
for word in puzzle:
for pos in range(len(word)):
if fullpuzzle[count] == letter:
word[pos] = letter
count += 1
count += 1 # manage spaces
return False
if __name__ == "__main__":
while(True):
setupPuzzle()
puzzle_done = False
while(not puzzle_done):
print("\n".join(guess_ngram()[:10]))
puzzle_done = update_puzzle()
output_puzzle()
|
josephlewis42/personal_codebase
|
python/webkit_browser/simple_webkit_browser.py
|
#!/usr/bin/env python
'''
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of the nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright 2010 <NAME> <<EMAIL>>
'''
import gtk
import webkit
#Constants
BROWSER_NAME = "Simple Browser"
class MyWebBrowser(gtk.Window):
def __init__(self):
#Init the program, essentially just create the gtk environment.
#Create the vbox to hold the menubar and gtkwindow
self.vbox = gtk.VBox(False, 2)
self.view = webkit.WebView()
self.view.open("http://localhost/")
self.view.connect('title-changed', self.update_title_bar)
self.view.connect('document-load-finished', self.doc_load_finished)
self.sw = gtk.ScrolledWindow()
self.sw.add(self.view)
self.make_menu_bar()
self.win = gtk.Window()
self.win.set_size_request(760, 500)
self.vbox.pack_end(self.sw)
self.win.add(self.vbox)
self.win.show_all()
self.win.connect('delete_event', gtk.main_quit)
def make_menu_bar(self):
'''Makes the menu bar for the program, pretty simple really.'''
#Make the hbox to fit everything in.
self.menu_box = gtk.HBox(False, 5)
#Make the back button and set it up.
self.back_button = gtk.Button(stock=gtk.STOCK_GO_BACK)
self.menu_box.pack_start(self.back_button, False, False, 0)
self.back_button.connect("pressed",self.page_back)
#Make the forward button and set it up.
self.forward_button = gtk.Button(stock=gtk.STOCK_GO_FORWARD)
self.menu_box.pack_start(self.forward_button, False, False, 0)
self.forward_button.connect("pressed",self.page_forward)
#The Refresh button
#The home button
#The url entry box
self.url_entry = gtk.Entry()
self.menu_box.pack_start(self.url_entry, True, True, 0)
#The go button
self.go_button = gtk.Button("Go")
self.menu_box.pack_start(self.go_button, False, False, 0)
self.go_button.connect("pressed",self.go_to_url)
self.vbox.pack_start(self.menu_box, False, False, 0)
def go_to_url(self, event):
'''Goes to the url provided in the input box.'''
self.view.open(self.url_entry.get_text())
def update_title_bar(self, webview, frame, title):
'''Updates the title bar when a webpage title is changed.'''
self.win.set_title(title)
def doc_load_finished(self, webview, unknown):
'''Changes browser settings when a url is loaded, like location bar, and
title.'''
#Set the title for the page
self.win.set_title(BROWSER_NAME + " - " + str(self.view.get_property("title")))
#Set the new uri
self.url_entry.set_text( self.view.get_property("uri") )
def page_back(self, event):
'''Go back a page.'''
self.view.go_back()
def page_forward(self, event):
'''Go forward a page.'''
self.view.go_forward()
if __name__ == "__main__":
webbrowser = MyWebBrowser()
gtk.main()
|
josephlewis42/personal_codebase
|
python/PersonalFileServer/Site/upload.py
|
import os
if POST_DICT:
try:
print POST_DICT.keys()
print POST_DICT['filename']
path = os.path.join("Downloads", POST_DICT['filename'])
print path
with open(path, 'wb') as f:
f.write(POST_DICT['myfile'])
except Exception, e:
print e
self.redirect("index.py")
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex19_gp.py
|
from pyevolve import GSimpleGA
from pyevolve import GTree
from pyevolve import Consts
from pyevolve import Selectors
from pyevolve import Mutators
from math import sqrt
import pydot
import random
def gp_add(a, b):
assert len(a)==len(b)
new_list = [x+y for x,y in zip(a,b)]
return new_list
#def gp_sub(a, b):
# assert len(a)==len(b)
# new_list = [x-y for x,y in zip(a,b)]
# return new_list
def prot_div(a, b):
if b==0:
return b
else:
return a/b
#def gp_div(a,b):
# assert len(a)==len(b)
# new_list = [prot_div(x,float(y)) for x,y in zip(a,b)]
# return new_list
def gp_mul(a,b):
assert len(a)==len(b)
new_list = [x*y for x,y in zip(a,b)]
return new_list
def random_lists(size):
list_a = [random.randint(1,20) for i in xrange(size)]
list_b = [random.randint(1,20) for i in xrange(size)]
return (list_a, list_b)
def eval_func(chromosome):
sz = 20
code_comp = chromosome.getCompiledCode()
square_accum = 0.0
for j in xrange(sz):
a, b = random_lists(5)
target_list = gp_add(gp_mul(a,b),gp_mul(a,b))
ret_list = eval(code_comp)
square_accum += (sum(target_list)-sum(ret_list))**2
RMSE = sqrt(square_accum / float(sz))
score = (1.0 / (RMSE+1.0))
return score
def main_run():
genome = GTree.GTreeGP()
root = GTree.GTreeNodeGP('a', Consts.nodeType["TERMINAL"])
genome.setRoot(root)
genome.setParams(max_depth=2, method="ramped")
genome.evaluator += eval_func
genome.mutator.set(Mutators.GTreeGPMutatorSubtree)
ga = GSimpleGA.GSimpleGA(genome)
ga.setParams(gp_terminals = ['a', 'b'],
gp_function_prefix = "gp")
ga.setMinimax(Consts.minimaxType["maximize"])
ga.setGenerations(500)
ga.setCrossoverRate(1.0)
ga.setMutationRate(0.08)
ga.setPopulationSize(80)
ga(freq_stats=1)
print ga.bestIndividual()
graph = pydot.Dot()
ga.bestIndividual().writeDotGraph(graph)
graph.write_jpeg('tree.png', prog='dot')
if __name__ == "__main__":
main_run()
#import hotshot, hotshot.stats
#prof = hotshot.Profile("ev.prof")
#prof.runcall(main_run)
#prof.close()
#stats = hotshot.stats.load("ev.prof")
#stats.strip_dirs()
#stats.sort_stats('time', 'calls')
#stats.print_stats(20)
|
josephlewis42/personal_codebase
|
python/pyWebserver/configure.py
|
"""
This application starts the webserver.
@Author : <NAME> <<EMAIL>>
@Licence : Apache License
@Date : Fri 12 Feb 2010 05:00:22 PM MST
"""
#WX Stuff
import wx
from wx import xrc
#Config Parser, not needed in normal wx applications.
import ConfigParser
config = ConfigParser.RawConfigParser()
class ServerApp(wx.App):
'''
The server app creates a class that wx can use to interact with the items
in the application.
'''
def OnInit(self):
'''
Called by wx to start the applet.
'''
#The location of the configuration file
self.res = xrc.XmlResource("./Lib/configure_gui.xrc")
#Init the frame and the items within
self.InitFrame()
#Init the buttons and bind them
self.InitButtons()
#Start up the sizer, and show the frame
self.InitEverythingElse()
return True
def InitFrame(self):
'''
Sets the variables of the main frame, and the controls
'''
#Init frame
self.frame = self.res.LoadFrame(None, "MainFrame")
#Init the main panel
self.panel = xrc.XRCCTRL(self.frame, "MainPanel")
#Init Input Boxes
self.portControl = xrc.XRCCTRL(self.panel, "port_ctrl")
self.hostControl = xrc.XRCCTRL(self.panel, "host_ctrl")
self.rootControl = xrc.XRCCTRL(self.panel, "root_ctrl")
self.errorsControl = xrc.XRCCTRL(self.panel, "errors_ctrl")
self.indexControl = xrc.XRCCTRL(self.panel, "index_ctrl")
self._404Control = xrc.XRCCTRL(self.panel, "_404_ctrl")
def InitButtons(self):
'''
Bind the user controllable items.
'''
self.frame.Bind(wx.EVT_BUTTON, self.StartServer, id=xrc.XRCID("StartServerButton"))
def InitEverythingElse(self):
'''
Adds a sizer, and shows the panel
'''
sizer = self.panel.GetSizer()
sizer.Fit(self.frame)
sizer.SetSizeHints(self.frame)
self.frame.Show()
def StartServer(self, evt):
'''
Write the config file, then start the server.
'''
#Set Variables
config.add_section('Pages')
config.set('Pages', 'error_dir', self.errorsControl.GetValue())
config.set('Pages', '_404', self._404Control.GetValue())
config.set('Pages', 'siteroot', self.rootControl.GetValue())
config.set('Pages', 'index', self.indexControl.GetValue())
config.add_section('Server')
config.set('Server', 'port', self.portControl.GetValue())
config.set('Server', 'host_name', self.hostControl.GetValue())
# Write the configuration file to 'configure.cfg'
with open('./Configuration/configure.cfg', 'wb') as configfile:
config.write(configfile)
#Start the webserver in a new process (fork)
import os
pid = os.fork()
if pid:
import webserver
webserver.main()
else:
#Start a browser for the user to see their work.
import webbrowser
webbrowser.open("http://"+ str(self.hostControl.GetValue())+":"+str(self.portControl.GetValue()))
def main():
app = ServerApp(0)
app.MainLoop()
if __name__ == '__main__':
main()
|
josephlewis42/personal_codebase
|
python/PersonalFileServer/Site/download.py
|
import os
import mimetypes
import urllib
if QUERY_DICT:
filename = urllib.unquote(QUERY_DICT['f'][0])
mime = mimetypes.guess_type(filename)
path = os.path.join("Downloads", filename)
head={'Content-Disposition':'attachment; filename="%s"' %(filename)}
self.send_200(mime_type=mime, headers=head)
with open(path) as f:
self.wfile.write(f.read())
else:
self.redirect("index.py")
|
josephlewis42/personal_codebase
|
python/advanced_find_replace/replace_over.py
|
<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: latin-1 -*-
'''A handy little script that replaces files in a directory with
Copyright 2011 <NAME> <joehms22 [at] gmail com>
Originally Made: 2012-06-12
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Potential improvements:
Allow the regex rules to also be applied only to documents with a certain structure.
Allow rules to only be done once/based upon expressions
Allow the choice of files by either entering one, or a list
'''
import os, os.path
import difflib
import webbrowser
import re
import string
import argparse
import json
import codecs
__author__ = "<NAME>"
__copyright__ = "Copyright 2012, <NAME>"
__license__ = "BSD"
# {string_doc_must_contain_to_do_replacement : {orig_text : replacement}
rep_rules = {}
# {string_line_must_contain_to_do_replacement : {orig_text : replacement}
line_rep_rules = {}
regx_rules = {}
changed_files = []
doc_vars = []
universal_diff = ""
# CLI vars
verbose = True
accept_all = False
show_summary = True
print_diff = False
def print_verbose(to_print):
if verbose:
print to_print
def do_diff(name_a, name_b, str_a, str_b):
''' Create a diff of the given two strings, seperated based on
the character provided. Returns True if the revision was accepted,
false otherwise.
'''
global universal_diff
if print_diff:
for line in difflib.unified_diff(str_a.split('\n'), str_b.split('\n'), name_a, name_a):
universal_diff += line + "\n"
return True
if accept_all:
return True
with codecs.open("/tmp/difflib.tmp.html",'w', encoding='utf-8') as dlt:
dlt.write(difflib.HtmlDiff().make_file(str_a.split("\n"),str_b.split("\n"),name_a,name_b))
webbrowser.open("file:///tmp/difflib.tmp.html")
j = raw_input("Keep current? (Y|N) ")
if len(j) > 0 and j.upper()[0] == 'Y':
return True
return False
check_file_prepped = False
def check_file(f, name):
'''Checks the file for lines and replaces them.
'''
document_variables = {}
orig_doc = f.read()
changed_doc = orig_doc
# Find variables for the document
for match in doc_vars:
tmp = re.finditer(match, changed_doc)
for t in tmp:
document_variables.update(t.groupdict())
break
if document_variables:
print_verbose("Found vars: %s" % str(document_variables))
# Simple replacement
for check, replace_dict in rep_rules.items():
if not check in orig_doc:
continue
for to_replace, replace_with in replace_dict.items():
changed_doc = changed_doc.replace(to_replace, replace_with)
# Regex dict replacement. e.g.
# Orig: " print "Hello: " + itema.firstname
# print "From: " + itemb.fistname
# torep: "(?P<itemname>\w+).firstname"
# repwith: "${itemname}.lastname"
# new: " print "Hello: " + itema.lastname
# print "From: " + itemb.lastname"
for to_replace, replace_with in regx_rules.items():
try:
to_replace = to_replace % document_variables
for match in re.finditer(to_replace, changed_doc):
temp_dict = match.groupdict()
temp_dict.update(document_variables)
changed_doc = changed_doc.replace(match.group(), replace_with % temp_dict)
except KeyError:
continue
except Exception, ex:
print str(ex)
print to_replace
# Simple replacement (lines)
for check, replace_dict in line_rep_rules.items():
tmpdoc = []
for line in changed_doc.split("\n"):
if not check in line:
tmpdoc.append(line)
continue
for to_replace, replace_with in replace_dict.items():
line = line.replace(to_replace, replace_with)
tmpdoc.append(line)
changed_doc = "\n".join(tmpdoc)
if orig_doc != changed_doc:
if do_diff(name, "Changed Version", orig_doc, changed_doc):
return changed_doc
return None
def summarize():
''' Shows a summary of the changed documents.'''
if print_diff:
print "== Diff =="
print universal_diff
return
if not show_summary:
return
print "== Summary of Changed Files =="
for tmp in changed_files:
print "\t%s" % (tmp)
def save_file(location, content):
''' Saves a file to the given location with the given content and updates
the list of changed files.
'''
with codecs.open(location, 'w', encoding='utf-8') as curr_file:
curr_file.write(content)
changed_files.append(location)
def check_diff_dirs(dir_to_check):
for root, dirs, files in os.walk(dir_to_check):
for f in files:
fullpath = os.path.join(root, f)
print "Checking: " + fullpath
ret = None
try:
with codecs.open(fullpath, encoding='utf-8') as curr_file:
ret = check_file(curr_file, fullpath)
if ret and not print_diff:
save_file(fullpath, ret)
except UnicodeDecodeError, ex:
print fullpath
print ex
continue
summarize()
def validate_regex(regex):
'''Validates a regex, if valid return true, else false.
'''
try:
re.compile(regex)
return True
except Exception, ex:
print "Error in your REGEX: %s \n\t%s" % (regex, ex)
return False
def load_expressions(path_to_file):
''' The replacement filter file is in a JSON format:
[file_version, rep_rules, regex_rules]
file_version = 2.0
rep_rules = {string_doc_must_contain_to_do_replacement : {orig_text : replacement, ...}, ...}
regex_rules = {orig_text : replacement, ...}
e.g. A file looking like:
{
"version":2.0,
"replace":{"":{"Hello":"Hola"}},
"regex":{"(?P<greeting>\\w+), world!":"%(greeting)s, Joseph!"},
"variables":["Hello, (?P<OrigName>\\w+)"],
"lines":{"linecontains":{"toreplace":"replacewith"}}
}
Would produce:
Hello, world! --> Hola, Joseph!
Note: You may use variables in the regex output, and regex inputs, and replace
input strings by including them using string vars: %(varname)s, any var not
found will be left.
'''
global rep_rules
global line_rep_rules
global regx_rules
global doc_vars
is_valid_regex = True
try:
with codecs.open(path_to_file, encoding='utf-8') as f:
tmp_array = json.load(f)
file_version = tmp_array['version']
rep_rules = tmp_array['replace']
regx_rules = tmp_array['regex']
doc_vars = tmp_array['variables']
if float(file_version) >= 2.0:
line_rep_rules = tmp_array['lines']
else:
print "Using a 1.0 document, 2.0 is suggested."
line_rep_rules = {}
for k in regx_rules.keys():
ret = validate_regex(k)
if not ret:
is_valid_regex = False
for k in doc_vars:
ret = validate_regex(k)
if not ret:
is_valid_regex = False
if not is_valid_regex:
print "Cannot continue with invalid regex(s)"
exit(2)
print_verbose( "== Regex Rules ==")
for k, v in regx_rules.items():
print_verbose("\t %s -> %s" % (k,v))
print_verbose("== Variables ==")
for k in doc_vars:
print_verbose("\t %s" % k)
for big_k, big_d in rep_rules.items():
print_verbose("==Rules for files containing: '%s'==" % (big_k))
for k, v in big_d.items():
print_verbose("\t %s -> %s" % (k,v))
for big_k, big_d in line_rep_rules.items():
print_verbose("==Rules for lines containing: '%s'==" % (big_k))
for k, v in big_d.items():
print_verbose("\t %s -> %s" % (k,v))
except Exception, ex:
print "Your JSON is not properly formatted: %s" % (ex)
exit(2)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Replaces text in files based upon complex regexs',
epilog=load_expressions.__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-q', '--quiet', help="Turns off verbose debugging", action='store_true', default=False)
parser.add_argument('-a', '--accept', help="Automatically accept ALL file changes without showing them", action='store_true', default=False)
parser.add_argument('-d', '--diff_only', help="Does not change files, rather creates a universal diff and prints it to stdout (implies -a)",action='store_true', default=False)
parser.add_argument('--no_summary', help="Do not show a summary of the changed files.", action='store_false', default=True)
parser.add_argument('PATH', help='the path of the directory to parse files in')
parser.add_argument('REPLACE_PATH', help='the path of the replacement fiter')
args = parser.parse_args()
try:
verbose = not args.quiet
accept_all = args.accept
show_summary = args.no_summary
print_diff = args.diff_only
if args.PATH and args.REPLACE_PATH:
load_expressions(args.REPLACE_PATH)
check_diff_dirs(args.PATH)
except IOError:
print "File given can't be found."
|
josephlewis42/personal_codebase
|
python/OpenCalc/Lib/Code/Graph.py
|
#!/usr/bin/python
'''
Graph provides an interface to matplotlib, as well as classes defining graph
objects, and function objects
@Author = <NAME>
@Date = 2010-03-12
@License = GPL
==Changelog==
2010-03-12 - Original Built by <NAME> <<EMAIL>>
2010-03-17 - Added functions to get the graph colors and style - JL
'''
#from pylib import *
import numpy
import Parser
import matplotlib.numerix as nx #Depreciated TODO fix
import matplotlib.patches #Fixes momentarily the Depreciation?
xmin = -10
xmax = 10
x_increment = 0.01
ymin = -10
ymax = 10
zmin = -10
zmax = 10
def get_x_range(lower,upper,by):
'''
Returns a range from lower, to upper, by incriment.
'''
return nx.arange(lower,upper,by)
class function():
'''
Defines a function object, this object holds a function to be plotted
'''
function_name = ""
function_value = ""
previous_fx_value = ""
will_graph = False
line_color = "Blue"
line_style = "Solid Line"
x_values = ()
y_values = []
def __init__(self, value, name):
self.function_value = value
self.function_name = name
def get_descriptor(self):
'''
Returns a string description of the plot
'''
desc = self.function_name + " " +self.function_value
if self.will_graph:
desc = desc + " " + "ON"
else:
desc = desc + " " + "OFF"
return desc
def update_function(self, arr):
'''
Creates a set of Y values from the x values in the array only if the
current set will not work for some reason
'''
if tuple(arr) != self.x_values or self.previous_fx_value != self.function_value:
#Update the conditions that made this switch work so it wont again
#if next time the f(x) is the same.
self.x_values = tuple(arr)
self.previous_fx_value = self.function_value
self.y_values = []
for x in arr:
self.y_values.append(Parser.clean_parse(self.function_value, x))
def get_color(self):
'''
Get the matplotlib equivilent of a color word that is input.
'''
color_values = {
"Blue": "b",
"Cyan": "c",
"Green":"g",
"Black":"k",
"Magenta":"m",
"Yellow": "y",
"Red": "r",
"White": "w",
}
return color_values.get(self.line_color, 'b') #Default = blue
def get_line_style(self):
'''
Get the matplotlib equivilent of a style word that is input.
'''
line_values = {
"Solid Line":'-',
"Dashed Line":'--',
"Dashed - Dot Line":"-.",
"Dotted Line":":",
}
return line_values.get(self.line_style, '-') #Default = solid
def get_function_titles():
'''
Returns a list of function descriptors
'''
global function_list
titles = []
for fx in function_list:
titles.append(fx.get_descriptor())
return titles
def get_on_functions():
'''
Returns a list of lists, the first value is x, the next is y, the third is
the title of the plot.
'''
on_functions = []
for fx in function_list:
if fx.will_graph:
on_functions.append(fx)
return on_functions
function_list = [function('sin(x)', 'Y1'), function('', 'Y2'), function('', 'Y3'),
function('', 'Y4'),function('', 'Y5'),function('', 'Y6'),
function('', 'Y7'),function('', 'Y8'),function('', 'Y9'),
function('', 'Y0')] #The default functions
#Test
xmin = -180
xmax = 180
function_list[0].will_graph = True
|
josephlewis42/personal_codebase
|
python/randall/alife_randall_checkout/randallai/AI/limbic.py
|
<filename>python/randall/alife_randall_checkout/randallai/AI/limbic.py
#!/usr/bin/env python
'''
The limbic module is responsible for maintaining emotions.
Copyright (c) 2011 <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
import threading
import time
import pavlov
__version__ = 1.0
__author__ = "<NAME> <<EMAIL>>"
def generate_plutchik_limbic(response_network):
'''Returns a basic Limbic emotion system, in which emotions are
(somewhat) tied together. The emotions that begin with a > are
dependant upon the two next to it and will contain the average of
those two values.
Based off Plutchik's Wheel of Emotions
http://www.storiedmind.com/wp-content/uploads/2009/09/Wheel-of-Emotions2-441x450.jpg
joy
> love
trust
> submission
fear
> awe
surprise
> disapproval
sadness
> remorse
disgust
> contempt
anger
> aggressiveness
anticipation
> optimism
joy
Paramaters:
response_network -- An implementation of the pavlov.ResponseNetwork
class. (pavlov.ResponseNetwork)
'''
def average_emotion(emotion_one, emotion_two):
def average():
return (emotion_one.value + emotion_two.value) / 2
return average
l = Limbic()
#Primary emotions
l.emotions.append( Emotion("joy", response_network) )
l.emotions.append( Emotion("trust", response_network) )
l.emotions.append( Emotion("fear", response_network) )
l.emotions.append( Emotion("surprise", response_network) )
l.emotions.append( Emotion("sadness", response_network) )
l.emotions.append( Emotion("disgust", response_network) )
l.emotions.append( Emotion("anger", response_network) )
l.emotions.append( Emotion("anticipation", response_network) )
#Secondary emotions
tmp = average_emotion(l['joy'], l['trust'])
l.emotions.append( Emotion("love", response_network, tmp) )
tmp = average_emotion(l['trust'], l['fear'])
l.emotions.append( Emotion("submission", response_network, tmp) )
tmp = average_emotion(l['fear'], l['surprise'])
l.emotions.append( Emotion("awe", response_network, tmp) )
tmp = average_emotion(l['surprise'], l['sadness'])
l.emotions.append( Emotion("disapproval", response_network, tmp) )
tmp = average_emotion(l['sadness'], l['disgust'])
l.emotions.append( Emotion("remorse", response_network, tmp) )
tmp = average_emotion(l['disgust'], l['anger'])
l.emotions.append( Emotion("contempt", response_network, tmp) )
tmp = average_emotion(l['anger'], l['anticipation'])
l.emotions.append( Emotion("aggressiveness", response_network, tmp) )
tmp = average_emotion(l['anticipation'], l['joy'])
l.emotions.append( Emotion("optimism", response_network, tmp) )
return l
class Emotion():
'''
The emotion class represents an emotion in a creature, for example
happiness, it's value is between 0 and 100 and is raised or lowered
through calls.
This class can trigger events when the value reaches certain levels.
These levels must be added to the dictionary "events" with the key
being the condition sent to the pavlov.ResponseNetwork class
supplied and value being a tuple of size 2 .
For example:
"hello":(2,20)
Would trigger the event "hello" when this particular emotion was
between (and including) 2 and 20.
Alternatively you could use the add_event function.
'''
updown = None
last_value = 0
value = 0
events = {}
name = "Defined at init"
def __init__(self, name, response_network, update_function=None, updown=True):
''' Initializes the Emotion.
Paramaters:
name -- The name of the emotion for identification and warning
purposes. (String)
response_network -- An implementation of the pavlov.ResponseNetwork
class. (pavlov.ResponseNetwork)
update_function -- The function called when the emotion needs
it's value updated, should return a number
between 0 and 100 inclusive. The function
will be passed the current value if possible.
You don't need to supply this. DEFAULT:None
(Function)
updown -- A boolean, if true the conditions <emotionname>_up
and <emotionname>_down will be created, when the
emotion value is raised <emotionname>_up will be fired
and the opposite for lowering. (boolean) Default: True
Raises:
TypeError "ERROR: Wrong type of pavlov.ResponseNetwork class", this
happens if the pavlov.ResponseNetwork class is not an instance
of pavlov.ResponseNetwork.
'''
self.name = name
self.update_function = update_function
if isinstance(response_network, pavlov.ResponseNetwork):
self.response_network = response_network
else:
raise TypeError, "ERROR: Wrong type of pavlov.ResponseNetwork class"
#Do the updown setup.
if updown:
response_network.register_con_res("%s_up"%name)
response_network.register_con_res("%s_down"%name)
self.updown = updown
def add_event(self, low, high, event_name):
'''A convenience function for adding events to the emotion.
Paramaters:
low -- The low number to trigger the event.
high -- The high number to stop triggering the event at.
event_name -- The event sent to the pavlov.ResponseNetwork class.
'''
self.events[event_name] = (low, high)
def update(self):
'''Updates the value if a function was given at init, after that
sends events to the ResponseNetwork by calling send_events().
Returns the updated value.
'''
self.last_value = self.value
if hasattr(self.update_function, '__call__'):
try:
self.value = self.update_function(self.value)
except TypeError:
self.value = self.update_function()
self.send_events()
return self.value
def send_events(self):
'''Sends events for values set in the events dictionary by the
user.
This class can trigger events when the value reaches certain levels.
These levels must be added to the dictionary "events" with the key
being the condition sent to the pavlov.ResponseNetwork class
supplied and value being a tuple of size 2 .
For example:
"hello":(2,20)
Would trigger the event "hello" when this particular emotion was
between (and including) 2 and 20.
Alternatively you could use the add_event function.
NOTE:
This function is called periodically by the Limbic class, it
does not need to be done manually unless desired.
NOTE:
This function is used for ensuring the value is really between
0 and 100, if less than or greater than the value will be set to
0 or 100.
'''
global value
if self.value < 0:
self.value = 0
if self.value > 100:
self.value = 100
#Register raise and lowering of emotions.
if self.updown:
if self.value > self.last_value:
self.response_network.condition("%s_up"%self.name)
elif self.value < self.last_value:
self.response_network.condition("%s_down"%self.name)
#Register percentages.
for cond in self.events.keys():
low, high = self.events[cond]
if self.value in range(low, high + 1):
self.response_network.condition(cond)
def autogen_events(self, step=10, start=0, stop=101):
'''
Autogenerates events for ranges starting at start ending at stop
every stop numbers and adds them to the response_network neuron
list. Returns a list of these events.
Example:
>>> autogen_events(10, 20, 50)
['name_20','name_30','name_40']
Where name is the name of this emotion.
Event name_20 would be triggered from 20-29, name_30 30-49 and
name_40 from 40-49.
'''
new_events = range(start, stop, step)
#Add the maximum so we can get to the stop.
new_events.append(stop)
newnames = []
x = 0
while x < len(new_events) - 1:
#Generate the name of this event.
e_name = "%s_%d" % (self.name, new_events[x])
newnames.append(e_name)
#Generate new neurons
self.response_network.register_con_res(e_name)
#Generate it locally, subtract from the high so there aren't
#conflicts in ranges.
self.add_event(new_events[x], new_events[x+1] - 1, e_name)
x += 1
return newnames
def get_value(self):
'''A getter that is used by any function that needs a dynamic way
to get the value. (I'm looking at you maslow!)
'''
return self.value
class Limbic(threading.Thread):
'''A simple container for Emotions.
To add emotions, just append them to the variable "emotions".
The Limbic class can get emotions just like a dictionary:
<Limbic>[emotionname] will return the emotion whose name is that
supplied.
'''
emotions = []
_update_time = None
_awake = True #True if thread is running, false to kill it.
def __init__(self, update_time=1, begin=True):
'''Sets up the emotional system.
Paramaters:
update_time -- A function that returns a float as the number of
seconds until the organs update and fire events,
or just a float. | DEFAULT:1 | (function, float)
begin -- Whether or not to start the thred as soon as done
initializing. If false, the thread won't ever trigger
events or check for value correctness unless you
manually start it by calling start()
DEFAULT: True (boolean)
'''
self._update_time = update_time
threading.Thread.__init__ ( self )
if begin:
self.start()
def __getitem__(self, key):
'''Emulates a list or dictionary, called with the name of
the emotion. Raises IndexError if not found.'''
#Check for strings
for e in self.emotions:
if e.name == key:
return e
#Check for ints
return self.emotions[key]
#else raise error
raise IndexError
def __len__(self):
'''Returns the number of emotions.'''
return len(self.emotions)
def keys(self):
'''Returns a list of all the names of the emotions.'''
k = []
for e in self.emotions:
k.append(e.name)
return k
def run(self):
while self._awake:
#Handle update times for functions and numbers.
if hasattr(self._update_time, '__call__'):
ut = float(self._update_time())
else:
ut = self._update_time
#Wait so we don't hog the cpu
time.sleep(ut)
#Have all the emotions fire events to the pavlov network.
for emotion in self.emotions:
emotion.update()
def sleep(self):
'''Kills the thread.'''
self._awake = False
if __name__ == "__main__":
def myresponse():
print "I am happy"
def loveup():
print "Love raised"
rn = pavlov.ResponseNetwork()
rn.start()
rn.register_con_res('happy80', myresponse)
l = generate_plutchik_limbic(rn)
l['joy'].add_event(80, 70, "happy80")
rn.change_response('love_up', loveup)
l['joy'].value = 100
l['trust'].value = 80
time.sleep(2)
print l['love'].value
l.sleep()
|
josephlewis42/personal_codebase
|
python/randall/alife_randall_checkout/randallai/AI/mapper.py
|
#!/usr/bin/env python
''' The mapper module is used to maintain a map of places.
Copyright (c) 2011 <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
import threading
import time
import random
import copy
__version__ = 1.0
__author__ = "<NAME> <<EMAIL>>"
__license__ = "Copyright (c) 2010 <NAME> <<EMAIL>> all rights reserved."
DEBUGGING = False
def make_maze(seed=None, xsize=10, ysize=10, zsize=1):
'''Returns a randomized grid (a maze). A seed can be supplied to
get the same maze each time.
Paramaters:
seed -- An int to seed the random number generator with.
xsize -- The width of the maze to generate. (int) Default: 10
ysize -- The height of the maze to generate. (int) Default: 10
zsize -- The z of the maze to generate. (int) Default: 1
'''
if not seed:
seed = int(random.random() * 1000000)
random.seed(seed)
#Make a graph and populate it with cells
g = Grid(xsize, ysize, zsize, True, name="Random Seed:%s"%(str(seed)))
#Gets the non visited neighbors of the given cell.
def non_visited_neighbors(cell):
nonvisited = []
for n in g.neighbors(cell):
if n.parent == None:
nonvisited.append(n)
return nonvisited
#Recursively remove walls, without recursive calls due to overflows.
current = g.cell_at(0,0,0)
last = []
last.append(current)
while last:
#If there are neighbors remove a wall and add to the stack.
nvn = non_visited_neighbors(current)
if nvn:
next = random.choice(nvn)
g.set_accessible(current, next, True)
next.parent = current
last.append(current)
current = next
else: #If there are no neighbors pop the stack and try from there.
current = last.pop()
return g
def make_from_mapfile(mapfile_location):
'''Re-creates a maze from a mapfile at the given filesystem path.
'''
f = open(mapfile_location)
name = ""
size = None
#Read first line, this should say MAP version.
line = f.readline()
if "MAP" not in line:
raise Exception, "Not a valid mapfile!"
if eval(line.split(" ")[1]) > __version__:
raise Exception("Map file too new!")
#Fetch the name and size of the map.
while line.startswith("#"):
line = f.readline()
if "Name" in line:
name = line[line.index(' '):-1] #-1 = Don't include newline
if "Size" in line:
size = line[line.index(' '):-1] #-1 = Don't include newline
size = eval(size) #Change to tuple
#Make new map instance that fits the size of the given file.
x, y, z = size
newgrid = Grid(x, y, z, True, name)
#Get all of the cells and populate the map.
#A line is in the format: (x,y,z) nesw []
f.seek(0)
for line in f:
if line.startswith("#"): #Skip comments.
continue
a = line.split('\t')
x, y, z = eval(a[0])
d = a[1]
items = eval(a[2])
c = Cell(x,y,z, 'n' in d, 's' in d, 'e' in d, 'w' in d, \
'u' in d, 'd' in d)
c.items = items
newgrid.append(c)
return newgrid
def map2HTML(mapfile_location):
'''Generates an HTML version of the mapfile at the same location
as the original.'''
g = make_from_mapfile(mapfile_location)
g.gen_HTML(file_path=mapfile_location+".html")
class Cell:
'''A representation of a square of the map, has an x y and z axis
to allow better representaiton of the map. Each square can have
extra variables attached to it such as temperature, humidity, etc.
Map squares can also have objects attached to them, usually things
identified by the senses that the Actor can interact with. These
can be stored in a list in the map square.
Variables:
north -- Can this cell access the one to the north? (boolean)
south -- Can this cell access the one to the south? (boolean)
east -- Can this cell access the one to the east? (boolean)
west -- Can this cell access the one to the west? (boolean)
up -- Can this cell access the one above? (boolean)
down -- Can this cell access the one below? (boolean)
x -- The x (E/W) location of this cell in the world. (int)
y -- The y (N/S) location of this cell in the world. (int)
z -- The z (U/D) location of this cell in the world. (int)
items -- A list of items this cell holds that Actors can interact
with. (List of Strings)
css_id -- A unique id for representing this Cell when it is placed
in an HTML file. Format: x00,y00,z00 Where the zeros
are replaced by the x,y, and z of the Cell. (String)
Note:
Just because this cell can access another doesn't mean the reverse
is true.
'''
last_visit = 0.0 #The last time this cell was seen live.
#For a* algorithm
score = 0
parent = None
def __init__(self, x, y, z, north, south, east, west, up=False, down=False):
'''Creates a new map square, with the x y and z location, as well as
the movement variables.
Paramaters:
x -- The x location of this square (int)
y -- The y location of this square (int)
z -- The z location of this square (int)
north -- Can this square access the north? (bool)
south -- Can this square access the south? (bool)
east -- Can this square access the east? (bool)
west -- Can this square access the west? (bool)
up -- Can this square access above? (bool) Default: False
down -- Can this square access below? (bool) Default: False
'''
self.x = x
self.y = y
self.z = z
self.north = north
self.south = south
self.east = east
self.west = west
self.up = up
self.down = down
self.items = []
self.css_id = "x%iy%iz%i" % (x, y, z)
def __str__(self):
return "(%i,%i,%i)" % (self.x, self.y, self.z)
def is_north(self, other):
'''Is this cell North of the one given? Return bool.'''
return self.y < other.y
def is_south(self, other):
'''Is this cell South of the one given? Return bool.'''
return self.y > other.y
def is_east(self, other):
'''Is this cell East of the one given? Return bool.'''
return self.x > other.x
def is_west(self, other):
'''Is this cell West of the one given? Return bool.'''
return self.x < other.x
def is_up(self, other):
'''Is this cell above the one given? Return bool.'''
return self.z < other.z
def is_down(self, other):
'''Is this cell below the one given? Return bool.'''
return self.z > other.z
def is_same_location(self, other):
'''Is this cell in the same location as the one given? (bool)
'''
return other.x == self.x and other.y == self.y and other.z == self.z
def update(self, newer):
'''Updates this cell's directions and item list based off the
values of another (newer) version.
Also updates the last_visit variable to the current time.
Paramaters:
newer -- An instance of a Cell whose direction and items
values are to be copied to this cell's. (Cell)
'''
self.north = newer.north
self.east = newer.east
self.south = newer.south
self.west = newer.west
self.up = newer.up
self.down = newer.down
self.items = copy.copy(newer.items)
self.last_visit = time.time()
class Grid:
'''A container of Cells.
North/South is y Furthest north is 0
East/West is x Furthest West is 0
Up/Down is z Furthest up is 0
Variables:
grid -- A 3D array of Cells.
_x -- The x size for the grid. (int)
_y -- The y size for the grid. (int)
_z -- The z size for the grid. (int)
name -- A name for this grid. (String)
'''
def __init__(self, x, y, z=1, fill=False, name=""):
'''Creates a new grid with the number of elements. To concerve
memory with potentially large grids they are not filled unless specified
with the fill variable.
Paramaters:
x -- The number of x columns. (int)
y -- The number of y rows. (int)
z -- The number of z levels. (int) Default: 1
fill -- Should the grid be populated with cells? (bool)
Default: False
name -- The name of this map. (string) Default: ""
'''
if not isinstance(x, int) or not isinstance(y, int) or not isinstance(z, int):
raise TypeError("Can't create grid from non int indexes.")
self._x = x
self._y = y
self._z = z
self.name = name
#Create a new grid filled with Nones.
self.grid = [[[None]*z for i in xrange(y)] for j in xrange(x)]
if fill:
for j in range(x):
for k in range(y):
for l in range(z):
c = Cell(j, k, l, False, False, False, False)
self.append(c)
class Iterator():
'''A simple dirty iterator for mapper.'''
def __init__(self, parent):
self.mylist = []
for j in range(parent._x):
for k in range(parent._y):
for l in range(parent._z):
self.mylist.append( parent.cell_at(j, k, l) )
self.mylist.reverse()
def next(self):
#Check for stop:
if not self.mylist:
raise StopIteration
return self.mylist.pop()
def __iter__(self):
'''Allows Grid to be used in for loops.
Example:
>>> for cell in Grid:
>>> print cell
'''
return self.Iterator(self)
def add_cell(self, cell):
'''Adds a cell to the Grid.'''
import warnings
warnings.warn("Use Grid.append() instead of Grid.add_cell()", DeprecationWarning, stacklevel=2)
self.append(cell)
def append(self, cell):
'''Adds a cell to the Grid container.'''
self.grid[cell.x][cell.y][cell.z] = cell
def cell_at(self, x, y, z=0):
'''Returns the cell at the given location. Returns none if
the cell has not been generated yet.
Throws:
IndexError -- If indexes are negative or out of bounds.
'''
if x < 0 or y < 0 or z < 0:
raise IndexError("List index negative.")
return self.grid[x][y][z]
def safe_cell_at(self, x, y, z=0):
'''Returns the cell at the given location. Returns none if the cell
has not been generated yet or is out of bounds.
'''
try:
return self.cell_at(x, y, z)
except IndexError:
return None
def clear_parents(self):
'''Removes all parents settings from the cells.'''
for c in self:
try:
c.parent = None
except AttributeError:
pass
def get_all_items(self):
'''Returns a list of all the unique items in the Grid's Cells.'''
itemlist = []
for c in self:
try:
for i in c.items:
itemlist.append(i)
except AttributeError:
pass #The cell must be None
return list( set(itemlist) ) #Uniquify
def find_closest_list(self, items_list, othercell, quick=False):
'''Returns the closest Cell to the one given that has the
of the given items from items_list in its item list.
Paramaters:
items_list -- A list of names of items to search for. (string)
othercell -- The cell to judge distances from. (Cell)
quick -- True to judge the distance quickly based on the cells
relative position, False to actually find a route to
each cell before returning the fastest. False is
much more accurate, but much slower.
Default: False (boolean)
Returns a tuple (distance to closest cell, closest cell,
item at that cell).
Returns (None, None, None) if no cell has the given item.
'''
eachitem = []
self.clear_parents()
for i in items_list:
dist, cell = self.find_closest(i, othercell, quick)
if dist and cell:
cell.parent = i
eachitem.append((dist, cell))
for j in sorted(eachitem):
return (j[0], j[1], j[1].parent)
return (None, None, None)
def find_closest(self, itemname, othercell, quick=False):
'''Returns the closest Cell to the one given that has the
given item in its item list.
Paramaters:
itemname -- The name of the desired item. (string)
othercell -- The cell to judge distances from. (Cell)
quick -- True to judge the distance quickly based on the cells
relative position, False to actually find a route to
each cell before returning the fastest. False is
much more accurate, but much slower.
Default: False (boolean)
Returns a tuple (distance to closest cell, closest cell).
Returns (None, None) if no cell has the given item.
'''
closest = None
dist = None #The distance to the closest
for c in self:
if not c:
continue
if itemname in c.items:
if DEBUGGING:
print "%s is in %s" % (itemname, c)
#Get the first one.
if not closest:
closest = c
dist = self.heuristic(othercell, c)
#Less computation
if quick:
mydist = self.heuristic(othercell, c)
if mydist < dist:
closest = c
dist = mydist
#More computation, but more accuracy
else:
mydist = self.heuristic(othercell, c)
if mydist <= dist:
mydist = len(self.path_to(othercell, c)) - 1 #Subtract the starting position.
if mydist < dist:
closest = c
dist = mydist
return (dist, closest)
def find_closest_unexplored(self, here):
'''Finds the closest cell with unexplored neighbors, returns
as a tuple (distance, closest_cell).
'''
for c in self:
if c and self.unvisited_neighbors(c):
c.items.append("has_unexplored_neighbors")
print c
output = self.find_closest("has_unexplored_neighbors", here, True)
#Remove unvisited status
for c in self:
try:
c.items.remove("has_unexplored_neighbors")
except:
pass
return output
def heuristic(self, here, there):
'''A heuristic estimate of distance between two nodes.
Paramaters:
here -- A cell or a tuple with x,y,z coordinates for a location.
there -- A cell or a tuple with x,y,z coordinates for a location.
Example:
heuristic(Cell c, (2,2,8))
'''
if hasattr(here, "__module__"):
h_x, h_y, h_z = here.x, here.y, here.z
else:
h_x, h_y, h_z = here #Unpack the tuple
if hasattr(there, "__module__"):
t_x, t_y, t_z = there.x, there.y, there.z
else:
t_x, t_y, t_z = there
x = abs(h_x - t_x)
y = abs(h_y - t_y)
z = abs(h_z - t_z)
return x + y + z
def path_to(self, here, there):
'''Returns the path from the first cell to the second using the A*
search algorighm.
TODO: add support for terrain difficulty.
'''
self.clear_parents()
open_set = set()
closed_set = set()
path = []
def retrace_path(c):
path = [c]
while c.parent is not None:
c = c.parent
path.append(c)
path.reverse()
return path
open_set.add(here)
while open_set:
#Get the node in openset having the lowest f_score value (stored as score in ini)
current = sorted(open_set, key=lambda i:i.score)[0]
#end if we have reached the end.
if current == there:
return retrace_path(current)
#Move x from openset to closedset
open_set.remove(current)
closed_set.add(current)
for y in self.accessible_neighbors(current):
if y not in closed_set:
y.score = self.heuristic(y, there)
if y not in open_set:
open_set.add(y)
y.parent = current
return [] #Failed
def is_touching(self, cellone, celltwo):
'''Returns True if both cells are touching (regardless of if
they can access one another or not). Cells in the same
location are always touching.
'''
for n in self.neighbors(cellone):
if celltwo.is_same_location(n):
return True
if cellone.is_same_location(celltwo):
return True
return False
def is_accessable(self, cellone, celltwo):
'''Returns True if celltwo is accessable from cellone, note
that the reverse isn't always True. Cells in the same
location are always accessable to each other.'''
for n in self.accessible_neighbors(cellone):
if celltwo.is_same_location(n):
return True
if cellone.is_same_location(celltwo):
return True
return False
'''if cellone.is_north(celltwo):
return cellone.south
if cellone.is_south(celltwo):
return cellone.north
if cellone.is_east(celltwo):
return cellone.west
if cellone.is_west(celltwo):
return cellone.east
if cellone.is_up(celltwo):
return cellone.down
#Cellone must be below celltwo
return cellone.up'''
def neighbors(self, cell):
'''Returns a list of the neighbors for the cell supplied.
If the neighbors haven't been added to the grid (None)
they are ignored.
Paramaters:
cell -- The cell to return neighbors for.
'''
x = cell.x
y = cell.y
z = cell.z
return self.neighbors_by_location(x,y,z)
def neighbors_by_location(self, x, y, z):
'''Returns a list of the neighbors for the coordinates
supplied.
If the neighbors haven't been added to the grid (None)
they are ignored.
Paramaters:
x,y,z -- The coordinates for the cell to get neighbors from.
'''
n = []
n.append(self.safe_cell_at(x-1, y, z))
n.append(self.safe_cell_at(x+1, y, z))
n.append(self.safe_cell_at(x, y+1, z))
n.append(self.safe_cell_at(x, y-1, z))
n.append(self.safe_cell_at(x, y, z-1))
n.append(self.safe_cell_at(x, y, z+1))
#Remove Nones so as not to mess up program
#ValueError is thrown when no more exist.
try:
while True:
n.remove(None)
except ValueError:
pass
return n
def unvisited_neighbors(self, cell):
'''Returns the number of neighbors that are accessible but unvisited
for the given cell.
'''
x = cell.x
y = cell.y
z = cell.z
c = cell
unvisited = []
if c.north:
try:
unvisited.append(self.cell_at(x, y-1, z))
except IndexError:
pass
if c.south:
try:
unvisited.append(self.cell_at(x, y+1, z))
except IndexError:
pass
if c.east:
try:
unvisited.append(self.cell_at(x+1, y, z))
except IndexError:
pass
if c.west:
try:
unvisited.append(self.cell_at(x-1, y, z))
except IndexError:
pass
if c.up:
try:
unvisited.append(self.cell_at(x, y, z-1))
except IndexError:
pass
if c.down:
try:
unvisited.append(self.cell_at(x, y, z+1))
except IndexError:
pass
count = 0
for u in unvisited:
if not u:
count += 1
return count
def accessible_neighbors(self, cell):
'''Returns a list of the neighbors accessible from the cell at
the given point.
If the neighbors haven't been added to the grid (unexplored)
they are ignored.
Paramaters:
cell -- The cell to get neighbors from
'''
x = cell.x
y = cell.y
z = cell.z
c = cell
accessible = []
if c.north:
accessible.append(self.safe_cell_at(x, y-1, z))
if c.south:
accessible.append(self.safe_cell_at(x, y+1, z))
if c.east:
accessible.append(self.safe_cell_at(x+1, y, z))
if c.west:
accessible.append(self.safe_cell_at(x-1, y, z))
if c.up:
accessible.append(self.safe_cell_at(x, y, z-1))
if c.down:
accessible.append(self.safe_cell_at(x, y, z+1))
#Remove Nones so as not to mess up program
#ValueError is thrown when no more exist.
try:
while True:
accessible.remove(None)
except ValueError:
pass
return accessible
def random_accessible_neighbor(self, cell, notin=None):
'''Returns a random accessible neighbor for the cell given.'''
myn = self.accessible_neighbors(cell)
random.shuffle(myn)
if notin and myn[0].is_same_location(notin):
try:
return myn[1]
except:
pass
return myn[0]
def random_neighbor(self, cell, notin=None):
'''Returns a random neighbor for the cell given. If supplied
the cell given at notin will not be chosen.'''
myn = self.neighbors(cell)
random.shuffle(myn)
if notin and myn[0].is_same_location(notin):
try:
return myn[1]
except:
return myn[0]
return myn[0]
def set_accessible(self, cellone, celltwo, value=True):
'''Sets the walls between two cells to value. If the cells
aren't neighbors do nothing. The default value removes the
walls between the two cells.
Paramaters:
cellone -- A Cell to add or remove a wall between.
celltwo -- A Cell to add or remove a wall between.
value -- True = Remove "walls" False = Add "walls"
'''
if celltwo in self.neighbors(cellone):
if cellone.is_north(celltwo):
cellone.south = value
celltwo.north = value
elif cellone.is_south(celltwo):
cellone.north = value
celltwo.south = value
elif cellone.is_east(celltwo):
cellone.west = value
celltwo.east = value
elif cellone.is_west(celltwo):
cellone.east = value
celltwo.west = value
elif cellone.is_up(celltwo):
cellone.down = value
celltwo.up = value
elif cellone.is_down(celltwo):
cellone.up = value
celltwo.down = value
def gen_inner_HTML(self, z=0):
'''Generates the grid for the gen_HTML function.'''
table = ""
#Set up the css and divs for all cells
for j in range(self._y):
for k in range(self._x):
c = self.safe_cell_at(k, j, z)
css_id = "x%iy%iz%i"%(k, j, z)
if c == None: #Not explored
inner = "?"
nesw = "unknown"
else:
inner = ""
if c.up:
inner += "↑"
if c.down:
inner += "↓"
if c.items != []:
for item in c.items:
inner += str(item)+"<br />"
nesw = "" #class ids to apply
if not c.north:
nesw += "n "
if not c.east:
nesw += "e "
if not c.south:
nesw += "s "
if not c.west:
nesw += "w"
table += "<div id='%s' class='%s'>%s</div>\n" % (css_id, nesw, inner)
return table
def table_width(self, size_of_cell):
return size_of_cell * self._x
def gen_HTML(self, z=0, commands="", file_path=None):
'''Generates an HTML representation of the NESW directions
for the given level.
Paramaters:
z -- The level to generate from.
commands -- The cell IDs to be placed in the javascript
function. These correspond with cells.
file_path -- The file to write the map to, overwrites if
existing. (string)
'''
table = self.gen_inner_HTML(z)
page = '''
<html><head>
<script type="text/javascript">
var orig = "";
var current = null;
var list = [];
var i = 0;
function play()
{
clearInterval();
var all = document.getElementById('commands').value;
list = all.split("\\n");
i = 0;
setInterval(next, 200);
}
function next()
{
if( current != null)
{
document.getElementById(current).innerHTML = orig;
}
current = list[i];
orig = document.getElementById(current).innerHTML;
document.getElementById(current).innerHTML = "<:3)~";
i++;
if( i >= list.length - 1)
{
clearInterval();
}
}
</script>
<style>
div { width:28px; height:28px; text-align:center;
border:1px solid #FFF; float:left; font-size:8pt; }
#entire { width:%ipx; text-align:left; margin:0px; padding:0px; }
.unknown { background-color:#999; font-size:28px;}
.n { border-top:1px solid #000; }
.s { border-bottom:1px solid #000; }
.e { border-right:1px solid #000; }
.w { border-left:1px solid #000; }
</style></head>
<body><h1>%s</h1><div id="entire">%s</div>
<div width="100%%">
<textarea cols="50" rows="4" id="commands">%s</textarea>
<button type="button" onClick="javascript:play();">Play</button>
</div></body></html>
'''%(self.table_width(30), self.name, table, commands)
#Write file if desired.
if file_path:
f = open(file_path, 'w')
f.write(page)
f.close()
return page
def update_or_add(self, cell):
'''Updates the cell at the same location as the current cell if it
exists, adds it otherwise.'''
if self.cell_at(cell.x, cell.y, cell.z) != None:
self.cell_at(cell.x, cell.y, cell.z).update(cell)
else:
self.append( cell )
def gen_mapfile(self, file_path = None):
'''Generates a mapfile for this specific map. Returns it as a string.
Optionally writes it to a file.
Paramaters:
file_path = The file to write the map to, overwrites if existing. (string)
'''
output = "#MAP %s Used by AI mapper class, %s\n" % (str(__version__), __license__)
output += "#Generation Time UTC: %s\n" % (time.strftime("%Y-%m-%d %H.%M.%S"))
output += "#Name: %s\n" % (self.name)
output += "#Size: (%i,%i,%i)\n" % (self._x, self._y, self._z)
for c in self:
if not c: #If null, just get next
continue
representation = str(c) + "\t"
if c.north:
representation += "n"
if c.east:
representation += "e"
if c.south:
representation += "s"
if c.west:
representation += "w"
if c.up:
representation += "u"
if c.down:
representation += "d"
representation += "\t" + str(c.items) + "\n"
output += representation
#Write file if desired.
if file_path:
f = open(file_path, 'w')
f.write(output)
f.close()
return output
def interface_from_grid(grid, mynameclass):
'''Generates an ItemEventInterface from the given Grid, grid. All
of the Grid's item names are sought after in the given class
mynameclass. For example if you had a Grid whose Cells had the
following items: ['food', 'water', 'lever'] and passed an instance
of the class c:
class c:
def food(self, actor):
<--Insert code here-->
def water(self, actor):
<--Insert code here-->
Then the items food and water would be mapped to the functions
with the same name, the final item would throw an exception.
Paramaters:
grid -- An instance of Grid to take items from.
mynameclass -- An instance of a class whose methods are the same
names as the items.
'''
func_names = set(dir(mynameclass))
items = grid.get_all_items()
iei = ItemEventInterface()
for i in items:
if i in func_names:
func_i = eval('mnc.%s' % (i), {}, {'mnc':mynameclass})
iei.register(i, func_i)
else:
raise KeyError("Can't map %s to a function!" % (i))
return iei
class ItemEventInterface:
'''Provides an interface for interacting with items on the map.
Items get registered with their specific functions.'''
_iei = {}
news = []
def name_to_action(self, string):
'''Convert the name of an object to an interaction name.'''
return string + "_interact"
def register(self, item_name, event):
'''Adds the item_name and event to the interface.
Paramaters:
item_name -- The name of the item as it is found in the items
list in Cells on a Grid. (string)
event -- The function that is triggered when an Actor
interacts with the item. Takes a single paramater,
the Actor that is interacting with the item. Returns
a string about what happened (for logging/news
updates) or None. (function)
'''
#Change the name to action
item_name = self.name_to_action(item_name)
self._iei[item_name] = event
def interact(self, actor, item_name):
'''This function is called when an actor wishes to interact
with an item on the map. Also registers the action with the
Actor's pavlov.ResponseNetwork, adding it if necessary.
Paramaters:
item_name -- The name of the item as it is found in the items
list in Cells on a Grid. (string)
'''
if DEBUGGING:
print("Actor %s interacted with %s" % (actor.name, item_name))
#Change the name to action
item_name = self.name_to_action(item_name)
#Register the action with the Actor's pavlov.
actor.response_network.condition(item_name)
#Run the event.
self.news.append( self._iei[item_name](actor) )
def fetch_news(self):
'''Returns a list of strings of the news generated by the
actor's interactions with their environment.
'''
n = self.news
self.news = []
return n
def exists(self, i):
'''Checks if an item actually exists. Return true/false.
If i is a list, returns a list of the items that exist.
'''
#String
if not hasattr(i, '__iter__'):
#Change the name to action
i = self.name_to_action(i)
return i in self._iei.keys()
#List
new = []
for j in i:
if self.exists(j):
new.append(j)
return new
if __name__ == "__main__":
g = make_maze(seed=617161, xsize=30, ysize=30)
#g.gen_HTML(file_path="output_basic.html")
g.grid[1][1][0].items = ['food']
a,b = g.find_closest('food',g.cell_at(1,1))
#print b
#print g.heuristic(g.cell_at(1,1), g.cell_at(2,2))
#x = g.find_closest_unexplored(g.cell_at(9,9))
#print x[1]
#cmds = ""
#for x in g.path_to(g.cell_at(9,9), x[1]):
# cmds += ("%s\n"%(x.css_id))
#g.gen_HTML(commands=cmds, file_path="output.html")
#g.gen_mapfile('output.map')
|
josephlewis42/personal_codebase
|
python/randall/alife_randall_checkout/randallai/AI/maslow.py
|
<reponame>josephlewis42/personal_codebase
#!/usr/bin/env python
'''
The maslow module provides a basic list of needs and the ability to
judge how well those needs are doing based off organs.
More Info: http://en.wikipedia.org/wiki/Maslow's_hierarchy_of_needs
Copyright (c) 2011 <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
__version__ = 1.0
__author__ = "<NAME> <<EMAIL>>"
DEBUGGING = False
PHYSIOLOGICAL = 0
SAFETY = 1
LOVE = 2
ESTEEM = 3
SELF_ACTUALIZATION = 4
OTHER = 5
PHYSIOLOGICAL_NEEDS = ['breathing', 'food', 'water', 'sex', 'sleep', \
'homeostasis', 'excretion']
SAFETY_NEEDS = ['body', 'employment', 'family', 'health', 'resources', \
'morality', 'property']
LOVE_NEEDS = ['friendship', 'family', 'intimacy']
ESTEEM_NEEDS = ['self_esteem', 'confidence', 'achivement', \
'respect_of_others', 'respect_by_others']
SELF_ACTUALIZATION_NEEDS = ['creativity', 'morality', 'spontaneity', \
'problem_solving', 'lack_prejudice', \
'fact_acceptance']
#The number of items to keep in a needs history used for extrapolating future needs.
NEED_HISTORY_LENGTH = 5
class Need:
'''The need class represents a particular need for a creature.
The higher the Need.value the more pressing it is.'''
importance = None
update_function = None
name = None
need_history = [] #The last NEED_HISTORY_LENGTH values for need, determines change
value = 0
def __init__(self, name, importance, update_function=None, updown=None):
'''Initializes a Need.
Paramaters:
name -- The key used to represent this need in the Heirarchy.
Usually a string.
importance -- The importance of this need in the heirarchy,
0 being the lowest (PHYSIOLOGICAL variable) and
4 being the highest (SELF_ACTUALIZATION). (int)
update_function -- The function called to update this need,
if none is provided the need will be ignored!
The function will be passed one variable, the
current value, if the function does not
accept this variable it will be called with
none.
The function should return a number between
0 and 100 anything higher or lower will be
changed to it's respective min/max (function)
Default: None
updown -- An instance of pavlov.Response_Network, if not None
the conditions <needname>_up and <needname>_down
will be created, when the need value is raised
<needname>_up will be fired and the opposite for
lowering. (pavlov.ResponseNetwork) Default: None
'''
self.name = name
self.importance = importance
self.update_function = update_function
#Do the updown setup.
if updown != None:
self.response_network = updown
self.updown = True
updown.register_con_res("%s_up"%(name))
updown.register_con_res("%s_down"%(name))
else:
self.updown = False
def __str__(self):
'''Returns the name and value of this need as a string.'''
return "%s:%i" % (self.name, self.value)
def sortvalue(self):
'''Creates a value to be used in sorting for importance.
The lower the value the more pressing this need. Needs with
a lower importance will always come in before needs with
a higher one, even if the need with the higher importance has
a higher value.
'''
return (100 - self.value) + (self.importance * 100)
def update(self):
'''Updates the Need's value by calling the need's
update_function.
Returns the new value.
'''
if hasattr(self.update_function, '__call__'):
#Try providing the current value.
try:
self.value = self.update_function(self.value)
except TypeError:
self.value = self.update_function()
#Set the need history, but don't let it get too long.
self.need_history.append(self.value)
if len(self.need_history) > NEED_HISTORY_LENGTH:
self.need_history = self.need_history[-NEED_HISTORY_LENGTH:]
#Fix values
if self.value > 100:
self.value = 100
elif self.value < 0:
self.value = 0
#Register raise and lowering of emotions.
if self.updown and len(self.need_history) > 2:
if self.need_history[-1] > self.need_history[-2]:
self.response_network.condition("%s_up"%self.name)
elif self.need_history[-1] < self.need_history[-2]:
self.response_network.condition("%s_down"%self.name)
if DEBUGGING:
print(str(self))
return self.value
def _average_need_history(self):
'''Returns the average slope of the need history.'''
myslopes = []
for i in range(len(self.need_history)-1):
tmp = self.need_history[i+1] - self.need_history[i] #Change in x, change in y is always 1
myslopes.append(tmp)
return sum(myslopes) / float(len(myslopes))
def calls_to_max(self):
'''Returns the (guessed) number of update calls until this
Need hits 100. Uses past data, the number of past points is
defined by the NEED_HISTORY_LENGTH variable.
Note: If need is going down the number of calls will be negative
'''
return (100 - self.value) / self._average_need_history()
def calls_to_min(self):
'''Returns the (guessed) number of update calls until this
Need hits 0. Uses past data, the number of past points is
defined by the NEED_HISTORY_LENGTH varaible.
Note: If need is rising the number of calls will be negative.
'''
return -self.value / self._average_need_history()
class Heirarchy:
'''The Heirarchy class is used in determining needs. Each need has
a priority and an update function, when the Heirarchy class is
polled for the highest need it updates itself, this can add time
but reduces latency between need changes and resolution. It also
removes the overhead of having an extra thread running constantly.
'''
needs = []
def __init__(self, level, updown_response_network=None):
'''Creates a heirarchy with the level of needs corresponding to
the given level. The update functions for these needs must
be set so they are considered when getting the most pressing
need.
If the level provided does not correspond to any need list then
no default needs will be added.
If updown_response_network is an instance of
pavlov.ResponseNetwork then conditions will be registered on
the raising and lowering of needs. DEFAULT: None
Paramaters:
level -- The level of needs to autogenerate (adds these needs
and all on lower levels). (int) Default: 1
updown -- An instance of pavlov.Response_Network, if not None
the conditions <needname>_up and <needname>_down
will be created for each autogenerated need. When
the need value is raised <needname>_up will be fired
and the opposite for lowering.
(pavlov.ResponseNetwork) Default: None
Example:
>>> h = Heirarchy(maslow.PHYSIOLOGICAL)
>>> h.needs
['breathing', 'food', 'water', 'sex' ... 'sleep']
'''
needs_list_list = []
if level >= SELF_ACTUALIZATION:
for n in SELF_ACTUALIZATION_NEEDS:
self.needs.append( Need(n, SELF_ACTUALIZATION, updown=updown_response_network) )
if level >= ESTEEM:
for n in ESTEEM_NEEDS:
self.needs.append( Need(n, ESTEEM, updown=updown_response_network) )
if level >= LOVE:
for n in LOVE_NEEDS:
self.needs.append( Need(n, LOVE, updown=updown_response_network) )
if level >= SAFETY:
for n in SAFETY_NEEDS:
self.needs.append( Need(n, SAFETY, updown=updown_response_network) )
if level >= PHYSIOLOGICAL:
for n in PHYSIOLOGICAL_NEEDS:
self.needs.append( Need(n, PHYSIOLOGICAL, updown=updown_response_network) )
def __getitem__(self, key):
'''Emulates a list or dictionary, called with the name of the
need, or an index. Raises IndexError if not found.
Example:
>>> <Heirarchy>['food']
<class Need at 0x0000007b>
>>> <Heirarchy>[0]
<class Need at 0x0000002a>
>>> <Heirarchy>[None]
IndexError
'''
#Check for strings
try:
for n in self.needs:
if n.name == key:
return n
except TypeError:
pass
#Check for indexes
try:
return self.needs[key]
except TypeError:
pass
#else raise error
raise IndexError
def __len__(self):
'''Returns the number of needs registered.'''
return len(self.needs)
def clean_needs(self):
'''Removes needs from the need list that have no update_function
This speeds up searches, updates, and clears memory. Needs such
as this may enter the needs list upon initialization.
'''
new_needs = []
for n in self.needs:
if hasattr(n.update_function, '__call__'):
new_needs.append(n)
self.needs = new_needs
def update_needs(self):
'''Updates the value of all needs by having each call its
update_function.'''
for n in self.needs:
n.update()
def most_urgent(self, threshold=80, update=True):
'''Gets the most urgent need from the lowest possible need
level that breaches the threshold. Return None if there are
no breaches.
If the threshold is None, just return the Need with the highest
value.
Paramaters:
threshold -- The number the need's value must be over to consider
returning the need. (int/None)
Default: 80
update -- Should the needs be updated before calling? (boolean)
Default: True
'''
#Update needs if desired
if update:
self.update_needs()
#If threshhold is none return need with highest value (last).
if not threshold:
return sorted(self.needs, key=lambda i:i.value)[-1]
#Get all needs over threshold.
over = []
for n in self.needs:
if n.value > threshold:
over.append(n)
#Sort so the most important is first
try:
return sorted(over, key=lambda i:i.sortvalue())[0]
except IndexError:
return None
if __name__ == "__main__":
h = Heirarchy(LOVE)
for n in h.needs:
print n
print h.most_urgent()
#Test needs cleaning
def friend():
return 81
def food():
return 81
h['friendship'].update_function = friend
h['food'].update_function = food
h.clean_needs()
#Test urgency rating
print h.most_urgent()
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex16_g2dbinstr.py
|
<filename>python/Genetic Programming/Examples/pyevolve_ex16_g2dbinstr.py
from pyevolve import G2DBinaryString
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import Crossovers
from pyevolve import Mutators
# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
score = 0.0
# iterate over the chromosome
for i in xrange(chromosome.getHeight()):
for j in xrange(chromosome.getWidth()):
# You can use the chromosome.getItem(i, j)
if chromosome[i][j]==0:
score += 0.1
return score
# Genome instance
genome = G2DBinaryString.G2DBinaryString(8, 5)
# The evaluator function (objective function)
genome.evaluator.set(eval_func)
genome.crossover.set(Crossovers.G2DBinaryStringXSingleHPoint)
genome.mutator.set(Mutators.G2DBinaryStringMutatorSwap)
# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.setGenerations(200)
# Do the evolution, with stats dump
# frequency of 10 generations
ga.evolve(freq_stats=10)
# Best individual
print ga.bestIndividual()
|
josephlewis42/personal_codebase
|
python/xkcdfetch.py
|
<filename>python/xkcdfetch.py<gh_stars>1-10
#!/usr/bin/python
import urllib2
import time
import sys
WGET = False
try:
if sys.argv[1] == "-w":
WGET = True
except IndexError:
pass
for i in range(1,850):
if i == 404: #Skip the 404th comic which is an error 404 page.
continue
url = "http://xkcd.com/%i/info.0.json" % (int(i))
comic_json = urllib2.urlopen(url)
time.sleep(.2)
comic = eval( comic_json.read() )
number = comic['num']
title = comic['title']
image = comic['img']
alt = comic['alt']
if WGET: #Just list urls for wget :)
print(image)
else:
print("<li><a href='%s'>%s - %s</a> - %s</li>\n" % (image, number, title, alt))
|
josephlewis42/personal_codebase
|
python/reprap-franklin/firmware/repman.py
|
<filename>python/reprap-franklin/firmware/repman.py<gh_stars>1-10
#!/usr/bin/env python
'''An emulator for RepMan specific commands (not complete)
Copyright 2011 <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
import full
__author__ = "<NAME>"
__copyright__ = "Copyright 2011, <NAME>"
__license__ = "GPL"
__version__ = "1.0"
class RepMan (full.Firmware):
title = "RepMan"
def M101(self, gc):
self.debug("M101: Turn extruder 1 on forward.")
if self.reprap.current_toolhead.extrude_rate == 0:
self.reprap.current_toolhead.extrude_rate = 1
def M103(self, gc):
self.debug("M103: Turn all extruders off.")
for th in self.reprap.possible_toolheads:
th.extrude_rate = 0
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Finished Programs/2010-08-30 GP Vaccum .py
|
from pyevolve import *
import math
import pprint
NORTH = 0
SOUTH = 2
EAST = 1
WEST = 3
lowest_score_yet = 100 #Print out the lowest scores.
loc_x = 1
loc_y = 1
direction = 0
grid = []
def setup_map():
global grid
global loc_x
global loc_y
global direction
loc_x = 1
loc_y = 1
direction = 2
grid = [["x","x","x","x","x","x","x","x","x","x","x","x"],
["x",0,0,0,0,0,0,0,0,0,0,"x"],
["x",0,0,0,0,0,0,0,0,0,0,"x"],
["x",0,0,0,0,0,0,0,0,0,0,"x"],
["x",0,0,0,0,0,0,0,0,0,0,"x"],
["x",0,0,0,0,0,0,0,0,0,0,"x"], #10x10 Grid, 1-10, 1-10
["x",0,0,0,0,0,0,0,0,0,0,"x"], #Upper Left is 0,0
["x",0,0,0,0,0,0,0,0,0,0,"x"], #Must be refrenced [y][x]
["x",0,0,0,0,0,0,0,0,0,0,"x"],
["x",0,0,0,0,0,0,0,0,0,0,"x"],
["x",0,0,0,0,0,0,0,0,0,0,"x"],
["x","x","x","x","x","x","x","x","x","x","x","x"]]
def eval_grid():
total_zeros = 0
for x in range(len(grid)):
for y in range(len(grid[x])):
if grid[y][x] == 0:
total_zeros += 1
return total_zeros
def gp_turn_right(z):
global direction
direction +=1
if direction > 3:
direction = 0
return wall_on_right()
def gp_turn_left(z):
global direction
direction -=1
if direction < 0:
direction = 3
return wall_on_left()
def can_move_forward():
global direction
global loc_x
global loc_y
global grid
if direction == 0: #North
a = grid[loc_y - 1][loc_x] != "x"
if direction == 1: #East
a = grid[loc_y][loc_x + 1] != "x"
if direction == 2: #South
a = grid[loc_y + 1][loc_x] != "x"
if direction == 3: #West
a = grid[loc_y][loc_x - 1] != "x"
if a == True:
return 1
else:
return -1
def wall_on_right():
global direction
global loc_x
global loc_y
global grid
if direction == 3: #North is on right
a = grid[loc_y - 1][loc_x] != "x"
if direction == 0: #East is on right
a = grid[loc_y][loc_x + 1] != "x"
if direction == 1: #South is on right
a = grid[loc_y + 1][loc_x] != "x"
if direction == 2: #West is on right
a = grid[loc_y][loc_x - 1] != "x"
if a == True:
return 1
else:
return -1
def wall_on_left():
global direction
global loc_x
global loc_y
global grid
if direction == 1: #North is on left
a = grid[loc_y - 1][loc_x] != "x"
if direction == 2: #East is on left
a = grid[loc_y][loc_x + 1] != "x"
if direction == 3: #South is on left
a = grid[loc_y + 1][loc_x] != "x"
if direction == 0: #West is on left
a = grid[loc_y][loc_x - 1] != "x"
if a == True:
return 1
else:
return -1
def gp_if_gt_zero(a,b,c):
if a > 0:
return b
else:
return c
def place_marker():
global grid
grid[loc_y][loc_x] = 1
def gp_go_forward(z):
global loc_x
global loc_y
place_marker()
if can_move_forward() == 1:
if direction == 0: #NORTH
loc_y -= 1
if direction == 1: #EAST
loc_x += 1
if direction == 2: #SOUTH
loc_y += 1
if direction == 3: #WEST
loc_x -= 1
return 1
def gp_go_forward_until_stop(z):
while can_move_forward() == 1:
gp_go_forward("")
return -1
error_accum = Util.ErrorAccumulator()
def rangef(min, max, step):
result = []
while 1:
result.append(min)
min = min+step
if min>=max:
break
return result
def eval_func(chromosome):
global error_accum
global lowest_score_yet
error_accum.reset()
code_comp = chromosome.getCompiledCode()
setup_map()
#print grid
eval(code_comp, globals(), locals())
evaluated = eval_grid()
#Print out the significant patterns.
if evaluated < lowest_score_yet:
lowest_score_yet = evaluated
pprint.pprint(grid)
target = 0 #0 empty spaces is target
error_accum += (target, evaluated)
return error_accum.getRMSE()
def main_run():
genome = GTree.GTreeGP()
genome.setParams(max_depth=10, method="ramped")
genome.evaluator.set(eval_func)
ga = GSimpleGA.GSimpleGA(genome)
ga.setParams(gp_terminals = ['wall_on_right()','wall_on_left()','can_move_forward()'], gp_function_prefix = "gp")
ga.setMinimax(Consts.minimaxType["minimize"])
ga.setGenerations(100)
ga.setMutationRate(0.08)
ga.setCrossoverRate(1.0)
ga.setPopulationSize(50)
ga.evolve(freq_stats=5)
print ga.bestIndividual()
if __name__ == "__main__":
main_run()
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex11_allele.py
|
from pyevolve import G1DList
from pyevolve import GSimpleGA
from pyevolve import Mutators
from pyevolve import Initializators
from pyevolve import GAllele
# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
score = 0.0
# iterate over the chromosome
for value in chromosome:
if value == 0:
score += 0.5
# Remember from the allele set defined above
# this value 'a' is possible at this position
if chromosome[18] == 'a':
score += 1.0
# Remember from the allele set defined above
# this value 'xxx' is possible at this position
if chromosome[12] == 'xxx':
score += 1.0
return score
def run_main():
# Genome instance
setOfAlleles = GAllele.GAlleles()
# From 0 to 10 we can have only some
# defined ranges of integers
for i in xrange(11):
a = GAllele.GAlleleRange(0, i)
setOfAlleles.add(a)
# From 11 to 19 we can have a set
# of elements
for i in xrange(11, 20):
# You can even add objects instead of strings or
# primitive values
a = GAllele.GAlleleList(['a','b', 'xxx', 666, 0])
setOfAlleles.add(a)
genome = G1DList.G1DList(20)
genome.setParams(allele=setOfAlleles)
# The evaluator function (objective function)
genome.evaluator.set(eval_func)
# This mutator and initializator will take care of
# initializing valid individuals based on the allele set
# that we have defined before
genome.mutator.set(Mutators.G1DListMutatorAllele)
genome.initializator.set(Initializators.G1DListInitializatorAllele)
# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.setGenerations(40)
# Do the evolution, with stats dump
# frequency of 10 generations
ga.evolve(freq_stats=5)
# Best individual
print ga.bestIndividual()
if __name__ == "__main__":
run_main()
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex15_rosenbrock.py
|
from pyevolve import G1DList, GSimpleGA, Selectors, Statistics
from pyevolve import Initializators, Mutators, Consts, DBAdapters
# This is the Rosenbrock Function
def rosenbrock(xlist):
sum_var = 0
for x in xrange(1, len(xlist)):
sum_var += 100.0 * (xlist[x] - xlist[x-1]**2)**2 + (1 - xlist[x-1])**2
return sum_var
def run_main():
# Genome instance
genome = G1DList.G1DList(15)
genome.setParams(rangemin=-1, rangemax=1.1)
genome.initializator.set(Initializators.G1DListInitializatorReal)
genome.mutator.set(Mutators.G1DListMutatorRealRange)
# The evaluator function (objective function)
genome.evaluator.set(rosenbrock)
# Genetic Algorithm Instance
ga = GSimpleGA.GSimpleGA(genome)
ga.setMinimax(Consts.minimaxType["minimize"])
ga.selector.set(Selectors.GRouletteWheel)
ga.setGenerations(4000)
ga.setCrossoverRate(0.9)
ga.setPopulationSize(100)
ga.setMutationRate(0.03)
ga.evolve(freq_stats=500)
# Best individual
best = ga.bestIndividual()
print "\nBest individual score: %.2f" % (best.score,)
print best
if __name__ == "__main__":
run_main()
|
josephlewis42/personal_codebase
|
python/Genetic Programming/Examples/pyevolve_ex12_tsp.py
|
from pyevolve import G1DList, GAllele
from pyevolve import GSimpleGA
from pyevolve import Mutators
from pyevolve import Crossovers
from pyevolve import Consts
import sys, random
random.seed(1024)
from math import sqrt
PIL_SUPPORT = None
try:
from PIL import Image, ImageDraw, ImageFont
PIL_SUPPORT = True
except:
PIL_SUPPORT = False
cm = []
coords = []
CITIES = 100
WIDTH = 1024
HEIGHT = 768
LAST_SCORE = -1
def cartesian_matrix(coords):
""" A distance matrix """
matrix={}
for i,(x1,y1) in enumerate(coords):
for j,(x2,y2) in enumerate(coords):
dx, dy = x1-x2, y1-y2
dist=sqrt(dx*dx + dy*dy)
matrix[i,j] = dist
return matrix
def tour_length(matrix, tour):
""" Returns the total length of the tour """
total = 0
t = tour.getInternalList()
for i in range(CITIES):
j = (i+1)%CITIES
total += matrix[t[i], t[j]]
return total
def write_tour_to_img(coords, tour, img_file):
""" The function to plot the graph """
padding=20
coords=[(x+padding,y+padding) for (x,y) in coords]
maxx,maxy=0,0
for x,y in coords:
maxx, maxy = max(x,maxx), max(y,maxy)
maxx+=padding
maxy+=padding
img=Image.new("RGB",(int(maxx),int(maxy)),color=(255,255,255))
font=ImageFont.load_default()
d=ImageDraw.Draw(img);
num_cities=len(tour)
for i in range(num_cities):
j=(i+1)%num_cities
city_i=tour[i]
city_j=tour[j]
x1,y1=coords[city_i]
x2,y2=coords[city_j]
d.line((int(x1),int(y1),int(x2),int(y2)),fill=(0,0,0))
d.text((int(x1)+7,int(y1)-5),str(i),font=font,fill=(32,32,32))
for x,y in coords:
x,y=int(x),int(y)
d.ellipse((x-5,y-5,x+5,y+5),outline=(0,0,0),fill=(196,196,196))
del d
img.save(img_file, "PNG")
print "The plot was saved into the %s file." % (img_file,)
def G1DListTSPInitializator(genome, **args):
""" The initializator for the TSP """
lst = [i for i in xrange(genome.getListSize())]
random.shuffle(lst)
genome.setInternalList(lst)
# This is to make a video of best individuals along the evolution
# Use mencoder to create a video with the file list list.txt
# mencoder mf://@list.txt -mf w=400:h=200:fps=3:type=png -ovc lavc
# -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o output.avi
#
def evolve_callback(ga_engine):
global LAST_SCORE
if ga_engine.getCurrentGeneration() % 100 == 0:
best = ga_engine.bestIndividual()
if LAST_SCORE != best.getRawScore():
write_tour_to_img( coords, best, "tspimg/tsp_result_%d.png" % ga_engine.getCurrentGeneration())
LAST_SCORE = best.getRawScore()
return False
def main_run():
global cm, coords, WIDTH, HEIGHT
coords = [(random.randint(0, WIDTH), random.randint(0, HEIGHT))
for i in xrange(CITIES)]
cm = cartesian_matrix(coords)
genome = G1DList.G1DList(len(coords))
genome.evaluator.set(lambda chromosome: tour_length(cm, chromosome))
genome.crossover.set(Crossovers.G1DListCrossoverEdge)
genome.initializator.set(G1DListTSPInitializator)
# 3662.69
ga = GSimpleGA.GSimpleGA(genome)
ga.setGenerations(200000)
ga.setMinimax(Consts.minimaxType["minimize"])
ga.setCrossoverRate(1.0)
ga.setMutationRate(0.02)
ga.setPopulationSize(80)
# This is to make a video
ga.stepCallback.set(evolve_callback)
# 21666.49
import psyco
psyco.full()
ga.evolve(freq_stats=500)
best = ga.bestIndividual()
if PIL_SUPPORT:
write_tour_to_img(coords, best, "tsp_result.png")
else:
print "No PIL detected, cannot plot the graph !"
if __name__ == "__main__":
main_run()
|
josephlewis42/personal_codebase
|
python/OpenCalc/Lib/Code/Functions/Trig.py
|
'''
Basic Trig Stuff
@Author = <NAME>
@Date = Friday, Feb. 19, 2010
==Changelog==
2010-2-25 - Added the boolean that changes if you want radians or degrees
2010-02-27 - Fixed a problem with the basic trigonometric functions that was
causing improper numbers to be returned. Also added the functions that set the
want_deg variable, so the user can do this from now on easily.s
'''
import math
PI = math.pi
pie = "()()() \n|\\ 3\n\\ \\ .\n \\ \\ 1\n \\_\\4"
PIE = pie
want_deg = True #Used to tell the system to use radians or degrees
#Conversion
def useradians():
global want_deg
want_deg = False
return "Now using Radians"
def usedegrees():
global want_deg
want_deg = True
return "Now using Degrees"
#Basic
def sin(num):
if want_deg == True:
return math.sin(torad(num))
else:
return math.sin(num)
def cos(num):
if want_deg == True:
return math.cos(torad(num))
else:
return math.cos(num)
def tan(num):
if want_deg == True:
return math.tan(torad(num))
else:
return math.tan(num)
#Arc
def asin(num):
if want_deg == True:
return math.asin(torad(num))
else:
return math.asin(num)
def acos(num):
if want_deg == True:
return math.acos(torad(num))
else:
return math.acos(num)
def atan(num):
if want_deg == True:
return math.atan(torad(num))
else:
return math.atan(num)
#Conversions
def todeg(num):
return num*(180.0/PI)
def torad(num):
return num*(PI/180.0)
|
josephlewis42/personal_codebase
|
python/randall/alife_randall_checkout/ai_webserver/organs.py
|
# organs.py
#
# Copyright 2011 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
self.send_200()
if not SESSION or 'login' not in SESSION.keys() or not SESSION['login']:
self.wfile.write("You are not logged in...<script type='text/javascript'>window.location = 'login.py'</script>")
else:
if 'reload' in QUERY_DICT.keys():
#Handle AJAX query.
page = '''<h3>Organs:</h3><div id="progresscontainer">'''
try:
w = SESSION['world']
a = SESSION['actor']
for item in w[a].my_body:
page += item.name + ":<br />"
#Set colors for different values (so the humans can easily see)
color = "#0D5995"
if item.value >= 25 and item.value < 50:
color = "#00FF00"
if item.value >= 50 and item.value < 75:
color = "#FFA500"
if item.value >= 75:
color = "#A52A2A"
page += '''<div class='progressbar'>
<div class='progressbartext'>%i%%</div>
<div class='progressbarinner' style='width:%i%%; background-color:%s;'></div>
</div>
''' % (int(item.value), int(item.value),color)
page += "<br /></div>"
self.wfile.write(page)
except KeyError, e:
self.wfile.write("Error: Couldn't find the key specified: %s" %(e))
except Exception, e:
self.wfile.write("Error: %s" %(e))
#Handle page query.
else:
page = '''
<html>
<head>
<script type="text/javascript" src="assets/jquery.js"></script>
<script type="text/javascript" src="assets/reloader.js"></script>
<link rel="StyleSheet" href="assets/login.css" type="text/css" />
</head>
<body onLoad="javascript:Update(2000, 'body', 'organs.py?reload=true');" class="widget">
Loading...
</body>
</html>
'''
self.wfile.write(page)
|
josephlewis42/personal_codebase
|
python/gamebot/codescraper.py
|
#!/usr/bin/python
'''
Copyright (c) 2010 <NAME> <<EMAIL>>
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 re
import urllib2
from xml.sax.saxutils import unescape as xmlunescape
numnones = 0
def unescape(string):
'''Unescape the & escapes in html, like " returns a string '''
string = string.replace(""", "\"") #Not done by xml lib
string = xmlunescape(string)
return string
def remove_HTML_tags(text):
'''Removes html tags from a supplied string.
Warning: This is accomplished using regular expressions that simply cut
out all text in between and including less than and greater than
characters.
'''
regex_html = re.compile(r'<.*?>')
return regex_html.sub('', text)
def fetch_page(url):
'''Returns the html for the webpage at the supplied url.'''
hdr = {'User-Agent': 'Mozilla/5.0 Gecko/20100101 Firefox/4.0',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language':'en-us,en;q=0.5',
'Accept-Encoding':'none',
'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Keep-Alive':'115',
'Connection':'keep-alive'}
request = urllib2.Request(url, None, hdr)
page = urllib2.urlopen(request)
pagetext = ""
for line in page:
pagetext += line
return pagetext
def url_content_type(url):
from urlparse import urlparse
o = urlparse(url)
import httplib
conn = httplib.HTTPConnection(o.netloc)
conn.request("HEAD", o.path)
res = conn.getresponse()
for key, value in res.getheaders():
if key.lower() == "content-type":
return value
def return_between(first_tag, second_tag, text):
'''Returns an array of the text between the delimiters given. All text
between the end and beginning delimiters will be discarded.
Arguments:
first_tag -- The tag to begin text harvesting. (string)
second_tag -- The tag to end text harvesting. (string)
text -- The string in which the tags are to be found. (string)
'''
basic_split = text.split(first_tag)
#select only the sections which contain the close tags, discard the rest.
second_split = []
for i in basic_split:
if second_tag in i:
second_split.append(i)
#Cut out the text before the close tag
between = []
for line in second_split:
value, end = line.split(second_tag, 1)
between.append(value)
return between
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v2/rtt.py
|
<filename>covid19_forecaster/v2/rtt.py
import numpy as np
import pandas as pd
from .. import DATA_DIR
from ..core import RevenueForecast
from ..forecasters import NoBaselineForecasterBySector
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class RealtyTransferTaxForecast(NoBaselineForecasterBySector, RevenueForecast):
"""Realty transfer tax revenue forecast."""
ASSUMPTIONS = {}
def __init__(self, fresh=False):
# Load the assumptions
path = DATA_DIR / "models" / "v2" / "RTT Analysis.xlsx"
skiprows = {"moderate": 5, "severe": 15}
for scenario in ["moderate", "severe"]:
# Load the data
data = pd.read_excel(
path,
nrows=2,
header=0,
index_col=0,
usecols="A,D:I",
sheet_name="FY21-FY22 RTT Scenarios",
skiprows=skiprows[scenario],
)
# Convert to keys --> sectors and values --> revenue
self.ASSUMPTIONS[scenario] = {}
for k in data.index:
self.ASSUMPTIONS[scenario][k] = data.loc[k].tolist()
super().__init__(
tax_name="rtt",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
ignore_sectors=False,
agg_after_fitting=True,
fit_kwargs={"seasonality_mode": "additive"},
flat_growth=True,
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v1/rtt.py
|
<filename>covid19_forecaster/v1/rtt.py
import numpy as np
from ..core import RevenueForecast
from ..forecasters import DefaultForecaster
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class RealtyTransferTaxForecast(DefaultForecaster, RevenueForecast):
"""Realty transfer tax revenue forecast."""
ASSUMPTIONS = {
"moderate": np.concatenate(
[[0, 0.25, 0.5], np.repeat(0.1, 6), np.repeat(0.05, 12)]
),
"severe": np.concatenate(
[[0, 0.25, 0.5], np.repeat(0.25, 6), np.repeat(0.1, 12)]
),
}
def __init__(self, fresh=False):
super().__init__(
tax_name="rtt",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
ignore_sectors=True,
fit_kwargs={"seasonality_mode": "multiplicative"},
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v2/__init__.py
|
# Forecast range
FORECAST_START = "2021-01-01"
FORECAST_STOP = "2022-06-30"
# Baseline range
BASELINE_START = "2013-07-01"
BASELINE_STOP = "2020-03-31"
# Forecast frequency
FREQ = "Q"
# Scenario names
SCENARIOS = ["moderate", "severe"]
from ..core import ScenarioComparison, ScenarioForecast
from .amusement import AmusementTaxForecast
from .birt import BIRTForecast
from .npt import NPTForecast
from .parking import ParkingTaxForecast
from .rtt import RealtyTransferTaxForecast
from .sales import SalesTaxForecast
from .soda import SodaTaxForecast
from .wage import WageTaxForecast
TAXES = [
AmusementTaxForecast,
BIRTForecast,
NPTForecast,
ParkingTaxForecast,
RealtyTransferTaxForecast,
SalesTaxForecast,
SodaTaxForecast,
WageTaxForecast,
]
|
PhiladelphiaController/covid19-forecaster
|
setup.py
|
from setuptools import setup, find_packages
import re
from pathlib import Path
PACKAGE_NAME = "covid19_forecaster"
HERE = Path(__file__).parent.absolute()
def find_version(*paths: str) -> str:
with HERE.joinpath(*paths).open("tr") as fp:
version_file = fp.read()
version_match = re.search(
r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M
)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
DESCRIPTION = (
"Forecasting the revenue impact of COVID-19"
" on the City of Philadelphia's finances"
)
setup(
name=PACKAGE_NAME,
version=find_version(PACKAGE_NAME, "__init__.py"),
author="<NAME>",
maintainer="<NAME>",
maintainer_email="<EMAIL>",
packages=find_packages(),
description=DESCRIPTION,
license="MIT",
python_requires=">=3.6",
install_requires=[
"pandas",
"fbprophet",
"phila-style",
"matplotlib",
"openpyxl",
],
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/baseline/sales.py
|
<filename>covid19_forecaster/baseline/sales.py
"""Transform sales data by splitting between City and School District"""
import pandas as pd
from ..utils import get_fiscal_year
# School district gets $120M
MAX_DISTRICT_AMOUNT = 120e6
def get_sales_fiscal_year(r: pd.Series) -> int:
"""
July/Aug are associated with the previous fiscal year
due to the accrual period.
"""
if r["month"] in [7, 8]:
return r["fiscal_year"] - 1
else:
return r["fiscal_year"]
def _get_city_sales_only(df: pd.DataFrame) -> pd.DataFrame:
"""
Internal function to extract city sales data.
Notes
-----
There must be "month", "total", and "fiscal_year" columns.
Parameters
----------
df :
sales data in tidy format
Returns
-------
out :
a copy of the input data, with
"""
# Make sure our columns exist
assert all(col in df.columns for col in ["month", "fiscal_year", "total"])
# Create a copy and add the fiscal year for sales calculation
X = df.copy()
X["fiscal_year_sales"] = df.apply(get_sales_fiscal_year, axis=1)
def add_sales_total(grp):
"""
Keep track of school district portion and allocate.
Strategy:
- Start in September
- Collections get split 50/50, until District hits cap
- City gets 100% of remaining months, until new fiscal year
"""
cnt = 0
out = []
months = [9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8]
for month in months:
# Get data for this month
row = grp.query(f"month == {month}").copy()
if len(row):
# Sum up total
total = row["total"].sum()
school_district_fraction = 0.0
if (
row.iloc[0]["fiscal_year_sales"] >= 2015
and cnt < MAX_DISTRICT_AMOUNT
):
school_district_fraction = 0.5
school_district = total * school_district_fraction
if cnt + school_district > 120e6:
school_district_fraction = (120e6 - cnt) / total
# Add the city
row["total"] = row["total"] * (1 - school_district_fraction)
out.append(row)
# Add to the cumulative count
cnt += total * school_district_fraction
out = pd.concat(out, axis=0, ignore_index=True)
return out
# Perform the calculation and return
out = X.groupby("fiscal_year_sales").apply(add_sales_total)
return out.drop(labels=["fiscal_year_sales"], axis=1).droplevel(
axis=0, level=0
)
def get_city_sales_only(X):
"""
Return a data frame that only includes the City portion of the
sales tax.
School District receives 50% of monthly collections until the
cap ($120M) is reached.
This gives the City sales data a strong seasonality, with peaks
in the summer months.
"""
# Set up
R = X.copy()
has_sectors = X.columns.nlevels > 1
# Add a fake column level for continuity of cases
if not has_sectors and len(X.columns) != 1:
R.columns = pd.MultiIndex.from_product([["total"], R.columns])
has_sectors = True
# Get the "total"
R = R["total"].reset_index()
# Using sectors
if has_sectors:
R = R.melt(id_vars=["date"], value_name="total", var_name="sector")
# Put into tidy format
R = R.assign(
fiscal_year=lambda df: df.date.apply(get_fiscal_year),
month=lambda df: df.date.dt.month,
)
# Do the allocation
R = _get_city_sales_only(R)
# Postprocess
if has_sectors:
# Pivot back
R = R.pivot_table(index="date", values="total", columns="sector")
R.columns = pd.MultiIndex.from_product([["total"], R.columns])
# Add upper and lower
if "upper" in X.columns:
out = [R]
for col in ["upper", "lower"]:
tmp = X[col] / X["total"] * R["total"]
tmp.columns = pd.MultiIndex.from_product([[col], tmp.columns])
out.append(tmp)
# Combine along column axis
out = pd.concat(out, axis=1).sort_index(axis=1, level=1)
else:
out = R
else:
if "upper" in X.columns:
out = R[["date", "total"]]
for col in ["upper", "lower"]:
out[col] = X[col] / X["total"] * R["total"]
out = out.set_index("date")
else:
out = R.set_index("date")[["total"]]
if has_sectors and X.columns.nlevels == 1:
out = out["total"]
return out
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v1/npt.py
|
from ..core import RevenueForecast
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class NPTForecast(RevenueForecast):
"""Net profits tax revenue forecast."""
ASSUMPTIONS = {
"moderate": {2020: 0.05, 2021: 0.1},
"severe": {2020: 0.1, 2021: 0.15},
}
def __init__(self, fresh=False):
super().__init__(
tax_name="npt",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
fit_kwargs={"seasonality_mode": "additive"},
)
def get_forecast_value(self, date, baseline, scenario):
"""Return the forecasted decline."""
assert scenario in ["moderate", "severe"]
decline = self.ASSUMPTIONS[scenario][date.year]
return baseline * (1 - decline)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/io.py
|
<reponame>PhiladelphiaController/covid19-forecaster<filename>covid19_forecaster/io.py<gh_stars>1-10
import calendar
import pandas as pd
from phl_budget_data.clean import (
load_birt_collections_by_sector,
load_city_collections,
load_rtt_collections_by_sector,
load_sales_collections_by_sector,
load_wage_collections_by_sector,
)
from . import DATA_DIR
MONTH_NAMES = [x.lower() for x in calendar.month_abbr]
def load_monthly_sales_tax_data():
"""Load monthly sales tax collections."""
# Load the raw data
sales = pd.read_excel(
DATA_DIR / "taxes" / "monthly-sales-data.xlsx",
sheet_name="Sales",
usecols="B,U:AB",
skiprows=12,
nrows=12,
index_col=0,
)
# Format it
sales = (
sales.melt(
ignore_index=False, var_name="fiscal_year", value_name="total"
)
.rename_axis("month_name", axis=0)
.reset_index()
.assign(
fiscal_year=lambda df: df.fiscal_year.str.slice(2).astype(int),
month_name=lambda df: df.month_name.str.lower().str.slice(0, 3),
month=lambda df: df.month_name.apply(
lambda x: MONTH_NAMES.index(x)
),
fiscal_month=lambda df: ((df.month - 7) % 12 + 1),
year=lambda df: df.apply(
lambda r: r["fiscal_year"]
if r["month"] < 7
else r["fiscal_year"] - 1,
axis=1,
),
date=lambda df: pd.to_datetime(
df["month"].astype(str) + "/" + df["year"].astype(str)
),
)
.dropna(subset=["total"])
)
return sales
def load_tax_rates(tax: str) -> pd.DataFrame:
"""Load the tax rates for the specified tax."""
# Check the allowed values
allowed = ["birt", "npt", "parking", "rtt", "sales", "wage"]
if tax.lower() not in allowed:
raise ValueError(f"Allowed values are: {allowed}")
# Load
path = DATA_DIR / "rates" / f"{tax}.csv"
rates = pd.read_csv(path, index_col=0)
if tax == "wage":
rates["rate"] = (
0.6 * rates["rate_resident"] + 0.4 * rates["rate_nonresident"]
)
elif tax == "npt":
rates["rate"] = (
0.515 * rates["rate_resident"] + 0.485 * rates["rate_nonresident"]
)
elif tax == "birt":
rates["rate"] = (
0.75 * rates["rate_net_income"]
+ 0.25 * rates["rate_gross_receipts"]
)
# index is "fiscal_year" and one column "rate"
return rates[["rate"]]
def load_data_by_sector(kind: str, use_subsectors=False) -> pd.DataFrame:
"""
Load data for various taxes by sector.
Parameters
----------
kind : str
load sector info for BIRT, sales tax, or wage tax
main_sectors_only : bool, optional
if True, only return the main sectors
Returns
-------
DataFrame :
sector info for the requested tax
"""
allowed = ["birt", "sales", "wage", "rtt"]
if kind not in allowed:
raise ValueError(f"Allowed values are: {allowed}")
LOADERS = {
"birt": load_birt_collections_by_sector,
"sales": load_sales_collections_by_sector,
"wage": load_wage_collections_by_sector,
"rtt": load_rtt_collections_by_sector,
}
# Load
df = LOADERS[kind]()
# Get the main sectors
if not use_subsectors:
out = df.query("parent_sector.isnull()").copy()
# Use sub-sectors
else:
parent_sectors = df["parent_sector"].unique()
out = df.query("sector not in @parent_sectors").copy()
if kind == "birt":
out["fiscal_year"] = out["tax_year"]
elif kind == "rtt":
out = out.query("sector != 'Unclassified'")
return out
def load_monthly_collections(tax_name) -> pd.DataFrame:
"""
Load data for monthly tax revenue collections
Returns
-------
DataFrame :
the data for collections by month
"""
if tax_name == "sales":
return load_monthly_sales_tax_data()
# Load all the data
df = load_city_collections().query("kind == 'Tax'")
# Combine wage + earnings
if tax_name == "wage":
# Combine wage + earnings
tax_names = ["wage", "earnings"]
df = df.query("name in @tax_names")
# Do the total
out = df.groupby(
[
"fiscal_year",
"month_name",
"month",
"fiscal_month",
"year",
"date",
],
as_index=False,
)["total"].sum()
else:
# Fix the tax names for some
if tax_name == "rtt":
tax_name = "real_estate_transfer"
elif tax_name == "npt":
tax_name = "net_profits"
# Query
out = df.query(f"name == '{tax_name}'").drop(
labels=["kind", "name"], axis=1
)
if tax_name == "soda":
out = out.query("date >= '2017-04-01'")
elif tax_name in ["birt", "net_profits"]:
# SOURCE: june 2020 collections report
if tax_name == "birt":
accrual = 261024311
else:
accrual = 10737282
# Subtract from July 2020
sel = (out["month"] == 7) & (out["year"] == 2020)
out.loc[sel, "total"] -= accrual
# Add to April 2020
sel = (out["month"] == 4) & (out["year"] == 2020)
out.loc[sel, "total"] += accrual
return out
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v1/parking.py
|
<gh_stars>1-10
import numpy as np
from ..core import RevenueForecast
from ..forecasters import DefaultForecaster
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class ParkingTaxForecast(DefaultForecaster, RevenueForecast):
"""Parking tax revenue forecast."""
ASSUMPTIONS = {
"moderate": np.concatenate(
[
np.repeat(0.3, 3),
np.repeat(0.15, 3),
np.repeat(0.1, 3),
np.repeat(0.05, 12),
]
),
"severe": np.concatenate(
[
np.repeat(0.5, 3),
np.repeat(0.3, 3),
np.repeat(0.15, 3),
np.repeat(0.1, 3),
np.repeat(0.05, 9),
]
),
}
def __init__(self, fresh=False):
# Initialize the underlying forecast class
super().__init__(
tax_name="parking",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
fit_kwargs={"seasonality_mode": "multiplicative"},
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v2/sales.py
|
<reponame>PhiladelphiaController/covid19-forecaster
import numpy as np
from ..core import RevenueForecast
from ..forecasters import SectorForecaster
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class SalesTaxForecast(SectorForecaster, RevenueForecast):
"""Sales tax revenue forecast."""
GROUPS = {
"impacted": [
"Hotels",
"Restaurants, bars, concessionaires and caterers",
"Motor Vehicle Sales Tax",
]
}
ASSUMPTIONS = {
"moderate": {
"impacted": [0.25, 0.20, 0.15, 0.10, 0.05, 0.05],
"default": [0.03, 0.02, 0.01, 0.01, 0.01, 0.0],
},
"severe": {
"impacted": [0.30, 0.30, 0.25, 0.2, 0.15, 0.125],
"default": [0.03, 0.03, 0.02, 0.02, 0.01, 0.01],
},
}
def __init__(
self, fresh=False,
):
super().__init__(
tax_name="sales",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
ignore_sectors=False,
agg_after_fitting=False,
fit_kwargs={"seasonality_mode": "multiplicative"},
flat_growth=True,
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v2/npt.py
|
from ..core import RevenueForecast
from ..forecasters import DefaultForecaster
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class NPTForecast(DefaultForecaster, RevenueForecast):
"""Net profits tax revenue forecast."""
ASSUMPTIONS = {
"moderate": [0.4, 0.4, 0.0, -0.02, -0.02, -0.05],
"severe": [0.6, 0.6, 0.02, 0.02, 0.02, 0.03],
}
def __init__(self, fresh=False):
super().__init__(
tax_name="npt",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
agg_after_fitting=False,
fit_kwargs={"seasonality_mode": "additive"},
flat_growth=True,
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/run.py
|
import argparse
import shutil
from pathlib import Path
from typing import List, Union
import click
import openpyxl
import pandas as pd
from loguru import logger
from matplotlib import pyplot as plt
from . import DATA_DIR, v1, v2
from .core import RevenueForecast, ScenarioComparison, ScenarioForecast
from .utils import get_fiscal_year
def groupby_fiscal_year(df):
"""Group the input data by the "fiscal_year" column"""
# Re-index the input data by fiscal year
X = df.copy()
X.index = pd.Index(
[get_fiscal_year(dt) for dt in X.index], name="fiscal_year"
)
# Group by and sum
return X.groupby("fiscal_year").sum()
def get_scenarios_with_actuals(
summary, by_fiscal_year=False, scenario_start_date="2021-01"
):
"""Get scenarios combined with actuals until the forecast."""
# Actuals
actuals = summary.xs("actual", level=1, axis=1).dropna()
# Moderate
moderate = (
summary.loc[scenario_start_date:]
.xs("moderate", level=1, axis=1)
.dropna()
)
moderate = pd.concat([actuals, moderate], axis=0)
# Severe
severe = (
summary.loc[scenario_start_date::]
.xs("severe", level=1, axis=1)
.dropna()
)
severe = pd.concat([actuals, severe], axis=0)
# Group by fiscal year?
if by_fiscal_year:
moderate = groupby_fiscal_year(moderate).T
severe = groupby_fiscal_year(severe).T
return moderate, severe
def save_scenario_results(
scenarios: ScenarioComparison, filename: Union[str, Path]
):
"""Save the scenario results to the specified path."""
if isinstance(filename, str):
filename = Path(filename)
# Check parent directory
if not filename.parent.exists():
filename.parent.mkdir()
# ---------------------------------------------------
# Calculation #1: Get the normalized declines
# ---------------------------------------------------
declines = scenarios.get_normalized_summary()
declines = declines.T.loc["2020":].T
# ---------------------------------------------------
# Calculation #2: Get the FY totals declines
# ---------------------------------------------------
r = scenarios.get_summary(start_date="07-01-2014").T
moderate_fy_totals, severe_fy_totals = get_scenarios_with_actuals(
r, by_fiscal_year=True
)
# Copy the template
template_path = DATA_DIR / "templates" / "covid-budget-scenarios-v2.xlsx"
shutil.copy(template_path, filename)
# Open the workbook
book = openpyxl.load_workbook(filename)
# Verify sheets are deleted
sheets = [
"Normalized Declines (Raw)",
"Optimistic (Raw)",
"Pessimistic (Raw)",
]
for sheet in sheets:
if sheet in book.sheetnames:
del book[sheet]
book.save(filename)
# Open and save the calculations
with pd.ExcelWriter(filename, engine="openpyxl", mode="a") as writer:
# Save the declines
declines.to_excel(writer, sheet_name=sheets[0])
# FY totals
(moderate_fy_totals / 1e3)[[2020, 2021, 2022]].to_excel(
writer, sheet_name=sheets[1]
)
(severe_fy_totals / 1e3)[[2020, 2021, 2022]].to_excel(
writer, sheet_name=sheets[2]
)
def _ensure_data_frame(X):
out = X.copy()
if isinstance(X, pd.Series):
out = out.to_frame()
return out
def save_model_outputs(scenarios: ScenarioComparison, path: Union[str, Path]):
"""Save the model outputs."""
if isinstance(path, str):
path = Path(path)
# Check directory
if not path.exists():
path.mkdir()
# Set up output directories
actual_dir = path / "actuals"
baseline_dir = path / "baseline"
forecast_dir = path / "forecasts"
for d in [actual_dir, baseline_dir, forecast_dir]:
if not d.exists():
d.mkdir()
# Loop over each scenario
for i, scenario in enumerate(scenarios.scenario_names):
# Get this scenario
this_scenario = scenarios[scenario]
# Loop over each tax
for tax_name in this_scenario.taxes:
# Get this tax
tax = this_scenario[tax_name]
# Save Actuals and Baseline
if i == 0:
# The baseline forecast
b = tax.baseline_forecast
# Actuals
b.actual_revenue_.to_csv(
actual_dir / f"{tax_name}-revenue.csv"
)
b.actual_tax_base_.to_csv(
actual_dir / f"{tax_name}-tax-base.csv"
)
# Baseline
_ensure_data_frame(b.forecasted_revenue_["total"]).to_csv(
baseline_dir / f"{tax_name}-revenue.csv"
)
_ensure_data_frame(b.forecasted_tax_base_["total"]).to_csv(
baseline_dir / f"{tax_name}-tax-base.csv"
)
for scenario in ["moderate", "severe"]:
# Run the forecast
f = _ensure_data_frame(tax.run_forecast(scenario))
f.to_csv(forecast_dir / f"{tax_name}-{scenario}-revenue.csv")
# Save the figure too
tax.plot()
plt.savefig(
forecast_dir / f"{tax_name}-{scenario}-revenue.png"
)
plt.close()
def run_scenarios(
taxes: List[RevenueForecast], fresh=False, scenarios=["moderate", "severe"]
):
"""Run the scenarios for the input taxes."""
results = {}
# Run all of the scenarios
for scenario in scenarios:
logger.info(f"Running scenario '{scenario}'")
forecasts = []
for cls in taxes:
# Initialize and log
tax = cls(fresh=fresh)
logger.info(f" Running forecast for '{tax.tax_name}'")
# Run the forecast
tax.run_forecast(scenario)
# Save it
forecasts.append(tax)
# Save a scenario forecast object
results[scenario] = ScenarioForecast(*forecasts)
return ScenarioComparison(results)
def run_and_save_scenarios(
taxes: List[RevenueForecast],
path: Union[str, Path],
fresh=False,
clean=False,
scenarios=["moderate", "severe"],
):
"""Run the scenarios and save the results."""
# Run
scenarios = run_scenarios(taxes, fresh=fresh, scenarios=scenarios)
# Make sure we have a Path object
if isinstance(path, str):
path = Path(path)
# Remove directory?
out_dir = path.parent
if out_dir.exists() and clean:
shutil.rmtree(out_dir)
# Make sure it exists
if not out_dir.exists():
out_dir.mkdir()
# Save the scenarios
save_scenario_results(scenarios, path)
# Save the model inputs
save_model_outputs(scenarios, out_dir)
@click.command()
@click.argument(
"output_dir", type=Path,
)
@click.option(
"--clean",
is_flag=True,
help="Whether to remove the output directory first.",
)
@click.option(
"--fresh",
is_flag=True,
help="Whether to create fresh baselines when modeling.",
)
def main(output_dir, clean=False, fresh=False):
"""Run and save the March 2021 model forecast."""
# Get the config for version #2
taxes = v2.TAXES
scenarios = v2.SCENARIOS
# Run and save
path = output_dir / f"covid-budget-impact-{version}.xlsx"
run_and_save_scenarios(
taxes, path, fresh=fresh, clean=clean, scenarios=scenarios
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v2/soda.py
|
<reponame>PhiladelphiaController/covid19-forecaster
import numpy as np
from ..core import RevenueForecast
from ..forecasters import DefaultForecaster
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class SodaTaxForecast(DefaultForecaster, RevenueForecast):
"""Soda tax revenue forecast."""
ASSUMPTIONS = {
"moderate": [0.1, 0.1, 0.05, 0.05, 0.03, 0.01],
"severe": [0.15, 0.15, 0.1, 0.075, 0.05, 0.03],
}
def __init__(self, fresh=False):
super().__init__(
tax_name="soda",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
agg_after_fitting=True,
fit_kwargs={"seasonality_mode": "additive"},
flat_growth=True,
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v1/__init__.py
|
<reponame>PhiladelphiaController/covid19-forecaster
# Forecast range
FORECAST_START = "2020-04-01"
FORECAST_STOP = "2021-12-31"
# Baseline range
BASELINE_START = "2013-07-01"
BASELINE_STOP = "2020-03-31"
# Forecast frequency
FREQ = "M"
# Scenario names
SCENARIOS = ["moderate", "severe"]
from loguru import logger
from ..core import ScenarioComparison, ScenarioForecast
from .amusement import AmusementTaxForecast
from .birt import BIRTForecast
from .npt import NPTForecast
from .parking import ParkingTaxForecast
from .rtt import RealtyTransferTaxForecast
from .sales import SalesTaxForecast
from .soda import SodaTaxForecast
from .wage import WageTaxForecast
TAXES = [
AmusementTaxForecast,
BIRTForecast,
NPTForecast,
ParkingTaxForecast,
RealtyTransferTaxForecast,
SalesTaxForecast,
SodaTaxForecast,
WageTaxForecast,
]
def run_scenarios(fresh=False):
"""Run the scenarios."""
scenarios = {}
# Run all of the scenarios
for scenario in SCENARIOS:
logger.info(f"Running scenario '{scenario}'")
forecasts = []
for cls in TAXES:
# Initialize and log
tax = cls(fresh=fresh)
logger.info(f" Running forecast for '{tax.tax_name}'")
# Run the forecast
tax.run_forecast(scenario)
# Save it
forecasts.append(tax)
# Save a scenario forecast object
scenarios[scenario] = ScenarioForecast(*forecasts)
comp = ScenarioComparison(scenarios)
# comp.save()
return comp
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/utils.py
|
<filename>covid19_forecaster/utils.py
import hashlib
import json
import numpy as np
import pandas as pd
def aggregate_to_quarters(df, cols=None, key=None):
"""Aggregate monthly data to quarters."""
grouped = df.groupby(pd.Grouper(freq="QS", key=key))
if cols is not None:
out = grouped[cols].sum()
else:
out = grouped.sum()
# Set quarters w/o three to missing
size = grouped.size()
missing = size != 3
out.loc[missing, :] = np.nan
return out.dropna(axis=0, how="all")
def get_unique_id(d, n=5):
"""Generate a unique hash string from a dictionary."""
unique_id = hashlib.sha1(
json.dumps(d, sort_keys=True).encode()
).hexdigest()
return unique_id[:n]
def get_fiscal_year(dt):
"""Get fiscal year from a date."""
if dt.month >= 7:
return dt.year + 1
else:
return dt.year
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/baseline/transformers.py
|
import logging
logger = logging.getLogger("fbprophet.plot")
logger.setLevel(logging.CRITICAL)
from dataclasses import dataclass, field
from typing import Optional
import numpy as np
import pandas as pd
from fbprophet import Prophet
from sklearn.base import TransformerMixin
from .. import io
from ..utils import get_fiscal_year
@dataclass
class BaselineForecaster(TransformerMixin):
"""
Transformer to produce a baseline forecast from actuals.
"""
fit_kwargs: Optional[dict] = field(default_factory=dict)
fit_start_date: Optional[str] = None
fit_stop_date: Optional[str] = "2020-03-31"
forecast_stop_date: Optional[str] = "2022-06-30"
def fit(self, data):
"""
Fit the data.
Notes
-----
Data must have a Datetime index.
"""
# Do some checks
if not isinstance(data.index, pd.DatetimeIndex):
raise ValueError("Index for input data should be a DatetimeIndex")
# Set freq
self.freq_ = data.index.inferred_freq
if self.freq_ is None:
raise ValueError("Freq of input datetime index cannot be None")
return self
def transform(self, data):
"""
Run the forecast for each column in data.
"""
# Trim the fit period
if self.fit_start_date is not None:
data = data.loc[self.fit_start_date :]
if self.fit_stop_date is not None:
data = data.loc[: self.fit_stop_date]
# Get the fit kwargs
fit_kwargs = {
"daily_seasonality": False,
"weekly_seasonality": False,
"n_changepoints": min(int(0.7 * len(data)), 25),
**self.fit_kwargs,
}
# Fit each variable
out = []
for col in data.columns:
# Format data for Prophet
df = (
data[col]
.rename_axis("ds")
.reset_index()
.rename(columns={col: "y"})
.sort_values("ds")
)
# Initialize and fit the model
model = Prophet(**fit_kwargs)
model.fit(df)
# Get the forecast period
periods = (
pd.to_datetime(self.forecast_stop_date).to_period(
self.freq_[0]
)
- df["ds"].max().to_period(self.freq_[0])
).n
future = model.make_future_dataframe(
periods=periods, freq=self.freq_
)
# Forecast
forecast = model.predict(future)
# Add the yearly term too (in absolute units)
forecast["yearly"] *= forecast["trend"]
# Keep total & uncertainty levels
forecast = (
forecast[
[
"ds",
"yhat",
"yhat_lower",
"yhat_upper",
"yearly",
"trend",
]
]
.rename(
columns={
"ds": "date",
"yhat": "total",
"yhat_lower": "lower",
"yhat_upper": "upper",
}
)
.set_index("date")
)
# If we're doing this by sector, we need to add another
# level to the column index
if len(data.columns) > 1:
forecast.columns = pd.MultiIndex.from_product(
[forecast.columns, [col],]
)
# Save
out.append(forecast)
return pd.concat(out, axis=1)
@dataclass
class RevenueToTaxBase(TransformerMixin):
"""Convert from revenue to tax base."""
tax_name: str
def __post_init__(self):
self.rates = None
try:
self.rates = io.load_tax_rates(self.tax_name)
except:
self.rates = None
def fit(self, X, y=None):
"""Fit the data."""
return self
def _transform(self, X, inverse=False):
"""Internal function to do transformation."""
# No transformation needed
if self.rates is None:
return X
# Start from a copy
fiscal_years = [get_fiscal_year(dt) for dt in X.index]
out = X.copy()
# Loop over all of the columns (columns can be a multi-index here)
for col in out.columns:
# Get the column and index by the fiscal years
df = X[col].copy()
df.index = fiscal_years
# Do the transformation (pandas will align the indices)
if not inverse:
rescaled = (df / self.rates["rate"]).dropna()
else:
rescaled = (df * self.rates["rate"]).dropna()
# Reset the index back to the original
rescaled.index = X.index
# And save it
out[col] = rescaled
return out
def transform(self, X):
"""Do the transformation from revenue to tax base."""
return self._transform(X)
def inverse_transform(self, X):
"""Do the inverse transformation from revenue to tax base."""
return self._transform(X, inverse=True)
@dataclass
class DisaggregateCollectionsBySector:
"""
Given monthly total collections, disaggregate by industry, using
historical data for collections by industry.
"""
sector_data: pd.DataFrame
def fit_transform(self, data, **kwargs):
"""Convenience function"""
# Fit
self.fit(data, **kwargs)
# Transform
return self.transform(data, **kwargs)
def fit(self, data, key="sector"):
"""Fit the data."""
# Check columns exist
for col in ["fiscal_year", key]:
if col not in self.sector_data.columns:
raise ValueError(
f"Missing column '{col}' in input sector data"
)
# Determine how to group
self.time_cols_ = ["fiscal_year"]
if "month" in self.sector_data.columns:
self.time_cols_ += ["month"]
def transform(self, data, key="sector"):
"""
Transform the input data to disaggregate by industry.
Note: if historical data by industry is not available
for a specific month, the most recent observation is used.
"""
# Aggregate over sector to get total for each time bin
sector_agg = self.sector_data.groupby(self.time_cols_)["total"].sum()
# Get the sector shares
# This is the share of collections to a specific sector per a given time period
# e.g., month or fiscal year
sector_shares = (
self.sector_data.groupby(self.time_cols_ + [key])["total"].sum()
/ sector_agg
).rename("sector_share")
# Check if the time periods for the input data and historical data are misaligned
i = data.set_index(self.time_cols_).index
missing = i.difference(sector_agg.index)
# Impute missing industry shares using most recent observations
if len(missing):
# Setup
existing_index = sector_shares.index
unique_sectors = existing_index.get_level_values(level=-1).unique()
# New time periods that we need to add to historical data
new_index = []
for ii in missing:
if not isinstance(ii, tuple):
ii = (ii,)
new_index += [(*ii, sector) for sector in unique_sectors]
# Reindex and impute missing with most recent obs
sector_shares = (
sector_shares.reindex(existing_index.tolist() + new_index)
.sort_index(level=-1, sort_remaining=True)
.fillna(method="ffill")
)
out = (
data.merge(
sector_shares.reset_index(), on=self.time_cols_, how="left"
)
.assign(total=lambda df: df["total"] * df["sector_share"])
.drop(labels=["sector_share"], axis=1)
)
return out
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/__init__.py
|
from pathlib import Path
# Version number
__version__ = "2.0.0"
# Data directory
DATA_DIR = Path(__file__).parent.absolute() / "data"
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/forecasters.py
|
import pandas as pd
def check_date_bounds(date, start_date, stop_date):
"""Check the bounds of a specific date."""
# Check min date
if date < pd.to_datetime(start_date):
date_str = date.strftime("%Y-%m-%d")
raise ValueError(
f"Date {date_str} before min forecast date ('{start_date}')"
)
# Check max date
if date > pd.to_datetime(stop_date):
date_str = date.strftime("%Y-%m-%d")
raise ValueError(
f"Date {date_str} after max forecast date ('{stop_date}')"
)
class DefaultForecaster:
"""
Default forecaster to make a prediction based on a
decline from a baseline forecast.
"""
ASSUMPTIONS = None
def get_forecast_value(self, date, baseline, scenario):
"""
For a given scenario (and optionally sector), return the revenue
decline from the baseline forecast for the specific date.
Parameters
----------
date : pandas.Timestamp
the date object for the month to forecast
"""
# Check inputs
assert self.ASSUMPTIONS is not None
if isinstance(self.ASSUMPTIONS, dict):
assert scenario is not None
# Check bounds of the date
check_date_bounds(date, self.forecast_start, self.forecast_stop)
# Get the scenario assumptions
declines = self.ASSUMPTIONS[scenario]
# Check length
if len(self.forecast_dates) != len(declines):
raise ValueError(
f"Size mismatch between forecast dates (length={len(self.forecast_dates)}) "
f"and forecast declines (length={len(declines)})"
)
# Get the matching index
# Default behavior: find the PREVIOUS index value if no exact match.
i = self.forecast_dates.get_loc(date, method="ffill")
# Retune 1 - decline
return baseline * (1 - declines[i])
class NoBaselineForecasterBySector:
"""
Default forecaster to make a prediction based on a
decline from a baseline forecast.
"""
ASSUMPTIONS = None
def get_forecast_value(self, date, baseline, scenario):
"""
For a given scenario (and optionally sector), return the revenue
decline from the baseline forecast for the specific date.
Parameters
----------
date : pandas.Timestamp
the date object for the month to forecast
"""
# Check inputs
assert self.ASSUMPTIONS is not None
if isinstance(self.ASSUMPTIONS, dict):
assert scenario is not None
# Check bounds of the date
check_date_bounds(date, self.forecast_start, self.forecast_stop)
# Get the scenario assumptions
values = self.ASSUMPTIONS[scenario]
# Get the matching index
# Default behavior: find the PREVIOUS index value if no exact match.
i = self.forecast_dates.get_loc(date, method="ffill")
out = baseline.copy()
for sector in out.index:
sector_values = values[sector]
if len(self.forecast_dates) != len(sector_values):
raise ValueError(
f"Size mismatch between forecast dates (length={len(self.forecast_dates)}) "
f"and forecast declines (length={len(sector_values)})"
)
out.loc[sector] = sector_values[i]
return out
class SectorForecaster:
"""
Default sector-based forecaster to make a prediction
based on a decline from a baseline forecast.
"""
GROUPS = None
ASSUMPTIONS = None
def get_forecast_value(self, date, baseline, scenario):
"""
For a given scenario (and optionally sector), return the revenue
decline from the baseline forecast for the specific date.
Parameters
----------
date : pandas.Timestamp
the date object for the month to forecast
"""
# Check inputs
assert self.ASSUMPTIONS is not None
assert self.GROUPS is not None
# Check bounds of the date
check_date_bounds(date, self.forecast_start, self.forecast_stop)
# Get the scenario assumptions
declines = self.ASSUMPTIONS[scenario]
# Get the matching index
# Default behavior: find the PREVIOUS index value if no exact match.
i = self.forecast_dates.get_loc(date, method="ffill")
out = baseline.copy()
for sector in out.index:
# Get the group label for this sector
group = "default"
for label in self.GROUPS:
if sector in self.GROUPS[label]:
group = label
break
sector_declines = declines[group]
if len(self.forecast_dates) != len(sector_declines):
raise ValueError(
f"Size mismatch between forecast dates (length={len(self.forecast_dates)}) "
f"and forecast declines (length={len(sector_declines)})"
)
# Multiply by 1 - decline
out.loc[sector] *= 1 - sector_declines[i]
return out
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v2/wage.py
|
<reponame>PhiladelphiaController/covid19-forecaster<gh_stars>1-10
import numpy as np
import pandas as pd
from .. import DATA_DIR
from ..core import RevenueForecast
from ..forecasters import NoBaselineForecasterBySector
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
CROSSWALK = {
"Leisure & Hospitality": [
"Arts, Entertainment, and Other Recreation",
"Hotels",
"Restaurants",
"Sport Teams",
],
"Financial activities": [
"Banking & Credit Unions",
"Insurance",
"Real Estate, Rental and Leasing",
"Securities / Financial Investments",
],
"Mining, Logging, & Construction": ["Construction"],
"Educational & Health Services": [
"Education",
"Health and Social Services",
],
"Government": ["Government"],
"Manufacturing": ["Manufacturing"],
"Other services": ["Other Sectors", "Unclassified Accounts"],
"Professional & Business Services": ["Professional Services"],
"Trade, Transportation, & Utilities": [
"Public Utilities",
"Retail Trade",
"Transportation and Warehousing",
"Wholesale Trade",
],
"Information": [
"Publishing, Broadcasting, and Other Information",
"Telecommunication",
],
}
class WageTaxForecast(NoBaselineForecasterBySector, RevenueForecast):
"""Wage tax revenue forecast."""
ASSUMPTIONS = {}
def __init__(
self, fresh=False,
):
# Load the assumptions
path = DATA_DIR / "models" / "v2" / "Wage Tax Analysis.xlsx"
skiprows = {"moderate": 23, "severe": 41}
for scenario in ["moderate", "severe"]:
# Load the data
data = pd.read_excel(
path,
nrows=10,
header=0,
index_col=0,
usecols="A,D:I",
sheet_name="FY21-FY22 Wage Tax Scenarios",
skiprows=skiprows[scenario],
)
# Convert to keys --> sectors and values --> revenue
self.ASSUMPTIONS[scenario] = {}
for k in data.index:
self.ASSUMPTIONS[scenario][k] = data.loc[k].tolist()
super().__init__(
tax_name="wage",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
sector_crosswalk=CROSSWALK,
agg_after_fitting=True,
fit_kwargs={"seasonality_mode": "multiplicative"},
flat_growth=True,
)
def run_forecast(self, scenario):
"""Run the forecast, adding seasonality in the severe case."""
# Run the base
self.forecast_ = super().run_forecast(scenario)
# Get the seasonality
baseline = self.baseline_forecast.forecasted_revenue_.copy()
seasonality = baseline["yearly"] / baseline["trend"]
# Get ratio of trends to actuals
trend_to_actuals = (
baseline["trend"] / self.baseline_forecast.actual_revenue_
)
# Calibrate to 4th of calendar year
TA = trend_to_actuals.loc[:"2020-01"].copy()
TA.index = TA.index.quarter
TREND_FACTOR = TA.loc[4].mean()
# Apply seasonality
start = self.forecast_start
self.forecast_.loc[start:] *= (
1 + seasonality.loc[start:]
) * TREND_FACTOR
return self.forecast_
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v2/birt.py
|
from ..core import RevenueForecast
from ..utils import get_fiscal_year
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class BIRTForecast(RevenueForecast):
"""BIRT revenue forecast."""
ASSUMPTIONS = {
"moderate": {2020: 0.0, 2021: 0.075, 2022: -0.05},
"severe": {2020: 0.0, 2021: 0.15, 2022: 0.0},
}
def __init__(self, fresh=False):
super().__init__(
tax_name="birt",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
ignore_sectors=True,
agg_after_fitting=False,
fit_kwargs={"seasonality_mode": "additive"},
flat_growth=True,
)
def get_forecast_value(self, date, baseline, scenario):
"""Return the forecasted decline."""
assert scenario in ["moderate", "severe"]
fiscal_year = get_fiscal_year(date)
decline = self.ASSUMPTIONS[scenario][fiscal_year]
return baseline * (1 - decline)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/core.py
|
<filename>covid19_forecaster/core.py
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Dict, Optional, Union
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from phila_style import get_digital_standards
from phila_style.matplotlib import get_theme
from .baseline.core import BaselineForecast
@dataclass
class RevenueForecast(ABC):
"""
A revenue forecast. This class is the base class for
forecasts for individual taxes.
The forecast is composed of:
1. A smooth, pre-COVID baseline forecast that captures
seasonality (computed using Prophet)
2. A post-COVID forecast parameterized as a function of the
baseline; in the simplest case, this forecast is a decline
from the baseline.
Parameters
----------
tax_name : str
the name of the tax to forecast
forecast_start :
the start date for the predicted forecast
forecast_stop :
the stop date for the predicted forecast
freq : {'M', 'Q'}
the frequency of the forecast, either monthly or quarterly
baseline_start : optional
the start date to fit the baseline
baseline_stop : optional
the stop date to fit the baseline; default is just before COVID pandemic
ignore_sectors : optional
whether to include sectors in the forecast
use_subsectors : optional
whether to include subsectors when forecasting
sector_crosswalk : optional
a cross walk to re-align sectors
fresh : optional
if True, calculate a fresh baseline fit
fit_kwargs : optional
additional parameters to pass
agg_after_fitting : optional
whether to aggregate to the desired frequency before or
after fitting the baseline
flat_growth : optional
whether to assume a flat baseline forecast beyond the baseline
fitting period
city_sales_only : optional
whether to transform sales tax data to model only City revenue
"""
tax_name: str
forecast_start: str
forecast_stop: str
freq: str
baseline_start: str = "2013-07-01"
baseline_stop: str = "2020-03-31"
ignore_sectors: Optional[bool] = False
use_subsectors: Optional[bool] = False
sector_crosswalk: Optional[dict] = None
fresh: Optional[bool] = False
fit_kwargs: Optional[dict] = field(default_factory=dict)
agg_after_fitting: Optional[bool] = False
flat_growth: Optional[bool] = False
city_sales_only: Optional[bool] = False
def __post_init__(self):
# Initialize the baseline forecaster
self.baseline_forecast = BaselineForecast(
tax_name=self.tax_name,
freq=self.freq,
fit_start_date=self.baseline_start,
fit_stop_date=self.baseline_stop,
ignore_sectors=self.ignore_sectors,
use_subsectors=self.use_subsectors,
fresh=self.fresh,
fit_kwargs=self.fit_kwargs,
sector_crosswalk=self.sector_crosswalk,
agg_after_fitting=self.agg_after_fitting,
flat_growth=self.flat_growth,
city_sales_only=self.city_sales_only,
)
# Create forecast dates index
freq = self.baseline_forecast.inferred_freq
self.forecast_dates = pd.date_range(
self.forecast_start, self.forecast_stop, freq=freq
)
def __repr__(self):
"""Improved representation."""
name = self.__class__.__name__
return (
f"{name}(tax_name='{self.tax_name}', "
f"forecast_start='{self.forecast_start}', "
f"forecast_stop='{self.forecast_stop}')"
)
@property
def has_sectors(self) -> bool:
"""Whether the forecast uses sector-based data."""
return self.baseline_forecast.has_sectors
@property
def actuals_raw(self) -> pd.DataFrame:
"""
The actual revenue collection (raw) data.
Note: this is in tidy format.
"""
return self.baseline_forecast.actuals_raw
@property
def total_baseline(self) -> pd.Series:
"""
The total baseline, summed over any sectors.
Note: This is a pandas Series indexed by date.
"""
baseline = self.baseline_forecast.forecasted_total_revenue_
return baseline.loc[: self.forecast_stop]
@property
def total_forecast(self) -> pd.Series:
"""
The total forecast, summed over any sectors. For dates prior
to the forecast period, the forecast is equal to the baseline.
Note: This is a pandas Series indexed by date.
"""
assert hasattr(self, "forecast_"), "Please call run_forecast() first"
forecast = self.forecast_
if self.has_sectors:
forecast = forecast.sum(axis=1)
return forecast.loc[: self.forecast_stop]
@property
def total_actuals(self) -> pd.Series:
"""
The total actuals, summed over any sectors.
Note: This is a pandas Series indexed by date.
"""
return self.baseline_forecast.actual_total_revenue_
@property
def actuals(self) -> pd.DataFrame:
"""
The actuals revenue collections.
Note: Columns are sectors (if using) or a single column 'Total'
"""
actuals = self.baseline_forecast.actual_revenue_
if not self.has_sectors:
actuals = actuals.rename(columns={"total": "Total"})
return actuals
@property
def baseline(self) -> pd.DataFrame:
"""
The baseline forecast.
Note: Columns are sectors (if using) or a single column 'Total'
"""
# Get the baseline revenue forecast
baseline = self.baseline_forecast.forecasted_revenue_["total"]
baseline = baseline.loc[: self.forecast_stop]
if not self.has_sectors:
baseline = baseline.to_frame(name="Total")
return baseline
def run_forecast(self, scenario: str) -> pd.DataFrame:
"""
Run the forecast for the specified scenario.
Note: this must be called before the "forecast_" attribute is calculated.
Parameters
----------
scenario :
the name of the scenario to run
Returns
-------
forecast_ :
the predicted revenue forecast
"""
# Set up the forecast period
start = self.forecast_start
stop = self.forecast_stop
# ---------------------------------------------------------------------
# STEP 1: Start from the baseline forecast over the forecast period
# ---------------------------------------------------------------------
self.forecast_ = self.baseline.copy()
# ---------------------------------------------------------------------
# STEP 2: Iterate over each time step and apply the reduction
# ---------------------------------------------------------------------
for date in self.forecast_.loc[start:stop].index:
# This is the baseline
# Either a value or a Series for each sector
baseline = self.baseline.loc[date].squeeze()
# Get the forecasted change
forecast_value = self.get_forecast_value(
date, baseline, scenario=scenario
)
# Save
self.forecast_.loc[date, :] = forecast_value
# Return the forecast
return self.forecast_
@abstractmethod
def get_forecast_value(
self,
date: pd.Timestamp,
baseline: Union[float, pd.Series],
scenario: str,
) -> Union[float, pd.Series]:
"""
For a given scenario, return the revenue forecast for the
specific date and the specific scenario.
Note: this is abstract — subclasses must define this function!
Parameters
----------
date :
the date for the forecast
baseline :
the baseline forecast for the specified date
scenario :
the scenario to forecast
"""
pass
def get_summary(
self,
include_sectors: bool = False,
quarterly: bool = False,
start_date: Optional[str] = None,
) -> pd.DataFrame:
"""
Summarize the current forecast, returning the actuals,
forecast, and baseline.
Note: you must call `run_forecast()` before this.
Parameters
----------
include_sectors :
whether to include sectors
quarterly :
if data is monthly, whether to summarize in quarters
start_date :
Only include data from this date forward in the summary
Returns
-------
summary :
Dataframe indexed by sector and kind, where kind includes
"actual", "forecast" and "baseline". Columns are dates.
"""
assert hasattr(self, "forecast_"), "Please call run_forecast() first"
out = []
labels = ["baseline", "actual", "forecast"]
for i, df in enumerate([self.baseline, self.actuals, self.forecast_]):
# Get the data frame with date along column axis
B = df.T.copy()
# Add a "Total" row
if self.has_sectors:
B.loc["Total"] = B.sum(axis=0)
# Prepend a level to the index
B = pd.concat({labels[i]: B}, names=["sector"])
out.append(B)
# Combine and make sure index is (tax, kind)
X = pd.concat(out, axis=0).swaplevel()
# Re-order the tax indices
if self.has_sectors:
cols = self.actuals.columns.tolist() + ["Total"]
X = X.loc[cols]
# Just return the "Total"
if not include_sectors:
X = X.loc[["Total"]]
# Summarize to quarters?
if self.freq == "M" and quarterly:
# Put date on row axis
X = X.T
# Set sum to Nan if not 3 months per quarter
X = X.groupby(pd.Grouper(freq="QS")).sum(min_count=3)
# Date on column axis
X = X.T
# Trim by start date
if start_date is not None:
X = X.T.loc[start_date:].T
return X.rename_axis(("sector", "kind"))
def get_normalized_summary(
self, include_sectors=False, quarterly=False, start_date=None
) -> pd.DataFrame:
"""
Return the actuals & forecast normalized by the baseline.
Note: you must call `run_forecast()` before this.
Parameters
----------
include_sectors :
whether to include sectors
quarterly :
if data is monthly, whether to summarize in quarters
start_date :
Only include data from this date forward in the summary
Returns
-------
summary :
Dataframe indexed by sector and kind, where kind includes
"actual" and "forecast". Columns are dates.
"""
# Get the summary
S = self.get_summary(
include_sectors=include_sectors,
quarterly=quarterly,
start_date=start_date,
)
# Get the baseline
baseline = S.xs("baseline", axis=0, level=-1)
# Create a copy to return and remove baseline
out = S.copy().drop("baseline", level=-1)
for name in ["forecast", "actual"]:
# Normalize the actuals/forecast
F = S.xs(name, axis=0, level=-1)
F = F / baseline
# Set it!
out.loc[pd.IndexSlice[:, name], :] = F.values
return out
def get_baseline_differences(
self,
cumulative: bool = True,
include_sectors: bool = False,
quarterly: bool = False,
start_date: Optional[str] = None,
) -> pd.DataFrame:
"""
Return the differences between the baseline and actuals/forecast.
Note: you must call `run_forecast()` before this.
Parameters
----------
cumulative :
whether to return cumulative difference since the specified start date
include_sectors :
whether to include sectors
quarterly :
if data is monthly, whether to summarize in quarters
start_date :
Only include data from this date forward in the summary
Returns
-------
summary :
Dataframe indexed by sector and kind, where kind includes
"actual" and "forecast". Columns are dates.
"""
# Get the summary
S = self.get_summary(
include_sectors=include_sectors,
quarterly=quarterly,
start_date=start_date,
)
# Get the baseline
baseline = S.xs("baseline", axis=0, level=-1)
# Create a copy to return and remove baseline
out = S.copy().drop("baseline", level=-1)
for name in ["forecast", "actual"]:
# Get the differences
F = S.xs(name, axis=0, level=-1)
F = F - baseline
if cumulative:
F = F.cumsum(axis=1)
# Set it!
out.loc[pd.IndexSlice[:, name], :] = F.values
return out
def plot(self, normalized=False, month_to_quarters=False, start_date=None):
"""
Plot the baseline and scenario forecasts, as well as the
historical data points.
Parameters
----------
normalized :
normalize the forecast by the baseline
month_to_quarters :
whether to aggregate monthly data to quarters before plotting
start_date :
Only include data from this date forward in the summary
"""
# Summarize
S = self.get_summary(
quarterly=month_to_quarters, start_date=start_date
).loc["Total"]
# Get the components
baseline = S.loc["baseline"]
forecast = S.loc["forecast"]
actuals = S.loc["actual"]
# Load the palettes
palette = get_digital_standards()
with plt.style.context(get_theme()):
fig, ax = plt.subplots(
figsize=(6, 4), gridspec_kw=dict(left=0.15, bottom=0.1)
)
# Not normalized
if not normalized:
baseline.plot(
lw=1,
ax=ax,
y="total",
color=palette["medium-gray"],
zorder=10,
legend=False,
label="Baseline",
clip_on=False,
)
# Get the forecast, with one point previous to where it started
i = forecast.index.get_loc(
self.forecast_start, method="nearest"
)
forecast = forecast.iloc[i:]
# Plot the forecast
forecast.plot(
lw=1,
ax=ax,
y="total",
color=palette["ben-franklin-blue"],
zorder=10,
legend=False,
label="Forecast",
clip_on=False,
)
# Plot the actuals scatter
actuals.reset_index(name="total").plot(
kind="scatter",
x="date",
y="total",
ax=ax,
color=palette["love-park-red"],
zorder=11,
label="Actuals",
clip_on=False,
)
else:
# Plot the forecast
N = forecast / baseline
N.plot(
lw=1,
ax=ax,
y="total",
color=palette["ben-franklin-blue"],
zorder=10,
legend=False,
label="Forecast",
clip_on=False,
)
# Plot the actuals scatter
A = (actuals / baseline).dropna()
A.reset_index(name="total").plot(
kind="scatter",
x="date",
y="total",
ax=ax,
color=palette["love-park-red"],
zorder=11,
label="Actuals",
clip_on=False,
)
# Format
ax.set_yticks(ax.get_yticks())
if not normalized:
ax.set_yticklabels([f"${x/1e6:.0f}M" for x in ax.get_yticks()])
else:
ax.set_yticklabels([f"{x*100:.0f}%" for x in ax.get_yticks()])
ax.set_xlabel("")
ax.set_ylabel("")
ax.legend(loc=0, fontsize=10)
return fig, ax
class ScenarioForecast:
"""
A collection of revenue forecasts for different taxes for a
specific scenario.
Parameters
----------
*forecasts :
individual RevenueForecast objects for each tax forecast
scenario :
if provided, call `run_forecast(scenario)` for each of the input forecasts.
"""
def __init__(self, *forecasts: RevenueForecast, scenario=None):
# Save the forecasts as a dict
self.forecasts = {f.tax_name: f for f in forecasts}
# Run the specified forecast
if scenario is not None:
for name in self.forecasts:
self.forecasts[name].run_forecast(scenario)
@property
def taxes(self):
"""The names of the taxes in the forecast."""
return sorted(self.forecasts.keys())
def __getitem__(self, name):
"""Return a specific forecast."""
if name in self.taxes:
return self.forecasts[name]
return super().__getitem__(name)
def __getattr__(self, name):
if name in self.taxes:
return self.forecasts[name]
raise AttributeError(f"No such attribute '{name}'")
def __iter__(self):
yield from self.taxes
def _get_report(
self,
func_name,
include_sectors=False,
quarterly=False,
start_date=None,
**kwargs,
):
"""Internal function to calculate a specific report."""
out = []
for tax_name in self:
# Get the tax object
tax = self[tax_name]
# Get the function
func = getattr(tax, func_name)
# Call it
summary = func(
include_sectors=include_sectors,
quarterly=quarterly,
start_date=start_date,
**kwargs,
)
# Rename the index level so it includes tax
summary = pd.concat({tax.tax_name: summary}, names=["tax"])
summary = summary.rename_axis(("tax", "sector", "kind"))
out.append(summary)
# Combine
# Date is now on column axis with taxes on row axis
out = pd.concat(out, axis=0)
# Add a "all taxes" column
all_taxes = out.xs("Total", axis=0, level=1).sum(axis=0, level=-1)
for name in all_taxes.index:
out.loc[("all_taxes", "Total", name)] = all_taxes.loc[name]
# Re-order
out = out.loc[self.taxes + ["all_taxes"]]
# Return just the total
if not include_sectors:
out = out.xs("Total", axis=0, level=1)
return out
def get_summary(
self,
include_sectors: bool = False,
quarterly: bool = False,
start_date: Optional[str] = None,
) -> pd.DataFrame:
"""
Summarize the scenario by providing actual, baseline,
and forecast values for each tax.
Note: you must call `run_forecast()` before this.
Parameters
----------
include_sectors :
whether to include sectors
quarterly :
if data is monthly, whether to summarize in quarters
start_date :
Only include data from this date forward in the summary
Returns
-------
summary :
Dataframe indexed by tax, sector and kind, where kind includes
"actual", "forecast" and "baseline". Columns are dates.
"""
return self._get_report(
"get_summary",
include_sectors=include_sectors,
quarterly=quarterly,
start_date=start_date,
)
def get_normalized_summary(
self, include_sectors=False, quarterly=False, start_date=None
) -> pd.DataFrame:
"""
Return the actuals & forecast normalized by the baseline.
Note: you must call `run_forecast()` before this.
Parameters
----------
include_sectors :
whether to include sectors
quarterly :
if data is monthly, whether to summarize in quarters
start_date :
Only include data from this date forward in the summary
Returns
-------
summary :
Dataframe indexed by sector and kind, where kind includes
"actual" and "forecast". Columns are dates.
"""
# Get the summary
S = self.get_summary(
include_sectors=include_sectors,
quarterly=quarterly,
start_date=start_date,
)
# Get the baseline
baseline = S.xs("baseline", axis=0, level=-1)
# Create a copy to return and remove baseline
out = S.copy().drop("baseline", level=-1)
for name in ["forecast", "actual"]:
# Normalize the actuals/forecast
F = S.xs(name, axis=0, level=-1)
F = F / baseline
# Set it!
if include_sectors:
idx = pd.IndexSlice[:, :, name]
else:
idx = pd.IndexSlice[:, name]
out.loc[idx, :] = F.values
return out
def get_baseline_differences(
self,
cumulative: bool = True,
include_sectors: bool = False,
quarterly: bool = False,
start_date: Optional[str] = None,
) -> pd.DataFrame:
"""
Return the differences between the baseline and actuals/forecast.
Note: you must call `run_forecast()` before this.
Parameters
----------
cumulative :
whether to return cumulative difference since the specified start date
include_sectors :
whether to include sectors
quarterly :
if data is monthly, whether to summarize in quarters
start_date :
Only include data from this date forward in the summary
Returns
-------
summary :
Dataframe indexed by sector and kind, where kind includes
"actual" and "forecast". Columns are dates.
"""
return self._get_report(
"get_baseline_differences",
cumulative=cumulative,
include_sectors=include_sectors,
quarterly=quarterly,
start_date=start_date,
)
@dataclass
class ScenarioComparison:
"""
A class to facilitate comparisons of multiple scenario forecasts.
Parameters
----------
scenarios :
dict mapping scenario name to forecast
"""
scenarios: Dict[str, ScenarioForecast]
def __repr__(self):
name = self.__class__.__name__
return f"{name}(scenarios={self.scenario_names})"
@property
def scenario_names(self):
"""The names of the scenarios to compare."""
return sorted(self.scenarios.keys())
def __getitem__(self, name):
"""Return a specific scenario."""
if name in self.scenario_names:
return self.scenarios[name]
return super().__getitem__(name)
def __getattr__(self, name):
if name in self.scenario_names:
return self.scenarios[name]
raise AttributeError(f"No such attribute '{name}'")
def _get_report(
self,
func_name,
start_date=None,
quarterly=False,
include_sectors=False,
**kwargs,
):
"""Internal function to get scenario report."""
out = []
for i, scenario in enumerate(self.scenario_names):
# This scenario
scenario_forecast = self.scenarios[scenario]
# Get the function
func = getattr(scenario_forecast, func_name)
# Run the function
df = func(
include_sectors=include_sectors,
quarterly=quarterly,
start_date=start_date,
**kwargs,
)
# Rename the forecast
df = df.rename(index={"forecast": scenario})
# Drop baseline if we need to
if "baseline" in df.index.get_level_values(-1):
df = df.drop("baseline", axis=0, level=-1)
# Drop actual if not the first
if i > 0:
df = df.drop("actual", axis=0, level=-1)
out.append(df)
# Combine
out = pd.concat(out, axis=0).sort_index()
# Return with "total" last
i = out.index.get_level_values(0).unique()
return out.loc[i.drop("all_taxes").tolist() + ["all_taxes"]]
def get_summary(
self,
include_sectors: bool = False,
quarterly: bool = False,
start_date: Optional[str] = None,
) -> pd.DataFrame:
"""
Return a summary of the scenario forecasts.
Note: This includes actual and forecasts but not baseline.
Parameters
----------
start_date :
Only include data from this date forward in the summary
include_sectors :
whether to include sectors
quarterly :
if data is monthly, whether to summarize in quarters
Returns
-------
summary :
Dataframe indexed by tax, sector and kind, where kind includes
"actual" and scenario names. Columns are dates.
"""
return self._get_report(
"get_summary",
start_date=start_date,
quarterly=quarterly,
include_sectors=include_sectors,
)
def get_baseline_differences(
self,
cumulative: bool = True,
include_sectors: bool = False,
quarterly: bool = False,
start_date: Optional[str] = None,
) -> pd.DataFrame:
"""
Return cumulative differences between forecast and baseline
since the specified start date.
Note: This includes differences between actual values and
baseline and forecasted values and baseline.
Parameters
----------
start_date :
Only include data from this date forward in the summary
include_sectors :
whether to include sectors
quarterly :
if data is monthly, whether to summarize in quarters
Returns
-------
diffs :
Dataframe indexed by tax, sector and kind, where kind includes
"actual" and scenario names. Columns are dates.
"""
return self._get_report(
"get_baseline_differences",
cumulative=cumulative,
start_date=start_date,
quarterly=quarterly,
include_sectors=include_sectors,
)
def get_normalized_summary(
self,
include_sectors: bool = False,
quarterly: bool = False,
start_date: Optional[str] = None,
) -> pd.DataFrame:
"""
Return the actual and scenario forecasts normalized by
the baseline.
Parameters
----------
start_date :
Only include data from this date forward in the summary
include_sectors :
whether to include sectors
quarterly :
if data is monthly, whether to summarize in quarters
Returns
-------
declines :
Dataframe indexed by tax, sector and kind, where kind includes
"actual" and scenario names. Columns are dates.
"""
return self._get_report(
"get_normalized_summary",
start_date=start_date,
quarterly=quarterly,
include_sectors=include_sectors,
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v1/amusement.py
|
<gh_stars>1-10
import numpy as np
from ..core import RevenueForecast
from ..forecasters import DefaultForecaster
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class AmusementTaxForecast(DefaultForecaster, RevenueForecast):
"""Amusement tax revenue forecast."""
ASSUMPTIONS = {
"moderate": np.concatenate(
[
np.repeat(0.7, 3),
np.repeat(0.4, 3),
np.repeat(0.25, 3),
np.repeat(0.15, 12),
]
),
"severe": np.concatenate(
[
np.repeat(0.9, 3),
np.repeat(0.6, 3),
np.repeat(0.3, 3),
np.repeat(0.2, 3),
np.repeat(0.15, 9),
]
),
}
def __init__(self, fresh=False):
super().__init__(
tax_name="amusement",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
fit_kwargs={"seasonality_mode": "multiplicative"},
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v1/sales.py
|
<gh_stars>1-10
import numpy as np
from ..core import RevenueForecast
from ..forecasters import SectorForecaster
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class SalesTaxForecast(SectorForecaster, RevenueForecast):
"""Sales tax revenue forecast."""
GROUPS = {
"impacted": [
"Hotels",
"Restaurants, bars, concessionaires and caterers",
"Total Retail",
"Wholesale",
]
}
ASSUMPTIONS = {
"moderate": {
"impacted": np.repeat([0.5, 0.3, 0.2, 0.1, 0.05, 0.0, 0.0], 3),
"default": np.repeat([0.3, 0.2, 0.1, 0.05, 0.03, 0.0, 0.0], 3),
},
"severe": {
"impacted": np.repeat([0.7, 0.5, 0.3, 0.2, 0.1, 0.05, 0.0], 3),
"default": np.repeat([0.5, 0.3, 0.2, 0.1, 0.05, 0.03, 0.0], 3),
},
}
def __init__(self, fresh=False):
super().__init__(
tax_name="sales",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
ignore_sectors=False,
fit_kwargs={"seasonality_mode": "multiplicative"},
city_sales_only=True,
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v1/wage.py
|
<gh_stars>1-10
import numpy as np
from ..core import RevenueForecast
from ..forecasters import check_date_bounds
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class WageTaxForecast(RevenueForecast):
"""Wage tax revenue forecast."""
RECOVERY_RATES = {
"moderate": {"impacted": 0.15, "default": 0.25},
"severe": {"impacted": 0.1, "default": 0.2},
}
GROUPS = {
"impacted": [
"Arts, Entertainment, and Other Recreation",
"Hotels",
"Restaurants",
"Retail Trade",
"Sport Teams",
"Wholesale Trade",
]
}
ASSUMPTIONS = {
"moderate": {
"Construction": 0.1,
"Manufacturing": 0.15,
"Public Utilities": 0.05,
"Transportation and Warehousing": 0.15,
"Telecommunication": 0.05,
"Publishing, Broadcasting, and Other Information": 0.05,
"Wholesale Trade": 0.25,
"Retail Trade": 0.25,
"Banking & Credit Unions": 0.05,
"Securities / Financial Investments": 0.1,
"Insurance": 0.05,
"Real Estate, Rental and Leasing": 0.05,
"Health and Social Services": 0.1,
"Education": 0.1,
"Professional Services": 0.05,
"Hotels": 0.25,
"Restaurants": 0.7,
"Sport Teams": 0.25,
"Arts, Entertainment, and Other Recreation": 0.25,
"Other Sectors": 0.15,
"Government": 0.03,
"Unclassified Accounts": 0.05,
},
"severe": {
"Construction": 0.2,
"Manufacturing": 0.3,
"Public Utilities": 0.1,
"Transportation and Warehousing": 0.3,
"Telecommunication": 0.1,
"Publishing, Broadcasting, and Other Information": 0.1,
"Wholesale Trade": 0.5,
"Retail Trade": 0.5,
"Banking & Credit Unions": 0.1,
"Securities / Financial Investments": 0.2,
"Insurance": 0.1,
"Real Estate, Rental and Leasing": 0.1,
"Health and Social Services": 0.2,
"Education": 0.2,
"Professional Services": 0.1,
"Hotels": 0.5,
"Restaurants": 0.9,
"Sport Teams": 0.5,
"Arts, Entertainment, and Other Recreation": 0.5,
"Other Sectors": 0.3,
"Government": 0.05,
"Unclassified Accounts": 0.1,
},
}
def get_forecast_value(self, date, baseline, scenario):
"""
For a given scenario (and optionally sector), return the revenue
decline from the baseline forecast for the specific date.
Parameters
----------
date : pandas.Timestamp
the date object for the month to forecast
"""
# Check bounds of the date
check_date_bounds(date, self.forecast_start, self.forecast_stop)
# Get the scenario assumptions
initial_declines = self.ASSUMPTIONS[scenario]
# Get the matching index
# Default behavior: find the PREVIOUS index value if no exact match.
i = self.forecast_dates.get_loc(date, method="ffill")
out = baseline.copy()
for sector in out.index:
# Make sure we have this sector
assert sector in initial_declines, sector
# Get the group label for this sector
group = "default"
for label in self.GROUPS:
if sector in self.GROUPS[label]:
group = label
break
# The recovery rate
recovery_rate = self.RECOVERY_RATES[scenario][group]
# The initial drop
initial_drop = initial_declines[sector]
# Get the decline
if scenario == "moderate" and i in [0, 1]:
decline = initial_drop
elif scenario == "severe" and i in [0, 1, 2]:
decline = initial_drop
else:
decline = initial_drop * (1 - recovery_rate) ** i
# Multiply by 1 - decline
out.loc[sector] *= 1 - decline
return out
def __init__(self, fresh=False):
super().__init__(
tax_name="wage",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
fit_kwargs={"seasonality_mode": "multiplicative"},
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v1/soda.py
|
<reponame>PhiladelphiaController/covid19-forecaster<gh_stars>1-10
import numpy as np
from ..core import RevenueForecast
from ..forecasters import DefaultForecaster
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class SodaTaxForecast(DefaultForecaster, RevenueForecast):
"""Soda tax revenue forecast."""
ASSUMPTIONS = {
"moderate": np.concatenate(
[
np.repeat(0.2, 3),
np.repeat(0.1, 3),
np.repeat(0.05, 3),
np.repeat(0.03, 3),
np.repeat(0.01, 9),
]
),
"severe": np.concatenate(
[
np.repeat(0.4, 3),
np.repeat(0.3, 3),
np.repeat(0.15, 3),
np.repeat(0.05, 3),
np.repeat(0.03, 9),
]
),
}
def __init__(self, fresh=False):
super().__init__(
tax_name="soda",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
fit_kwargs={"seasonality_mode": "additive"},
)
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/baseline/core.py
|
<reponame>PhiladelphiaController/covid19-forecaster
from collections import OrderedDict
from dataclasses import dataclass, field
from functools import partial
from typing import Dict, List, Optional
import pandas as pd
from cached_property import cached_property
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer
from .. import DATA_DIR, io
from ..utils import aggregate_to_quarters, get_unique_id
from .sales import get_city_sales_only
from .transformers import (
BaselineForecaster,
DisaggregateCollectionsBySector,
RevenueToTaxBase,
)
TAX_NAMES = [
"wage",
"birt",
"amusement",
"npt",
"parking",
"rtt",
"sales",
"soda",
]
def _has_sectors(tax_name: str, ignore_sectors: bool) -> bool:
"""Determine whether we are doing a sector-based forecast."""
return tax_name in ["birt", "sales", "wage", "rtt"] and not ignore_sectors
def _crosswalk_sectors(
df: pd.DataFrame, crosswalk: Dict[str, List[str]]
) -> pd.DataFrame:
"""Internal function to perform a crosswalk across sectors."""
# Loop over keys of crosswalk -> these are the new groupings
# Columns are the old groupings
out = []
for name in crosswalk:
X = df[crosswalk[name]].sum(axis=1).rename(name)
out.append(X)
return pd.concat(out, axis=1)
def _get_monthly_total(df):
"""Internal utility to get the monthly total."""
return df.groupby("date")["total"].sum().sort_index()
class cached_baseline:
"""Convenience wrapper to check if cached baseline is present."""
def __init__(self, func):
self.function = func
def __get__(self, instance, owner):
return partial(self.__call__, instance)
def __call__(self, baseline, X):
"""Decorator that checks cache first, and then calls function."""
# Get the cache path
path = self.get_cache_path(baseline)
# Call if we need to
if baseline.fresh or not path.exists():
# Call the function
out = self.function(baseline, X)
# Setup output path
path = self.get_cache_path(baseline)
if not path.parent.exists():
path.parent.mkdir()
# Save
out.to_csv(path)
baseline.fresh = False
else:
# Load from disk
out = self.load_from_cache(baseline)
return out
def get_cache_identifier(self, baseline):
"""Cache path for baseline data."""
# Get the params that go into the hash
d = {}
for key in [
"use_subsectors",
"ignore_sectors",
"freq",
"fit_start_date",
"fit_stop_date",
"agg_after_fitting",
"flat_growth",
]:
d[key] = getattr(baseline, key)
# Add fit kwargs
d.update(baseline.fit_kwargs)
# Get the hash string
return get_unique_id(d)
def get_cache_path(self, baseline):
"""Return the cache path."""
# Get the file path
tag = self.get_cache_identifier(baseline)
return DATA_DIR / "cache" / f"{baseline.tax_name}-baseline-{tag}.csv"
def load_from_cache(self, baseline):
"""Load a cached baseline."""
# Get the file path
path = self.get_cache_path(baseline)
assert path.exists()
# Number of headers in cached CSV
if _has_sectors(baseline.tax_name, baseline.ignore_sectors):
header = [0, 1]
else:
header = [0]
# Return
return pd.read_csv(path, index_col=0, parse_dates=[0], header=header)
@dataclass
class BaselineForecast:
"""
A baseline tax revenue forecast, produced using Facebook's
Prophet tool on using collections data.
Parameters
----------
tax_name :
the name of the tax to fit
freq :
the prediction frequency, either 'M' (monthly) or 'Q' (quarterly)
fit_start_date :
where to begin fitting the baseline
fit_stop_date :
where to stop fitting the baseline
forecast_stop_date :
where to stop the baseline forecast
ignore_sectors :
do not disaggregate actual data into sectors (if possible)
use_subsectors :
whether to disaggregate with parent sectors or subsectors
fresh :
whether to use the cached baseline, or generate a fresh copy
fit_kwargs :
any additional fitting keywords to pass to Prophet
sector_crosswalk :
a cross walk from old to new sector definitions
"""
tax_name: str
freq: str
fit_start_date: str = "2014-07-01"
fit_stop_date: str = "2020-03-31"
ignore_sectors: Optional[bool] = False
use_subsectors: Optional[bool] = False
fresh: Optional[bool] = False
fit_kwargs: Optional[dict] = field(default_factory=dict)
sector_crosswalk: Optional[Dict[str, List[str]]] = None
agg_after_fitting: Optional[bool] = False
flat_growth: Optional[bool] = False
city_sales_only: Optional[bool] = False
def __post_init__(self):
# Check parameter values
assert self.freq in ["M", "Q"]
assert self.tax_name in TAX_NAMES
if self.tax_name == "sales" and self.freq == "Q":
self.agg_after_fitting = True
# Load the actual data
self.actuals_raw = io.load_monthly_collections(self.tax_name)
# Construct the pipeline
self.steps = OrderedDict()
# ------------------------------------------------------------
# STEP 1: Disaggregate monthly totals by sector and reshape
# ------------------------------------------------------------
if _has_sectors(self.tax_name, self.ignore_sectors):
self.steps["disaggregate_by_sector"] = FunctionTransformer(
self.disaggregate_by_sector
)
else:
self.steps["reshape_raw_actuals"] = FunctionTransformer(
self.reshape_raw_actuals
)
# -----------------------------------------------------------------
# STEP 2: Aggregate to quarters before fitting (optional)
# -----------------------------------------------------------------
if self.freq == "Q" and not self.agg_after_fitting:
self.steps["aggregate_to_quarters"] = FunctionTransformer(
aggregate_to_quarters
)
# -----------------------------------------------------------------
# STEP 3: Convert revenue to tax base
# -----------------------------------------------------------------
self.steps["to_tax_base"] = FunctionTransformer(self.to_tax_base)
# -----------------------------------------------------------------
# STEP 4: Generate the tax base baseline forecast from the actuals
# -----------------------------------------------------------------
self.steps["fit_tax_base"] = FunctionTransformer(self.fit_tax_base)
# -----------------------------------------------------------------
# STEP 5: Convert back to revenue
# -----------------------------------------------------------------
self.steps["to_revenue"] = FunctionTransformer(self.to_revenue)
# -----------------------------------------------------------------
# STEP 6: Extract city portion of sales (optional)
# -----------------------------------------------------------------
if self.city_sales_only and self.tax_name == "sales":
self.steps["extract_city_sales"] = FunctionTransformer(
get_city_sales_only
)
# -----------------------------------------------------------------
# STEP 7: Aggregate to quarters after fitting (optional)
# -----------------------------------------------------------------
if self.freq == "Q" and self.agg_after_fitting:
self.steps["aggregate_to_quarters"] = FunctionTransformer(
aggregate_to_quarters
)
# -----------------------------------------------------------------
# FINAL: Create the pipeline that runs all of the above steps
# -----------------------------------------------------------------
self.pipeline = Pipeline(self.steps.items())
@cached_property
def forecasted_revenue_(self):
"""The predicted revenue forecast."""
return self.pipeline.fit_transform(self.actuals_raw)
@cached_property
def forecasted_tax_base_(self):
"""The predicted tax base forecast."""
if self.tax_name != "sales":
return self.to_tax_base(self.forecasted_revenue_)
else:
# Steps we will skip
skip = ["to_revenue", "extract_city_sales"]
# Start from raw actuals and then transform
X = self.actuals_raw
for (name, step) in self.pipeline.steps:
if name not in skip:
X = step.fit_transform(X)
return X
@cached_property
def forecasted_total_revenue_(self):
"""The predicted total revenue forecast, summed over any sectors"""
return self.sum_over_sectors(self.forecasted_revenue_["total"])
@cached_property
def forecasted_total_tax_base_(self):
"""The predicted total tax base forecast, summed over any sectors"""
return self.sum_over_sectors(self.forecasted_tax_base_["total"])
@cached_property
def actual_revenue_(self):
"""The actual, processed revenue data"""
# Steps we will skip
skip = [
"to_tax_base",
"fit_tax_base",
"project_flat_growth",
"to_revenue",
]
# Start from raw actuals and then transform
X = self.actuals_raw
for (name, step) in self.pipeline.steps:
if name not in skip:
X = step.fit_transform(X)
return X
@cached_property
def actual_tax_base_(self):
"""The actual, processed revenue data"""
if self.tax_name != "sales":
return self.to_tax_base(self.actual_revenue_)
else:
# Steps we will skip
skip = [
"fit_tax_base",
"project_flat_growth",
"to_revenue",
"extract_city_sales",
]
# Start from raw actuals and then transform
X = self.actuals_raw
for (name, step) in self.pipeline.steps:
if name not in skip:
X = step.fit_transform(X)
return X
@cached_property
def actual_total_revenue_(self):
"""The actual revenue data, summed over any sectors"""
return self.sum_over_sectors(self.actual_revenue_)
@cached_property
def actual_total_tax_base_(self):
"""The actual tax base data, summed over any sectors"""
return self.sum_over_sectors(self.actual_tax_base_)
def disaggregate_by_sector(self, X):
"""STEP: Disaggregate input actuals by sector."""
# Load the sector
sector_data = io.load_data_by_sector(
self.tax_name, use_subsectors=self.use_subsectors
)
# Disaggregate actuals by sector
sector_transformer = DisaggregateCollectionsBySector(sector_data)
X = sector_transformer.fit_transform(X)
# Pivot so each sector has its own column
X = X.pivot_table(index="date", values="total", columns="sector")
# Now do any cross walk if we need to
if self.sector_crosswalk is not None:
X = _crosswalk_sectors(X, self.sector_crosswalk)
return X
def reshape_raw_actuals(self, X):
"""STEP: Reshape the input actuals so index is date and there is one column"""
# Index is date and one column "total"
return X.pivot_table(index="date", values="total")
def to_tax_base(self, X):
"""STEP: Convert revenue to tax base by dividing by tax rate."""
# Initialize the transformer and return transformed
tax_base_transformer = RevenueToTaxBase(self.tax_name)
return tax_base_transformer.fit_transform(X)
@cached_baseline
def fit_tax_base(self, X):
"""STEP: Run Prophet to fit the tax base data."""
# Initialize the baseline
baseline = BaselineForecaster(
fit_start_date=self.fit_start_date,
fit_stop_date=self.fit_stop_date,
fit_kwargs=self.fit_kwargs,
forecast_stop_date="2025-06-30",
)
# Transform
out = baseline.fit_transform(X)
# -----------------------------------------------------------------
# Project flat tax base growth (optional)
# -----------------------------------------------------------------
if self.flat_growth:
out = self.project_flat_growth(out)
return out
def to_revenue(self, X):
"""STEP: Convert tax base to revenue by multiplying by tax rate."""
# Initialize the transformer and return transformed
tax_base_transformer = RevenueToTaxBase(self.tax_name)
return tax_base_transformer.inverse_transform(X)
def project_flat_growth(self, X, start="2019-04", stop="2020-03"):
"""Normalize future growth to be flat at the last annual period."""
# Make a copy first
X = X.copy()
freq = X.index.inferred_freq
X.index.freq = freq
# This is the part that will be projected
norm = X.loc[start:stop].copy()
latest_date = norm.index[-1]
# This should be monthly or quarterly
assert len(norm) in [4, 12]
if len(norm) == 4:
key = lambda dt: dt.quarter
else:
key = lambda dt: dt.month
# Reset the index to months/quarters
norm.index = [key(dt) for dt in norm.index]
# Change the forecast to be flat
forecast_start = latest_date + latest_date.freq
Y = X.loc[forecast_start:].copy()
# Reset index
i = Y.index
Y.index = [key(dt) for dt in Y.index]
# Overwrite
Y.loc[:] = norm.loc[Y.index].values
Y.index = i
# Add back to original
X.loc[Y.index] = Y.values
return X
def sum_over_sectors(self, X):
"""Convenience function to (optionally) sum over sectors."""
if self.has_sectors:
return X.sum(axis=1)
else:
return X.squeeze()
@property
def sectors(self):
"""The names of the sectors fit if the data is sector-based."""
if self.has_sectors:
return self.forecasted_revenue_.columns.get_level_values(
level=-1
).unique()
else:
return []
@property
def inferred_freq(self):
"""The frequency inferred from the data used in the fit."""
return self.actual_revenue_.index.inferred_freq
@property
def has_sectors(self):
"""Whether a baseline was fit for multiple sectors."""
return self.forecasted_revenue_.columns.nlevels > 1
@property
def mean_abs_error(self):
"""The mean absolute error of the fit."""
P = self.forecasted_total_revenue_
H = self.actual_total_revenue_
diff = (H - P).loc[self.fit_start_date : self.fit_stop_date]
return diff.dropna().abs().mean()
@property
def mean_abs_percent_error(self):
"""Mean absolute percent error of the fit."""
P = self.forecasted_total_revenue_
H = self.actual_total_revenue_
diff = ((H - P) / H).loc[self.fit_start_date : self.fit_stop_date]
return diff.dropna().abs().mean()
@property
def mean_rms(self):
"""The average root mean squared error of the fit."""
P = self.forecasted_total_revenue_
H = self.actual_total_revenue_
diff = ((H - P) ** 2).loc[self.fit_start_date : self.fit_stop_date]
return diff.dropna().mean() ** 0.5
def plot(self, sector=None, tax_base=False):
"""Plot the total forecast, as well as the historical data points."""
from matplotlib import pyplot as plt
from phila_style import get_digital_standards
from phila_style.matplotlib import get_theme
# Load the palettes
palette = get_digital_standards()
if sector is not None:
assert sector in self.sectors
with plt.style.context(get_theme()):
fig, ax = plt.subplots(
figsize=(6, 4), gridspec_kw=dict(left=0.15, bottom=0.1)
)
def _transform(X, sector):
if self.has_sectors:
if sector is not None:
X = X[sector]
else:
X = X.sum(axis=1)
return X
# Plot the prediction
prediction = self.forecasted_revenue_
if tax_base:
prediction = self.forecasted_tax_base_
total = _transform(prediction["total"], sector)
total.plot(
lw=1,
ax=ax,
color=palette["dark-ben-franklin"],
zorder=10,
legend=False,
)
# Uncertainty
lower = _transform(prediction["lower"], sector)
upper = _transform(prediction["upper"], sector)
ax.fill_between(
lower.index,
lower.values,
upper.values,
facecolor=palette["dark-ben-franklin"],
alpha=0.7,
zorder=9,
)
# Plot the historical scatter
if not tax_base:
H = _transform(self.actual_revenue_, sector)
else:
H = _transform(self.actual_tax_base_, sector)
ax.scatter(
H.index, H.values, color=palette["love-park-red"], zorder=11,
)
# Format
ax.set_yticks(ax.get_yticks())
ax.set_yticklabels([f"${x/1e6:.0f}M" for x in ax.get_yticks()])
ax.set_xlabel("")
ax.set_ylabel("")
return fig, ax
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/baseline/__init__.py
|
from .core import TAX_NAMES, BaselineForecast
|
PhiladelphiaController/covid19-forecaster
|
covid19_forecaster/v2/parking.py
|
import numpy as np
from ..core import RevenueForecast
from ..forecasters import DefaultForecaster
from . import (
BASELINE_START,
BASELINE_STOP,
FORECAST_START,
FORECAST_STOP,
FREQ,
)
class ParkingTaxForecast(DefaultForecaster, RevenueForecast):
"""Parking tax revenue forecast."""
ASSUMPTIONS = {
"moderate": [0.5, 0.4, 0.3, 0.2, 0.1, 0.1],
"severe": [0.5, 0.5, 0.4, 0.3, 0.3, 0.2],
}
def __init__(self, fresh=False):
# Initialize the underlying forecast class
super().__init__(
tax_name="parking",
forecast_start=FORECAST_START,
forecast_stop=FORECAST_STOP,
freq=FREQ,
baseline_start=BASELINE_START,
baseline_stop=BASELINE_STOP,
fresh=fresh,
agg_after_fitting=False,
fit_kwargs={"seasonality_mode": "multiplicative"},
flat_growth=True,
)
|
Zapata/bitshares-explorer-api
|
config.py
|
<filename>config.py
import os
WEBSOCKET_URL = os.environ.get('WEBSOCKET_URL', "ws://localhost:8090/ws")
# Default connection to Elastic Search.
ELASTICSEARCH = {
'hosts': os.environ.get('ELASTICSEARCH_URL', 'https://es.bitshares.eu/').split(','),
'user': os.environ.get('ELASTICSEARCH_USER', 'BitShares'),
'password': <PASSWORD>('ELASTICSEARCH_USER', '******')
}
# Optional ElasticSearch cluster to access other data.
# Currently expect:
# - 'operations': for bitshares-* indexes where operations are stored
# - 'objects': for objects-* indexes where Chain data is stored.
#
# Sample:
#
# ELASTICSEARCH_ADDITIONAL {
# 'operations': None, # Use default cluster.
# 'objects': {
# 'hosts': ['https://es.mycompany.com/'],
# 'user': 'myself',
# 'password': '<PASSWORD>'
# }
# }
ELASTICSEARCH_ADDITIONAL = {
# Overwrite cluster to use to retrieve bitshares-* index.
'operations': None,
# Overwrite cluster to use to retrieve bitshares-* index.
'objects': {
'hosts': ['http://192.168.127.12:5005/'] # oxarbitrage (no credentials)
}
}
# Cache: see https://flask-caching.readthedocs.io/en/latest/#configuring-flask-caching
CACHE = {
'CACHE_TYPE': os.environ.get('CACHE_TYPE', 'simple'), # use 'uwsgi' when running under uWSGI server.
'CACHE_DEFAULT_TIMEOUT': int(os.environ.get('CACHE_DEFAULT_TIMEOUT', 600)) # 10 min
}
# Configure profiler: see https://github.com/muatik/flask-profiler
PROFILER = {
'enabled': os.environ.get('PROFILER_ENABLED', False),
'username': os.environ.get('PROFILER_USERNAME', None),
'password': os.environ.get('PROFILER_PASSWORD', None),
}
CORE_ASSET_SYMBOL = 'BTS'
CORE_ASSET_ID = '1.3.0'
TESTNET = 0 # 0 = not in the testnet, 1 = testnet
CORE_ASSET_SYMBOL_TESTNET = 'TEST'
# Choose which APIs to expose, default to all.
#EXPOSED_APIS = ['explorer', 'es_wrapper', 'udf']
|
seanmorris/dotsyntax-sublime
|
dotsyntax.py
|
<reponame>seanmorris/dotsyntax-sublime<gh_stars>1-10
import sublime_plugin
import sublime
import os.path
import fnmatch
import io
import re
class DotSyntaxCommand(sublime_plugin.EventListener):
mappings = {}
def on_load_async(self, view):
self.set_syntax(view)
def on_post_save_async(self, view):
self.set_syntax(view)
def set_syntax(self, view):
file = os.path.basename(view.file_name());
views = [view];
if file == '.syntax':
views = view.window().views()
for _view in views:
file = _view.file_name();
if not file:
continue
print('dotsyntax checking ' + file)
mapped_ext = self.map_file_extension(file)
syntax_file = self.lookup_syntax_def_file(mapped_ext)
_view.settings().set('syntax', syntax_file)
def lookup_syntax_def_file(self, extension):
if(len(self.mappings) == 0):
self.load_settings()
if extension in self.mappings:
return self.mappings[extension]
def map_file_extension(self, file):
filename = os.path.basename(file)
dir = os.path.dirname(file)
dot_syntax_files = self.find_dotsyntax_files(dir)
for dot_syntax_file in dot_syntax_files:
dot_syntax_dir = os.path.dirname(dot_syntax_file)
rel_path = os.path.relpath(file, dot_syntax_dir)
# rel_path = os.path.dirname(rel_path)
with open(dot_syntax_file, "r") as handle:
defs = [i.strip().rpartition(':') for i in handle if i.strip()]
match = next((i for i in defs if self.filename_match(rel_path,i)), None)
if not match:
match = next((i for i in defs if self.filename_match(filename,i)), None)
if not match:
continue
*_, extension = match
extension = extension.strip()
print("\t.syntax " + dot_syntax_file)
print("\t syntax " + extension + "\n")
return extension.strip()
def filename_match(self, file, check):
*_ ,ext = os.path.splitext(file)
check = check[0].strip()
if check in {ext,file} or fnmatch.fnmatch(file, check):
print("\tmatched " + check + "\n\t file " + file)
return check
def find_dotsyntax_files(self, dir):
files = []
while dir != '/':
syntaxFile = dir + '/.syntax'
if os.path.exists(syntaxFile):
files.append(syntaxFile)
dir = os.path.abspath(os.path.join(dir, os.pardir))
return files
def load_settings(self):
syntaxDefFiles = sublime.find_resources('*.sublime-syntax')
extmode=0
for syntaxDefFile in syntaxDefFiles:
try:
settings = sublime.load_resource(syntaxDefFile)
for line in io.StringIO(settings):
if extmode == 1:
match = re.match('\s{2}-(.+?)\s+?\#?', line)
if match is not None:
extension = '.' + match.group(1).strip()
self.mappings[extension] = syntaxDefFile
else:
extmode = 0
break;
match = re.match('^file_extensions\:', line)
if match is not None:
extmode=1
continue;
except:
continue
|
madpin/renthub
|
main/app/alembic/versions/ef3f101feb21_initial_9.py
|
<reponame>madpin/renthub
"""Initial 9
Revision ID: ef<PASSWORD>
Revises: <PASSWORD>
Create Date: 2021-11-14 06:45:24.012682
"""
from alembic import op
import sqlalchemy as sa
import sqlmodel
# revision identifiers, used by Alembic.
revision = 'ef<PASSWORD>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('images', sa.Column('url_600', sqlmodel.sql.sqltypes.AutoString(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('images', 'url_600')
# ### end Alembic commands ###
|
madpin/renthub
|
main/app/backgroud.py
|
import asyncio
class BackgroundRunner:
def __init__(self):
self.value = 0
self.is_running = False
async def run_main(self):
while True:
if(not self.is_running):
await asyncio.sleep(1)
continue
await asyncio.sleep(0.1)
self.value += 1
|
madpin/renthub
|
location/app/schemas.py
|
import os
from typing import List, Optional
# import datetime
from pydantic import BaseModel
class Point(BaseModel):
lat: float
long: float
class Location(BaseModel):
point: Point
name: str
tags: Optional[List[str]]
class RouteSummary(BaseModel):
waking_distance: int
total_distance: int
total_time: int
public_transport_count: int
class InterestPoint(Point):
name: str
address: str
distance: int
website: Optional[str]
website_domain: Optional[str]
chain_name: Optional[str]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.