code
stringlengths
1
1.72M
language
stringclasses
1 value
import struct from Crypto.Cipher import AES """ http://www.ietf.org/rfc/rfc3394.txt quick'n'dirty AES wrap implementation used by iOS 4 KeyStore kernel extension for wrapping/unwrapping encryption keys """ def unpack64bit(s): return struct.unpack(">Q",s)[0] def pack64bit(s): return struct.pack(">Q",s) def AESUnwrap(kek, wrapped): C = [] for i in xrange(len(wrapped)/8): C.append(unpack64bit(wrapped[i*8:i*8+8])) n = len(C) - 1 R = [0] * (n+1) A = C[0] for i in xrange(1,n+1): R[i] = C[i] for j in reversed(xrange(0,6)): for i in reversed(xrange(1,n+1)): todec = pack64bit(A ^ (n*j+i)) todec += pack64bit(R[i]) B = AES.new(kek).decrypt(todec) A = unpack64bit(B[:8]) R[i] = unpack64bit(B[8:]) #assert A == 0xa6a6a6a6a6a6a6a6, "AESUnwrap: integrity check FAIL, wrong kek ?" if A != 0xa6a6a6a6a6a6a6a6: #print "AESUnwrap: integrity check FAIL, wrong kek ?" return None res = "".join(map(pack64bit, R[1:])) return res def AESwrap(kek, data): A = 0xa6a6a6a6a6a6a6a6 R = [0] for i in xrange(len(data)/8): R.append(unpack64bit(data[i*8:i*8+8])) n = len(R) - 1 for j in xrange(0,6): for i in xrange(1,n+1): B = AES.new(kek).encrypt(pack64bit(A) + pack64bit(R[i])) A = unpack64bit(B[:8]) ^ (n*j+i) R[i] = unpack64bit(B[8:]) res = pack64bit(A) + "".join(map(pack64bit, R[1:])) return res if __name__ == "__main__": #format (kek, data, expected_ciphertext) test_vectors = [ ("000102030405060708090A0B0C0D0E0F", "00112233445566778899AABBCCDDEEFF", "1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5"), ("000102030405060708090A0B0C0D0E0F1011121314151617", "00112233445566778899AABBCCDDEEFF", "96778B25AE6CA435F92B5B97C050AED2468AB8A17AD84E5D"), ("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", "00112233445566778899AABBCCDDEEFF", "64E8C3F9CE0F5BA263E9777905818A2A93C8191E7D6E8AE7"), ("000102030405060708090A0B0C0D0E0F1011121314151617", "00112233445566778899AABBCCDDEEFF0001020304050607", "031D33264E15D33268F24EC260743EDCE1C6C7DDEE725A936BA814915C6762D2"), ("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", "00112233445566778899AABBCCDDEEFF0001020304050607", "A8F9BC1612C68B3FF6E6F4FBE30E71E4769C8B80A32CB8958CD5D17D6B254DA1"), ("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", "00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F", "28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21") ] for kek, data, expected in test_vectors: ciphertext = AESwrap(kek.decode("hex"), data.decode("hex")) assert ciphertext == expected.decode("hex") assert AESUnwrap(kek.decode("hex"), ciphertext) == data.decode("hex") print "All tests OK !"
Python
from Crypto.Cipher import AES ZEROIV = "\x00"*16 def removePadding(blocksize, s): 'Remove rfc 1423 padding from string.' n = ord(s[-1]) # last byte contains number of padding bytes if n > blocksize or n > len(s): raise Exception('invalid padding') return s[:-n] def AESdecryptCBC(data, key, iv=ZEROIV, padding=False): if len(data) % 16: print "AESdecryptCBC: data length not /16, truncating" data = data[0:(len(data)/16) * 16] data = AES.new(key, AES.MODE_CBC, iv).decrypt(data) if padding: return removePadding(16, data) return data def AESencryptCBC(data, key, iv=ZEROIV, padding=False): if len(data) % 16: print "AESencryptCBC: data length not /16, truncating" data = data[0:(len(data)/16) * 16] data = AES.new(key, AES.MODE_CBC, iv).encrypt(data) return data #pycrypto MODE_CFB seems to give wrong results on icloud chunks ? def AESdecryptCFB(data, key, iv=ZEROIV): res = "" a = AES.new(key) ks = a.encrypt(iv) for i in xrange(0,len(data), 16): block = data[i:i+16] for j in xrange(0, len(block)): res += chr(ord(block[j]) ^ ord(ks[j])) if len(block) == 16: ks = a.encrypt(block) return res
Python
#!/usr/bin/env python import sys, os from PyQt4 import QtGui, QtCore from backups.backup4 import MBDB from keychain.keychain4 import Keychain4 from util.bplist import BPlistReader from keystore.keybag import Keybag from util import readPlist class KeychainTreeWidget(QtGui.QTreeWidget): def __init__(self, parent=None): QtGui.QTreeWidget.__init__(self, parent) self.setGeometry(10, 10, 780, 380) self.header().hide() self.setColumnCount(2) class KeychainTreeWidgetItem(QtGui.QTreeWidgetItem): def __init__(self, title): QtGui.QTreeWidgetItem.__init__(self, [title]) fnt = self.font(0) fnt.setBold(True) self.setFont(0, fnt) self.setColors() def setText(self, column, title): QtGui.QTreeWidgetItem.setText(self, column, title) def setColors(self): self.setForeground(0, QtGui.QBrush(QtGui.QColor(80, 80, 80))) self.setBackground(0, QtGui.QBrush(QtGui.QColor(230, 230, 230))) self.setBackground(1, QtGui.QBrush(QtGui.QColor(230, 230, 230))) class LockedKeychainTreeWidgetItem(KeychainTreeWidgetItem): def setColors(self): self.setForeground(0, QtGui.QBrush(QtGui.QColor(255, 80, 80))) self.setBackground(0, QtGui.QBrush(QtGui.QColor(255, 230, 230))) self.setBackground(1, QtGui.QBrush(QtGui.QColor(255, 230, 230))) class KeychainWindow(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setGeometry(100, 100, 800, 400) self.setWindowTitle('Keychain Explorer') self.passwordTree = KeychainTreeWidget(parent=self) def setGenericPasswords(self, pwds): self.genericPasswords = pwds self.passwordItems = KeychainTreeWidgetItem('Generic Passwords') for pwd in self.genericPasswords: if not pwd.has_key('acct'): continue if len(pwd['acct']) > 0: item_title = '%s (%s)' % (pwd['svce'], pwd['acct']) else: item_title = pwd['svce'] if pwd['data'] is None: item = LockedKeychainTreeWidgetItem(item_title) else: item = KeychainTreeWidgetItem(item_title) item.addChild(QtGui.QTreeWidgetItem(['Service', pwd['svce']])) item.addChild(QtGui.QTreeWidgetItem(['Account', pwd['acct']])) if pwd['data'] is not None: item.addChild(QtGui.QTreeWidgetItem(['Data', pwd['data']])) else: item.addChild(QtGui.QTreeWidgetItem(['Data', 'N/A'])) item.addChild(QtGui.QTreeWidgetItem(['Access Group', pwd['agrp']])) self.passwordItems.addChild(item) self.passwordTree.addTopLevelItem(self.passwordItems) self.passwordTree.expandAll() self.passwordTree.resizeColumnToContents(0) def setInternetPasswords(self, pwds): self.internetPasswords = pwds self.internetPasswordItems = KeychainTreeWidgetItem('Internet Passwords') for pwd in pwds: item_title = '%s (%s)' % (pwd['srvr'], pwd['acct']) item = KeychainTreeWidgetItem(item_title) item.addChild(QtGui.QTreeWidgetItem(['Server', pwd['srvr']])) item.addChild(QtGui.QTreeWidgetItem(['Account', pwd['acct']])) if pwd['data'] is not None: item.addChild(QtGui.QTreeWidgetItem(['Data', pwd['data']])) else: item.addChild(QtGui.QTreeWidgetItem(['Data', 'N/A'])) item.addChild(QtGui.QTreeWidgetItem(['Port', str(pwd['port'])])) item.addChild(QtGui.QTreeWidgetItem(['Access Group', pwd['agrp']])) self.internetPasswordItems.addChild(item) self.passwordTree.addTopLevelItem(self.internetPasswordItems) self.passwordTree.expandAll() self.passwordTree.resizeColumnToContents(0) def warn(msg): print "WARNING: %s" % msg def getBackupKeyBag(backupfolder, passphrase): manifest = readPlist(backupfolder + "/Manifest.plist") kb = Keybag(manifest["BackupKeyBag"].data) if kb.unlockBackupKeybagWithPasscode(passphrase): print "BackupKeyBag unlock OK" return kb else: return None def main(): app = QtGui.QApplication(sys.argv) init_path = "{0:s}/Apple Computer/MobileSync/Backup".format(os.getenv('APPDATA')) dirname = QtGui.QFileDialog.getExistingDirectory(None, "Select iTunes backup directory", init_path) kb = getBackupKeyBag(dirname, 'pouet') #XXX: hardcoded password for demo if not kb: warn("Backup keybag unlock fail : wrong passcode?") return db = MBDB(dirname) db.keybag = kb filename, record = db.get_file_by_name("keychain-backup.plist") keychain_data = db.read_file(filename, record) f = file('keychain.tmp', 'wb') f.write(keychain_data) f.close() kc = Keychain4('keychain.tmp', kb) pwds = kc.get_passwords() inet_pwds = kc.get_inet_passwords() qb = KeychainWindow() qb.setGenericPasswords(pwds) qb.setInternetPasswords(inet_pwds) qb.show() sys.exit(app.exec_()) pass if __name__ == '__main__': main()
Python
import base64 def chunks(l, n): return (l[i:i+n] for i in xrange(0, len(l), n)) def RSA_KEY_DER_to_PEM(data): a = ["-----BEGIN RSA PRIVATE KEY-----"] a.extend(chunks(base64.b64encode(data),64)) a.append("-----END RSA PRIVATE KEY-----") return "\n".join(a) def CERT_DER_to_PEM(data): a = ["-----BEGIN CERTIFICATE-----"] a.extend(chunks(base64.b64encode(data),64)) a.append("-----END CERTIFICATE-----") return "\n".join(a)
Python
import struct def tlvToDict(blob): d = {} for tag,data in loopTLVBlocks(blob): d[tag] = data return d def tlvToList(blob): return list(loopTLVBlocks(blob)) def loopTLVBlocks(blob): i = 0 while i + 8 <= len(blob): tag = blob[i:i+4] length = struct.unpack(">L",blob[i+4:i+8])[0] data = blob[i+8:i+8+length] yield (tag,data) i += 8 + length
Python
import plistlib import struct import socket from datetime import datetime from progressbar import ProgressBar, Percentage, Bar, SimpleProgress, ETA from usbmux import usbmux from util import sizeof_fmt kIOAESAcceleratorEncrypt = 0 kIOAESAcceleratorDecrypt = 1 kIOAESAcceleratorGIDMask = 0x3E8 kIOAESAcceleratorUIDMask = 0x7D0 class DeviceInfo(dict): @staticmethod def create(dict): try: assert dict.has_key("dataVolumeUUID") filename = "%s.plist" % dict.get("dataVolumeUUID") return DeviceInfo(plistlib.readPlist(filename)) except: return DeviceInfo(dict) def save(self): filename = "%s.plist" % self.get("dataVolumeUUID", "unk") plistlib.writePlist(self, filename) #stop doing magic stuff #def __del__(self): # self.save() class RamdiskToolClient(object): instance = None @staticmethod def get(): if not RamdiskToolClient.instance: RamdiskToolClient.instance = RamdiskToolClient() return RamdiskToolClient.instance def __init__(self, udid=None, host="localhost", port=1999): self.host = host self.port = port self.device_infos = {} self.s = None self.connect(udid) self.getDeviceInfos() def close(self): if self.s: self.s.close() self.s = None def connect(self, udid=None): mux = usbmux.USBMux() mux.process(1.0) if not mux.devices: print "Waiting for iOS device" while not mux.devices: mux.process(1.0) if not mux.devices: print "No device found" return dev = mux.devices[0] print "Connecting to device : " + dev.serial try: self.s = mux.connect(dev, self.port) except: raise Exception("Connexion to device port %d failed" % self.port) def getDeviceInfos(self): self.device_infos = self.send_req({"Request":"DeviceInfo"}) keys = self.grabDeviceKeys() if keys: self.device_infos.update(keys) return DeviceInfo.create(self.device_infos) def downloadFile(self, path): res = self.send_req({"Request": "DownloadFile", "Path": path}) if type(res) == plistlib._InternalDict and res.has_key("Data"): return res["Data"].data def getSystemKeyBag(self): return self.send_req({"Request":"GetSystemKeyBag"}) def bruteforceKeyBag(self, KeyBagKeys): return self.send_req({"Request":"BruteforceSystemKeyBag", "KeyBagKeys": plistlib.Data(KeyBagKeys)}) def getEscrowRecord(self, hostID): return self.send_req({"Request":"GetEscrowRecord", "HostID": hostID}) def getPasscodeKey(self, keybagkeys, passcode): return self.send_req({"Request":"KeyBagGetPasscodeKey", "KeyBagKeys": plistlib.Data(keybagkeys), "passcode": passcode}) def send_msg(self, dict): plist = plistlib.writePlistToString(dict) data = struct.pack("<L",len(plist)) + plist return self.s.send(data) def recv_msg(self): try: l = self.s.recv(4) if len(l) != 4: return None ll = struct.unpack("<L",l)[0] data = "" l = 0 while l < ll: x = self.s.recv(ll-l) if not x: return None data += x l += len(x) return plistlib.readPlistFromString(data) except: raise return None def send_req(self, dict): start = None self.send_msg(dict) while True: r = self.recv_msg() if type(r) == plistlib._InternalDict and r.get("MessageType") == "Progress": if not start: pbar = ProgressBar(r.get("Total",100),[SimpleProgress(), " ", ETA(), "\n", Percentage(), " ", Bar()]) pbar.start() start = datetime.utcnow() pbar.update( r.get("Progress", 0)) else: if start: pbar.finish() print dict.get("Request"), ":", datetime.utcnow() - start return r def aesUID(self, data): return self.aes(data, kIOAESAcceleratorUIDMask, kIOAESAcceleratorEncrypt) def aesGID(self, data): return self.aes(data, kIOAESAcceleratorGIDMask, kIOAESAcceleratorDecrypt) def aes(self, data, keyMask, mode): return self.send_req({"Request":"AES", "input": plistlib.Data(data), "keyMask": keyMask, "mode": mode, "bits": 128 }) def grabDeviceKeys(self): blobs = {"key835": "\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01", "key899": "\xD1\xE8\xFC\xB5\x39\x37\xBF\x8D\xEF\xC7\x4C\xD1\xD0\xF1\xD4\xB0", "key89A": "\xDB\x1F\x5B\x33\x60\x6C\x5F\x1C\x19\x34\xAA\x66\x58\x9C\x06\x61", "key89B": "\x18\x3E\x99\x67\x6B\xB0\x3C\x54\x6F\xA4\x68\xF5\x1C\x0C\xBD\x49" } for k,b in blobs.items(): r = self.aesUID(b) if not r or r.returnCode != 0 or not r.has_key("data"): print "AES UID error" return blobs[k] = r.data.data.encode("hex") return blobs def reboot(self): print "Rebooting device" return self.send_req({"Request":"Reboot"})
Python
from keystore.keybag import Keybag from keystore.effaceable import EffaceableLockers from util.ramdiskclient import RamdiskToolClient import plistlib COMPLEXITY={ 0: "4 digits", 1: "n digits", 2: "n alphanum" } def checkPasscodeComplexity(data_volume): pl = data_volume.readFile("/mobile/Library/ConfigurationProfiles/UserSettings.plist", returnString=True) if not pl: print "Failed to read UserSettings.plist, assuming simple passcode" return 0 pl = plistlib.readPlistFromString(pl) #print "passcodeKeyboardComplexity :", pl["restrictedValue"]["passcodeKeyboardComplexity"] value = pl["restrictedValue"]["passcodeKeyboardComplexity"]["value"] print "passcodeKeyboardComplexity %d => %s" % (value, COMPLEXITY.get(value)) return pl["restrictedValue"]["passcodeKeyboardComplexity"]["value"] def loadKeybagFromVolume(volume, device_infos): systembag = volume.readFile("/keybags/systembag.kb", returnString=True) if not systembag or not systembag.startswith("bplist"): print "FAIL: could not read /keybags/systembag.kb from data partition" return False lockers = EffaceableLockers(device_infos["lockers"].data) bag1key = lockers.get("BAG1")[-32:] keybag = Keybag.createWithSystemkbfile(systembag, bag1key, device_infos.get("key835", "").decode("hex")) keybag.setDKey(device_infos) if device_infos.has_key("passcodeKey"): keybag.unlockWithPasscodeKey(device_infos.get("passcodeKey").decode("hex")) return keybag def bruteforcePasscode(device_infos, data_volume): if device_infos.has_key("passcode"): print "Passcode already found, no bruteforce required" return False kb = data_volume.keybag if not kb: return False rd = RamdiskToolClient.get() if rd.device_infos.udid != device_infos.udid: print "Wrong device connected" return print "Passcode comlexity (from OpaqueStuff) : %s" % COMPLEXITY.get(kb.passcodeComplexity) print "Enter passcode or leave blank for bruteforce:" z = raw_input() bf = rd.getPasscodeKey(kb.KeyBagKeys, z) if kb.unlockWithPasscodeKey(bf.get("passcodeKey").decode("hex")): print "Passcode \"%s\" OK" % z else: if z != "": print "Wrong passcode, trying to bruteforce !" if kb.passcodeComplexity != 0: print "Complex passcode used, not bruteforcing" return False bf = rd.bruteforceKeyBag(kb.KeyBagKeys) if bf and kb.unlockWithPasscodeKey(bf.get("passcodeKey").decode("hex")): print "Bruteforce successful, passcode : %s" % bf["passcode"] print "Passcode key : %s" % bf.get("passcodeKey") if kb.unlocked: device_infos.update(bf) device_infos["classKeys"] = kb.getClearClassKeysDict() device_infos["KeyBagKeys"] = plistlib.Data(kb.KeyBagKeys) return True return False
Python
""" http://github.com/farcaller/bplist-python/blob/master/bplist.py """ import struct import plistlib from datetime import datetime, timedelta class BPListWriter(object): def __init__(self, objects): self.bplist = "" self.objects = objects def binary(self): '''binary -> string Generates bplist ''' self.data = 'bplist00' # TODO: flatten objects and count max length size # TODO: write objects and save offsets # TODO: write offsets # TODO: write metadata return self.data def write(self, filename): ''' Writes bplist to file ''' if self.bplist != "": pass # TODO: save self.bplist to file else: raise Exception('BPlist not yet generated') class BPlistReader(object): def __init__(self, s): self.data = s self.objects = [] self.resolved = {} def __unpackIntStruct(self, sz, s): '''__unpackIntStruct(size, string) -> int Unpacks the integer of given size (1, 2 or 4 bytes) from string ''' if sz == 1: ot = '!B' elif sz == 2: ot = '!H' elif sz == 4: ot = '!I' elif sz == 8: ot = '!Q' else: raise Exception('int unpack size '+str(sz)+' unsupported') return struct.unpack(ot, s)[0] def __unpackInt(self, offset): '''__unpackInt(offset) -> int Unpacks int field from plist at given offset ''' return self.__unpackIntMeta(offset)[1] def __unpackIntMeta(self, offset): '''__unpackIntMeta(offset) -> (size, int) Unpacks int field from plist at given offset and returns its size and value ''' obj_header = struct.unpack('!B', self.data[offset])[0] obj_type, obj_info = (obj_header & 0xF0), (obj_header & 0x0F) int_sz = 2**obj_info return int_sz, self.__unpackIntStruct(int_sz, self.data[offset+1:offset+1+int_sz]) def __resolveIntSize(self, obj_info, offset): '''__resolveIntSize(obj_info, offset) -> (count, offset) Calculates count of objref* array entries and returns count and offset to first element ''' if obj_info == 0x0F: ofs, obj_count = self.__unpackIntMeta(offset+1) objref = offset+2+ofs else: obj_count = obj_info objref = offset+1 return obj_count, objref def __unpackFloatStruct(self, sz, s): '''__unpackFloatStruct(size, string) -> float Unpacks the float of given size (4 or 8 bytes) from string ''' if sz == 4: ot = '!f' elif sz == 8: ot = '!d' else: raise Exception('float unpack size '+str(sz)+' unsupported') return struct.unpack(ot, s)[0] def __unpackFloat(self, offset): '''__unpackFloat(offset) -> float Unpacks float field from plist at given offset ''' obj_header = struct.unpack('!B', self.data[offset])[0] obj_type, obj_info = (obj_header & 0xF0), (obj_header & 0x0F) int_sz = 2**obj_info return int_sz, self.__unpackFloatStruct(int_sz, self.data[offset+1:offset+1+int_sz]) def __unpackDate(self, offset): td = int(struct.unpack(">d", self.data[offset+1:offset+9])[0]) return datetime(year=2001,month=1,day=1) + timedelta(seconds=td) def __unpackItem(self, offset): '''__unpackItem(offset) Unpacks and returns an item from plist ''' obj_header = struct.unpack('!B', self.data[offset])[0] obj_type, obj_info = (obj_header & 0xF0), (obj_header & 0x0F) if obj_type == 0x00: if obj_info == 0x00: # null 0000 0000 return None elif obj_info == 0x08: # bool 0000 1000 // false return False elif obj_info == 0x09: # bool 0000 1001 // true return True elif obj_info == 0x0F: # fill 0000 1111 // fill byte raise Exception("0x0F Not Implemented") # this is really pad byte, FIXME else: raise Exception('unpack item type '+str(obj_header)+' at '+str(offset)+ 'failed') elif obj_type == 0x10: # int 0001 nnnn ... // # of bytes is 2^nnnn, big-endian bytes return self.__unpackInt(offset) elif obj_type == 0x20: # real 0010 nnnn ... // # of bytes is 2^nnnn, big-endian bytes return self.__unpackFloat(offset) elif obj_type == 0x30: # date 0011 0011 ... // 8 byte float follows, big-endian bytes return self.__unpackDate(offset) elif obj_type == 0x40: # data 0100 nnnn [int] ... // nnnn is number of bytes unless 1111 then int count follows, followed by bytes obj_count, objref = self.__resolveIntSize(obj_info, offset) return plistlib.Data(self.data[objref:objref+obj_count]) # XXX: we return data as str elif obj_type == 0x50: # string 0101 nnnn [int] ... // ASCII string, nnnn is # of chars, else 1111 then int count, then bytes obj_count, objref = self.__resolveIntSize(obj_info, offset) return self.data[objref:objref+obj_count] elif obj_type == 0x60: # string 0110 nnnn [int] ... // Unicode string, nnnn is # of chars, else 1111 then int count, then big-endian 2-byte uint16_t obj_count, objref = self.__resolveIntSize(obj_info, offset) return self.data[objref:objref+obj_count*2].decode('utf-16be') elif obj_type == 0x80: # uid 1000 nnnn ... // nnnn+1 is # of bytes # FIXME: Accept as a string for now obj_count, objref = self.__resolveIntSize(obj_info, offset) return plistlib.Data(self.data[objref:objref+obj_count]) elif obj_type == 0xA0: # array 1010 nnnn [int] objref* // nnnn is count, unless '1111', then int count follows obj_count, objref = self.__resolveIntSize(obj_info, offset) arr = [] for i in range(obj_count): arr.append(self.__unpackIntStruct(self.object_ref_size, self.data[objref+i*self.object_ref_size:objref+i*self.object_ref_size+self.object_ref_size])) return arr elif obj_type == 0xC0: # set 1100 nnnn [int] objref* // nnnn is count, unless '1111', then int count follows # XXX: not serializable via apple implementation raise Exception("0xC0 Not Implemented") # FIXME: implement elif obj_type == 0xD0: # dict 1101 nnnn [int] keyref* objref* // nnnn is count, unless '1111', then int count follows obj_count, objref = self.__resolveIntSize(obj_info, offset) keys = [] for i in range(obj_count): keys.append(self.__unpackIntStruct(self.object_ref_size, self.data[objref+i*self.object_ref_size:objref+i*self.object_ref_size+self.object_ref_size])) values = [] objref += obj_count*self.object_ref_size for i in range(obj_count): values.append(self.__unpackIntStruct(self.object_ref_size, self.data[objref+i*self.object_ref_size:objref+i*self.object_ref_size+self.object_ref_size])) dic = {} for i in range(obj_count): dic[keys[i]] = values[i] return dic else: raise Exception('don\'t know how to unpack obj type '+hex(obj_type)+' at '+str(offset)) def __resolveObject(self, idx): try: return self.resolved[idx] except KeyError: obj = self.objects[idx] if type(obj) == list: newArr = [] for i in obj: newArr.append(self.__resolveObject(i)) self.resolved[idx] = newArr return newArr if type(obj) == dict: newDic = {} for k,v in obj.iteritems(): rk = self.__resolveObject(k) rv = self.__resolveObject(v) newDic[rk] = rv self.resolved[idx] = newDic return newDic else: self.resolved[idx] = obj return obj def parse(self): # read header if self.data[:8] != 'bplist00': raise Exception('Bad magic') # read trailer self.offset_size, self.object_ref_size, self.number_of_objects, self.top_object, self.table_offset = struct.unpack('!6xBB4xI4xI4xI', self.data[-32:]) #print "** plist offset_size:",self.offset_size,"objref_size:",self.object_ref_size,"num_objs:",self.number_of_objects,"top:",self.top_object,"table_ofs:",self.table_offset # read offset table self.offset_table = self.data[self.table_offset:-32] self.offsets = [] ot = self.offset_table for i in xrange(self.number_of_objects): offset_entry = ot[:self.offset_size] ot = ot[self.offset_size:] self.offsets.append(self.__unpackIntStruct(self.offset_size, offset_entry)) #print "** plist offsets:",self.offsets # read object table self.objects = [] k = 0 for i in self.offsets: obj = self.__unpackItem(i) #print "** plist unpacked",k,type(obj),obj,"at",i k += 1 self.objects.append(obj) # rebuild object tree #for i in range(len(self.objects)): # self.__resolveObject(i) # return root object return self.__resolveObject(self.top_object) @classmethod def plistWithString(cls, s): parser = cls(s) return parser.parse() @classmethod def plistWithFile(cls, f): file = open(f,"rb") parser = cls(file.read()) file.close() return parser.parse()
Python
""" /************************************************************** LZSS.C -- A Data Compression Program *************************************************************** 4/6/1989 Haruhiko Okumura Use, distribute, and modify this program freely. Please send me your improved versions. PC-VAN SCIENCE NIFTY-Serve PAF01022 CompuServe 74050,1022 **************************************************************/ /* * lzss.c - Package for decompressing lzss compressed objects * * Copyright (c) 2003 Apple Computer, Inc. * * DRI: Josh de Cesare */ """ from array import array import struct N = 4096 F = 18 THRESHOLD = 2 NIL = N def decompress_lzss(str): if str[:8] !="complzss": print "decompress_lzss: complzss magic missing" return decompsize = struct.unpack(">L", str[12:16])[0] text_buf = array("B", " "*(N + F - 1)) src = array("B", str[0x180:]) srclen = len(src) dst = array("B", " "*decompsize) r = N - F srcidx, dstidx, flags, c = 0, 0, 0, 0 while True: flags >>= 1 if ((flags & 0x100) == 0): if (srcidx >= srclen): break c = src[srcidx]; srcidx += 1 flags = c | 0xFF00; if (flags & 1): if (srcidx >= srclen): break c = src[srcidx]; srcidx += 1 dst[dstidx] = c; dstidx += 1 text_buf[r] = c; r += 1 r &= (N - 1); else: if (srcidx >= srclen): break i = src[srcidx]; srcidx += 1 if (srcidx >= srclen): break j = src[srcidx]; srcidx += 1 i |= ((j & 0xF0) << 4) j = (j & 0x0F) + THRESHOLD for k in xrange(j+1): c = text_buf[(i + k) & (N - 1)] dst[dstidx] = c; dstidx += 1 text_buf[r] = c; r += 1 r &= (N - 1) return dst.tostring()
Python
import os import sys from util import sizeof_fmt, hexdump from progressbar import ProgressBar from crypto.aes import AESdecryptCBC, AESencryptCBC class FileBlockDevice(object): def __init__(self, filename, offset=0, write=False): flag = os.O_RDONLY if not write else os.O_RDWR if sys.platform == 'win32': flag = flag | os.O_BINARY self.filename = filename self.fd = os.open(filename, flag) self.offset = offset self.writeFlag = write self.size = os.path.getsize(filename) self.setBlockSize(8192) def setBlockSize(self, bs): self.blockSize = bs self.nBlocks = self.size / bs def readBlock(self, blockNum): off = self.offset + self.blockSize * blockNum if off > self.size: raise Exception("fail to seek at %d" % off) os.lseek(self.fd, off, os.SEEK_SET) return os.read(self.fd, self.blockSize) def write(self, offset, data): if self.writeFlag: #fail silently for testing os.lseek(self.fd, self.offset + offset, os.SEEK_SET) return os.write(self.fd, data) def writeBlock(self, lba, block): return self.write(lba*self.blockSize, block) class FTLBlockDevice(object): def __init__(self, nand, first_lba, last_lba, defaultKey=None): self.nand = nand self.pageSize = nand.pageSize self.blockSize = 0 #not used self.key = defaultKey self.lbaoffset = first_lba self.last_lba = last_lba self.setBlockSize(self.pageSize) def setBlockSize(self, bs): self.blockSize = bs self.lbasPerPage = self.pageSize / bs self.lbaToLpnFactor = bs / (self.pageSize+0.0) self.pagesPerLBA = bs / self.pageSize if bs > self.pageSize: pass#raise Exception("FTLBlockDevice lba-size > pageSize not handled") def readBlock(self, blockNum): #if (self.lbaoffset + blockNum / self.lbasPerPage) > self.last_lba: # print "readBlock past last lba", blockNum # print "readBlock past last lba", blockNum # return "\x00" * self.blockSize lpn = int(self.lbaoffset + blockNum * self.lbaToLpnFactor) d = self.nand.readLPN(lpn, self.key) for i in xrange(1, self.pagesPerLBA): d += self.nand.readLPN(lpn + i, self.key) if self.lbasPerPage: zz = blockNum % self.lbasPerPage return d[zz*self.blockSize:(zz+1)*self.blockSize] return d def write(self, offset, data): raise Exception("FTLBlockDevice write method not implemented") def writeBlock(self, lba, block): raise Exception("FTLBlockDevice writeBlock method not implemented") def dumpToFile(self, outputfilename): hs = sizeof_fmt((self.last_lba - self.lbaoffset) * self.pageSize) print "Dumping partition to %s (%s)" % (outputfilename, hs) flags = os.O_CREAT | os.O_RDWR if sys.platform == "win32": flags |= os.O_BINARY fd=os.open(outputfilename, flags) pbar = ProgressBar(self.last_lba - self.lbaoffset - 1) pbar.start() for i in xrange(self.lbaoffset, self.last_lba): pbar.update(i-self.lbaoffset) d = self.nand.readLPN(i, self.key) if i == self.lbaoffset and d[0x400:0x402] != "HX": print "FAIL? Not HFS partition or wrong key" os.write(fd, d) pbar.finish() os.close(fd) class IMG3BlockDevice(object): def __init__(self, filename, key, iv, write=False): flag = os.O_RDONLY if not write else os.O_RDWR if sys.platform == 'win32': flag = flag | os.O_BINARY self.filename = filename self.fd = os.open(filename, flag) self.writeFlag = write d = os.read(self.fd, 8192) if d[:4] != "3gmI": raise Exception("IMG3BlockDevice bad magic %s" % d[:4]) if d[0x34:0x38] != "ATAD": raise Exception("Fu") self.encrypted = True self.key = key self.iv0 = iv self.offset = 0x40 self.size = os.path.getsize(filename) self.setBlockSize(8192) def setBlockSize(self, bs): self.blockSize = bs self.nBlocks = self.size / bs self.ivs = {0: self.iv0} def getIVforBlock(self, blockNum): #read last 16 bytes of previous block to get IV if not self.ivs.has_key(blockNum): os.lseek(self.fd, self.offset + self.blockSize * blockNum - 16, os.SEEK_SET) self.ivs[blockNum] = os.read(self.fd, 16) return self.ivs[blockNum] def readBlock(self, blockNum): os.lseek(self.fd, self.offset + self.blockSize * blockNum, os.SEEK_SET) data = os.read(self.fd, self.blockSize) if self.encrypted: data = AESdecryptCBC(data, self.key, self.getIVforBlock(blockNum)) return data def _write(self, offset, data): if self.writeFlag: #fail silently for testing os.lseek(self.fd, self.offset + offset, os.SEEK_SET) return os.write(self.fd, data) def writeBlock(self, lba, data): if self.encrypted: data = AESencryptCBC(data, self.key, self.getIVforBlock(lba)) return self._write(lba*self.blockSize, data)
Python
def print_table(title, headers, rows): widths = [] for i in xrange(len(headers)): z = map(len, [str(row[i]) for row in rows]) z.append(len(headers[i])) widths.append(max(z)) width = sum(widths) + len(headers) + 1 print "-"* width print "|" + title.center(width-2) + "|" print "-"* width hline = "|" for i in xrange(len(headers)): hline += headers[i].ljust(widths[i]) + "|" print hline print "-"* width for row in rows: line = "|" for i in xrange(len(row)): line += str(row[i]).ljust(widths[i]) + "|" print line if len(rows) == 0: print "|" + "No entries".center(width-2) + "|" print "-"* width print ""
Python
import glob import plistlib import os from bplist import BPlistReader import cPickle import gzip def read_file(filename): f = open(filename, "rb") data = f.read() f.close() return data def write_file(filename,data): f = open(filename, "wb") f.write(data) f.close() def makedirs(dirs): try: os.makedirs(dirs) except: pass def getHomePath(foldername, filename): home = os.path.expanduser('~') folderpath = os.path.join(home, foldername) if not os.path.exists(folderpath): makedirs(folderpath) return os.path.join(folderpath, filename) def readHomeFile(foldername, filename): path = getHomePath(foldername, filename) if not os.path.exists(path): return None return read_file(path) #return path to HOME+foldername+filename def writeHomeFile(foldername, filename, data): filepath = getHomePath(foldername, filename) write_file(filepath, data) return filepath def readPlist(filename): f = open(filename,"rb") d = f.read(16) f.close() if d.startswith("bplist"): return BPlistReader.plistWithFile(filename) else: return plistlib.readPlist(filename) def parsePlist(s): if s.startswith("bplist"): return BPlistReader.plistWithString(s) else: return plistlib.readPlistFromString(s) #http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size def sizeof_fmt(num): for x in ['bytes','KB','MB','GB','TB']: if num < 1024.0: return "%d%s" % (num, x) num /= 1024.0 #http://www.5dollarwhitebox.org/drupal/node/84 def convert_bytes(bytes): bytes = float(bytes) if bytes >= 1099511627776: terabytes = bytes / 1099511627776 size = '%.2fT' % terabytes elif bytes >= 1073741824: gigabytes = bytes / 1073741824 size = '%.2fG' % gigabytes elif bytes >= 1048576: megabytes = bytes / 1048576 size = '%.2fM' % megabytes elif bytes >= 1024: kilobytes = bytes / 1024 size = '%.2fK' % kilobytes else: size = '%.2fb' % bytes return size def xor_strings(a,b): r="" for i in xrange(len(a)): r+= chr(ord(a[i])^ord(b[i])) return r hex = lambda data: " ".join("%02X" % ord(i) for i in data) ascii = lambda data: "".join(c if 31 < ord(c) < 127 else "." for c in data) def hexdump(d): for i in xrange(0,len(d),16): data = d[i:i+16] print "%08X | %s | %s" % (i, hex(data).ljust(47), ascii(data)) def search_plist(directory, matchDict): for p in map(os.path.normpath, glob.glob(directory + "/*.plist")): try: d = plistlib.readPlist(p) ok = True for k,v in matchDict.items(): if d.get(k) != v: ok = False break if ok: print "Using plist file %s" % p return d except: continue def save_pickle(filename,data): f = gzip.open(filename,"wb") cPickle.dump(data, f, cPickle.HIGHEST_PROTOCOL) f.close() def load_pickle(filename): f = gzip.open(filename,"rb") data = cPickle.load(f) f.close() return data
Python
#!/usr/bin/python from optparse import OptionParser from keystore.keybag import Keybag from keychain import keychain_load from keychain.managedconfiguration import bruteforce_old_pass from util import readPlist from keychain.keychain4 import Keychain4 import plistlib def main(): parser = OptionParser(usage="%prog keychain.db/keychain-backup.plist keyfile.plist/Manifest.plist") parser.add_option("-d", "--display", dest="display", action="store_true", default=False, help="Show keychain items on stdout") parser.add_option("-s", "--sanitize", dest="sanitize", action="store_true", default=False, help="Hide secrets on stdout with ***") parser.add_option("-p", "--passwords", dest="passwords", action="store_true", default=False, help="Save generic & internet passwords as CSV file") parser.add_option("-c", "--certs", dest="certs", action="store_true", default=False, help="Extract certificates and keys") parser.add_option("-o", "--old", dest="oldpass", action="store_true", default=False, help="Bruteforce old passcodes") (options, args) = parser.parse_args() if len(args) < 2: parser.print_help() return p = readPlist(args[1]) if p.has_key("BackupKeyBag"): deviceKey = None if p.has_key("key835"): deviceKey = p["key835"].decode("hex") else: if not p["IsEncrypted"]: print "This backup is not encrypted, without key 835 nothing in the keychain can be decrypted" print "If you have key835 for device %s enter it (in hex)" % p["Lockdown"]["UniqueDeviceID"] d = raw_input() if len(d) == 32: p["key835"] = d deviceKey = d.decode("hex") plistlib.writePlist(p, args[1]) kb = Keybag.createWithBackupManifest(p, p.get("password",""), deviceKey) if not kb: return k = Keychain4(args[0], kb) else: kb = Keybag.createWithPlist(p) k = keychain_load(args[0], kb, p["key835"].decode("hex")) if options.display: k.print_all(options.sanitize) if options.passwords: k.save_passwords() if options.certs: k.save_certs_keys() if options.oldpass: mc = k.get_managed_configuration() if not mc: print "Managed configuration not found" return print "Bruteforcing %d old passcodes" % len(mc.get("history",[])) for h in mc["history"]: p = bruteforce_old_pass(h) if p: print "Found : %s" % p else: print "Not Found" if __name__ == "__main__": main()
Python
from store import PlistKeychain, SQLiteKeychain from util import write_file from util.asciitables import print_table from util.bplist import BPlistReader from util.cert import RSA_KEY_DER_to_PEM, CERT_DER_to_PEM import M2Crypto import hashlib import plistlib import sqlite3 import string import struct KSECATTRACCESSIBLE = { 6: "kSecAttrAccessibleWhenUnlocked", 7: "kSecAttrAccessibleAfterFirstUnlock", 8: "kSecAttrAccessibleAlways", 9: "kSecAttrAccessibleWhenUnlockedThisDeviceOnly", 10: "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly", 11: "kSecAttrAccessibleAlwaysThisDeviceOnly" } printset = set(string.printable) def render_password(p): data = p["data"] if data != None and data.startswith("bplist") and data.find("\x00") != -1: pl = BPlistReader.plistWithString(p["data"]) filename = "%s_%s_%d.plist" % (p["svce"],p["acct"],p["rowid"]) plistlib.writePlist(pl, filename) #write_file("bin_"+filename, p["data"]) data = filename if p.has_key("srvr"): return "%s:%d;%s;%s" % (p["srvr"],p["port"],p["acct"],data) else: return "%s;%s;%s" % (p["svce"],p["acct"],data) class Keychain(object): def __init__(self, filename): magic = open(filename, "rb").read(16) if magic.startswith("SQLite"): self.store = SQLiteKeychain(filename) elif magic.startswith("bplist"): self.store = PlistKeychain(filename) else: raise Exception("Unknown keychain format for %s" % filename) self.bsanitize = True self.items = {"genp": None, "inet": None, "cert": None, "keys": None} def decrypt_data(self, data): return data #override this method def decrypt_item(self, res): res["data"] = self.decrypt_data(res["data"]) if not res["data"]: return {} return res def get_items(self, table): if self.items[table]: return self.items[table] self.items[table] = filter(lambda x:x!={}, map(self.decrypt_item, self.store.get_items(table))) return self.items[table] def get_passwords(self): return self.get_items("genp") def get_inet_passwords(self): return self.get_items("inet") def get_keys(self): return self.get_items("keys") def get_cert(self): return self.get_items("cert") def get_certs(self): certs = {} pkeys = {} keys = self.get_keys() for row in self.get_cert(): cert = M2Crypto.X509.load_cert_der_string(row["data"]) subject = cert.get_subject().as_text() common_name = cert.get_subject().get_entries_by_nid(M2Crypto.X509.X509_Name.nid['CN']) if len(common_name): subject = str(common_name[0].get_data()) else: subject = "cn_unknown_%d" % row["rowid"] certs[subject+ "_%s" % row["agrp"]] = cert #print subject #print "Access :\t" + KSECATTRACCESSIBLE.get(row["clas"]) for k in keys: if k["agrp"] == row["agrp"] and k["klbl"] == row["pkhh"]: pkey_der = k["data"] pkey_der = RSA_KEY_DER_to_PEM(pkey_der) pkeys[subject + "_%s" % row["agrp"]] = pkey_der break return certs, pkeys def save_passwords(self): passwords = "\n".join(map(render_password, self.get_passwords())) inetpasswords = "\n".join(map(render_password, self.get_inet_passwords())) print "Writing passwords to keychain.csv" write_file("keychain.csv", "Passwords;;\n"+passwords+"\nInternet passwords;;\n"+ inetpasswords) def save_certs_keys(self): certs, pkeys = self.get_certs() for c in certs: filename = c + ".crt" print "Saving certificate %s" % filename certs[c].save_pem(filename) for k in pkeys: filename = k + ".key" print "Saving key %s" % filename write_file(filename, pkeys[k]) def sanitize(self, pw): if pw.startswith("bplist"): return "<binary plist data>" elif not set(pw).issubset(printset): pw = ">"+ pw.encode("hex") #pw = "<binary data> : " + pw.encode("hex") if self.bsanitize: return pw[:2] + ("*" * (len(pw) - 2)) return pw def print_all(self, sanitize=True): self.bsanitize = sanitize headers = ["Service", "Account", "Data", "Access group", "Protection class"] rows = [] for p in self.get_passwords(): row = [p.get("svce","?"), str(p.get("acct","?"))[:40], self.sanitize(p.get("data","?"))[:20], p.get("agrp","?"), KSECATTRACCESSIBLE.get(p["clas"])[18:]] rows.append(row) print_table("Passwords", headers, rows) headers = ["Server", "Account", "Data", "Access group", "Protection class"] rows = [] for p in self.get_inet_passwords(): addr = "?" if p.has_key("srvr"): addr = p["srvr"] + ":" + str(p["port"]) row = [addr, str(p.get("acct","?")), self.sanitize(p.get("data","?"))[:20], p.get("agrp","?"), KSECATTRACCESSIBLE.get(p["clas"])[18:]] rows.append(row) print_table("Internet Passwords", headers, rows) headers = ["Id", "Common Name", "Access group", "Protection class"] rows = [] c = {} for row in self.get_cert(): subject = "?" if row.has_key("data"): cert = M2Crypto.X509.load_cert_der_string(row["data"]) subject = cert.get_subject().as_text() common_name = cert.get_subject().get_entries_by_nid(M2Crypto.X509.X509_Name.nid['CN']) if len(common_name): subject = str(common_name[0].get_data()) else: subject = "cn_unknown_%d" % row["rowid"] c[hashlib.sha1(str(row["pkhh"])).hexdigest() + row["agrp"]] = subject row = [str(row["rowid"]), subject[:81], row.get("agrp","?")[:31], KSECATTRACCESSIBLE.get(row["clas"])[18:] ] rows.append(row) print_table("Certificates", headers, rows) headers = ["Id", "Label", "Common Name", "Access group", "Protection class"] rows = [] for row in self.get_keys(): subject = "" if row.has_key("klbl"): subject = c.get(hashlib.sha1(str(row["klbl"])).hexdigest() + row["agrp"], "") row = [str(row["rowid"]), row.get("labl", "?")[:30], subject[:39], row.get("agrp","?")[:31], KSECATTRACCESSIBLE.get(row["clas"])[18:]] rows.append(row) print_table("Keys", headers, rows) def get_push_token(self): for p in self.get_passwords(): if p["svce"] == "push.apple.com": return p["data"] def get_managed_configuration(self): for p in self.get_passwords(): if p["acct"] == "Private" and p["svce"] == "com.apple.managedconfiguration" and p["agrp"] == "apple": return BPlistReader.plistWithString(p["data"]) def _diff(self, older, res, func, key): res.setdefault(key, []) current = func(self) for p in func(older): if not p in current and not p in res[key]: res[key].append(p) def diff(self, older, res): self._diff(older, res, Keychain.get_passwords, "genp") self._diff(older, res, Keychain.get_inet_passwords, "inet") self._diff(older, res, Keychain.get_cert, "cert") self._diff(older, res, Keychain.get_keys, "keys") def cert(self, rowid, filename=""): for row in self.get_cert(): if row["rowid"] == rowid: blob = CERT_DER_to_PEM(row["data"]) if filename: write_file(filename, blob) cert = M2Crypto.X509.load_cert_der_string(row["data"]) print cert.as_text() return def key(self, rowid, filename=""): for row in self.get_keys(): if row["rowid"] == rowid: blob = RSA_KEY_DER_to_PEM(row["data"]) if filename: write_file(filename, blob) #k = M2Crypto.RSA.load_key_string(blob) print blob return
Python
from crypto.aes import AESdecryptCBC import struct """ iOS 4 keychain-2.db data column format version 0x00000000 key class 0x00000008 kSecAttrAccessibleWhenUnlocked 6 kSecAttrAccessibleAfterFirstUnlock 7 kSecAttrAccessibleAlways 8 kSecAttrAccessibleWhenUnlockedThisDeviceOnly 9 kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly 10 kSecAttrAccessibleAlwaysThisDeviceOnly 11 wrapped AES256 key 0x28 bytes (passed to kAppleKeyStoreKeyUnwrap) encrypted data (AES 256 CBC zero IV) """ from keychain import Keychain from crypto.gcm import gcm_decrypt from util.bplist import BPlistReader KSECATTRACCESSIBLE = { 6: "kSecAttrAccessibleWhenUnlocked", 7: "kSecAttrAccessibleAfterFirstUnlock", 8: "kSecAttrAccessibleAlways", 9: "kSecAttrAccessibleWhenUnlockedThisDeviceOnly", 10: "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly", 11: "kSecAttrAccessibleAlwaysThisDeviceOnly" } class Keychain4(Keychain): def __init__(self, filename, keybag): if not keybag.unlocked: print "Keychain object created with locked keybag, some items won't be decrypted" Keychain.__init__(self, filename) self.keybag = keybag def decrypt_item(self, row): version, clas = struct.unpack("<LL", row["data"][0:8]) if self.keybag.isBackupKeybag(): if clas >= 9 and not self.keybag.deviceKey: return {} if version >= 2: dict = self.decrypt_blob(row["data"]) if not dict: return {"clas": clas, "rowid": row["rowid"]} if dict.has_key("v_Data"): dict["data"] = dict["v_Data"].data else: dict["data"] = "" dict["rowid"] = row["rowid"] dict["clas"] = clas return dict row["clas"] = clas return Keychain.decrypt_item(self, row) def decrypt_data(self, data): data = self.decrypt_blob(data) if type(data) == dict: return data["v_Data"].data return data def decrypt_blob(self, blob): if blob == None: return "" if len(blob) < 48: print "keychain blob length must be >= 48" return version, clas = struct.unpack("<LL",blob[0:8]) self.clas=clas if version == 0: wrappedkey = blob[8:8+40] encrypted_data = blob[48:] elif version == 2: l = struct.unpack("<L",blob[8:12])[0] wrappedkey = blob[12:12+l] encrypted_data = blob[12+l:-16] else: raise Exception("unknown keychain verson ", version) return unwrappedkey = self.keybag.unwrapKeyForClass(clas, wrappedkey, False) if not unwrappedkey: return if version == 0: return AESdecryptCBC(encrypted_data, unwrappedkey, padding=True) elif version == 2: binaryplist = gcm_decrypt(unwrappedkey, "", encrypted_data, "", blob[-16:]) return BPlistReader(binaryplist).parse()
Python
""" 0 1:MCSHA256DigestWithSalt 2:SecKeyFromPassphraseDataHMACSHA1 """ from crypto.PBKDF2 import PBKDF2 import plistlib import hashlib SALT1 = "F92F024CA2CB9754".decode("hex") hashMethods={ 1: (lambda p,salt:hashlib.sha256(SALT1 + p)), 2: (lambda p,salt:PBKDF2(p, salt, iterations=1000).read(20)) } def bruteforce_old_pass(h): salt = h["salt"].data hash = h["hash"].data f = hashMethods.get(h["hashMethod"]) if f: print "Bruteforcing hash %s (4 digits)" % hash.encode("hex") for i in xrange(10000): p = "%04d" % (i % 10000) if f(p,salt) == hash: return p
Python
import plistlib import sqlite3 import struct from util import readPlist class KeychainStore(object): def __init__(self): pass def convertDict(self, d): return d def returnResults(self, r): for a in r: yield self.convertDict(a) def get_items(self, table): return [] class SQLiteKeychain(KeychainStore): def __init__(self, filename): self.conn = sqlite3.connect(filename) self.conn.row_factory = sqlite3.Row def convertDict(self, row): d = dict(row) for k,v in d.items(): if type(v) == buffer: d[k] = str(v) return d def get_items(self, table): sql = {"genp": "SELECT rowid, data, svce, acct, agrp FROM genp", "inet": "SELECT rowid, data, acct, srvr, port, agrp FROM inet", "cert": "SELECT rowid, data, pkhh, agrp FROM cert", "keys": "SELECT rowid, data, klbl, agrp FROM keys"} return self.returnResults(self.conn.execute(sql[table])) class PlistKeychain(KeychainStore): def __init__(self, filename): self.plist = readPlist(filename) def convertDict(self, d): for k, v in d.items(): if isinstance(v, plistlib.Data): if k == "v_Data": d["data"] = v.data elif k == "v_PersistentRef": #format tablename (4 chars) + rowid (64 bits) d["rowid"] = struct.unpack("<Q", v.data[-8:])[0] else: d[k] = v.data return d def get_items(self, table): return self.returnResults(self.plist.get(table, []))
Python
import sqlite3 from keychain3 import Keychain3 from keychain4 import Keychain4 def keychain_load(filename, keybag, key835): version = sqlite3.connect(filename).execute("SELECT version FROM tversion").fetchone()[0] #print "Keychain version : %d" % version if version == 3: return Keychain3(filename, key835) elif version >= 4: return Keychain4(filename, keybag) raise Exception("Unknown keychain version %d" % version)
Python
from keychain import Keychain from crypto.aes import AESdecryptCBC, AESencryptCBC import hashlib class Keychain3(Keychain): def __init__(self, filename, key835=None): Keychain.__init__(self, filename) self.key835 = key835 def decrypt_data(self, data): if data == None: return "" data = str(data) if not self.key835: print "Key 835 not availaible" return "" data = AESdecryptCBC(data[16:], self.key835, data[:16], padding=True) #data_column = iv + AES128_K835(iv, data + sha1(data)) if hashlib.sha1(data[:-20]).digest() != data[-20:]: print "data field hash mismatch : bad key ?" return "ERROR decrypting data : bad key ?" return data[:-20] def change_key835(self, newkey): tables = {"genp": "SELECT rowid, data FROM genp", "inet": "SELECT rowid, data FROM inet", "cert": "SELECT rowid, data FROM cert", "keys": "SELECT rowid, data FROM keys"} for t in tables.keys(): for row in self.conn.execute(tables[t]): rowid = row["rowid"] data = str(row["data"]) iv = data[:16] data = AESdecryptCBC(data[16:], self.key835, iv) data = AESencryptCBC(data, newkey, iv) data = iv + data data = buffer(data) self.conn.execute("UPDATE %s SET data=? WHERE rowid=?" % t, (data, rowid)) self.conn.commit()
Python
#!/usr/bin/env python '''Fisheries Economics Masterclass model''' import threading import wx from pylab import * import copy class Parameter(dict): """ Model parameter class A simple dict with some default values """ def __init__(self,value=0,min=0,max=1,units='',title='',description='',type='Miscellaneous',scale=1,scale_text=''): """Initialise the parameter""" self['value'] = value self['min'] = min self['max'] = max self['units'] = units self['title'] = title self['description'] = description self['type'] = type self['scale'] = scale self['scale_text']=scale_text class Component: """ Model component class All model classes should inherit this """ def get_parameters(self): """ Returns the parameters required by this component The format is a dictionary, keys are parameter name, value is a list of minimum value, maximum value, default value, """ return {} def execute(self,state,parameters): """Executes this component and returns the modified state""" return state class PDLogistic(Component): """Population Dynamics Logistic growth component""" def __init__(self): self.r = Parameter(title='Population growth rate', description='The maximum growth rate of the population', type='Population dynamics') self.K = Parameter(title='Maximum population size', description='The size of a unfished (virgin) population', type='Population dynamics') def get_parameters(self): return {'r': self.r,'K': self.K} #Execute a logistic step def execute(self,state,parameters,equilibrium=False): if equilibrium: r = parameters['r'] K = parameters['K'] if parameters.has_key('catch'): C = parameters['catch'] # [r-1 + (1-2r+r2+4Cr/K)^.5]/(2r/K) term = (r)**2-4*C*r/K #term = (1-4*parameters['catch']/parameters['r']/parameters['K']) if term < 0: state['biomass'][-1] = 0 else: #state['biomass'][-1] = parameters['K']/2*(1+term**0.5)#+parameters['catch'] #Catch is added back on as the catch step removes it state['biomass'][-1] = (r+term**.5)/(2*r/K) state['biomass'][-1] += parameters['catch'] #Catch is added back on as the catch step removes it else: catch = state['biomass'][-1]* parameters['catch_rate']*parameters['effort']/parameters['K'] state['biomass'][-1] = parameters['K']-parameters['catch_rate']*parameters['effort']/parameters['r'] state['biomass'][-1] += catch #state['biomass'][-1] = K*(1-r) else: b = state['biomass'][-1] state['biomass'][-1] = b+b*parameters['r']*(1-b/parameters['K']) return state #Catch component removes catch determines CPUE class CatchFixed(Component): """Fixed catch component with simplistic CPUE/effort calculation""" catch_rate = Parameter(title='Max catch rate', description='The biomass caught per unit of effort', type='Fleet dynamics') catch = Parameter(title='TAC', description='Total allowable catch', type='Management Controls' ) def get_parameters(self): return {'catch_rate': self.catch_rate, 'catch': self.catch} def execute(self,state,parameters,equilibrium=False): preCatchBiomass = state.get('biomass') previousBiomass = state['biomass'][-2] state.set(cpue=previousBiomass/parameters['K']*parameters['catch_rate']) state.set(biomass=preCatchBiomass-parameters['catch']) state.set(catch=parameters['catch']) if state.get('biomass') < 0: state.set(biomass=0,catch= preCatchBiomass) if state.get('cpue') <= 0: state.set(effort=0) else: state.set(effort=state.get('catch')/state.get('cpue')) return state #Constant effort class EffortFixed(Component): """Fixed catch component with simplistic CPUE/effort calculation""" catch_rate = Parameter(title='Max catch rate', description='The biomass caught per unit of effort', type='Fleet dynamics') effort = Parameter( title='Effort', description='Fishing effort', type='Management Controls' ) def get_parameters(self): return {'catch_rate': self.catch_rate, 'effort': self.effort} def execute(self,state,parameters,equilibrium=False): previousBiomass = state['biomass'][-2] preCatchBiomass = state['biomass'][-1] state.set(cpue=previousBiomass/parameters['K']*parameters['catch_rate']) state.set(catch=parameters['effort']*state.get('cpue')) state.set(biomass=preCatchBiomass-state.get('catch')) if state.get('biomass') < 0: state.set(biomass=0,catch= preCatchBiomass) state.set(effort=parameters['effort']) return state class Economics(Component): fixed_cost = Parameter( title='Operator fixed cost', description='An individual operator\s fixed annual cost', type='Economics') marginal_cost= Parameter( title='Operator marginal cost', description='An individual operator\s marginal cost per unit effort', type='Economics') movement_rate= Parameter( title='Fleet resize rate', description='The maximum rate at which vessels can enter or exit the fishery', type='Fleet dynamics') beach_price = Parameter( title='Beach price', description='The price per kg of landed fish', type='Economics') discount_rate = Parameter( title='Discount Rate', description='The discount rate', type='Economics') def get_parameters(self): return {'fixed_cost': self.fixed_cost, 'marginal_cost': self.marginal_cost, 'movement_rate': self.movement_rate, 'beach_price': self.beach_price, 'discount_rate': self.discount_rate} @staticmethod def _calculate_revenue(state,parameters): return state.get('catch')*parameters['beach_price'] @staticmethod def _calculate_cost(state,parameters): return (state.get('fleet_size')*parameters['fixed_cost']+\ state.get('effort')*parameters['marginal_cost']) @staticmethod def _calculate_profit(state,parameters): return Economics._calculate_revenue(state,parameters)-Economics._calculate_cost(state,parameters) def execute(self,state,parameters,equilibrium=False): #Adjust the fleet size original_fleet_size = state.get('fleet_size') while abs(self._calculate_profit(state,parameters))>parameters['fixed_cost'] and \ ((equilibrium and parameters['movement_rate'] > 0) or abs(original_fleet_size - state.get('fleet_size')) < parameters['movement_rate']): if self._calculate_profit(state,parameters) > 0: state.set(fleet_size = state.get('fleet_size')+1) else: state.set(fleet_size = state.get('fleet_size')-1) #Set the cost, revenue and profit state.set(cost = self._calculate_cost(state, parameters)) state.set(revenue = self._calculate_revenue(state,parameters)) profit = state.get('revenue')-state.get('cost') if abs(profit)<1000000: profit = 0 state.set(profit = profit) state.set(discounted_profit = profit*(1-parameters['discount_rate'])**(len(state['cost'])-2)) return state class State(dict): """Model state A dictionary where each key corresponds to an attribute of a fishery state (eg. biomass) all keys are the same length and can be extended trivially """ def __init__(self, attributes): """ Constructor attribute_list is a dictionary for the attributes of the fishery see example fishery models for details """ for key in attributes: self[key] = [nan] self.attributes = attributes self.attribute_order = self.attributes.keys() #The attributes to plot first up by default self.default_plot = self.attributes.keys() self.unit_order = [] units = {} for att in self.attributes: unit = self.attributes[att]['units'] if not units.has_key(unit): units[unit]=1 self.unit_order.append(unit) def extend(self): """Extend all the lists by one, using the previous value for the new value""" for att in self: self[att].append(self[att][-1]) return def set(self,**kwargs): """Set the current (last item) of one or more of the lists""" for key in kwargs: self[key][-1]=kwargs[key] def get(self,item): """Get the current (last item) of one of the lists""" return self[item][-1] def get_attribute_title(self,attribute): return self.attributes[attribute]['title'] def get_attribute_units(self,attribute): return self.attributes[attribute]['units'] def reset(self): """ Resets the state to the initial timestep """ for att in self: self[att]=self[att][0:1] return class Model(): """Model Definition By combining a set of model functions this class creates a complete model definition""" def __init__(self,functions=[],parameters={},initial_state = None,convergence_time=3): """ functions: a list of functions in the order that they are to be run parameters: a dict of parameters as required by the functions (can be set later) initial_state: initial state of the fishery convergence_time: number of steps required to convergence of static version """ if initial_state == None: self.state = State() else: self.state = initial_state self.functions = functions self.parameters = parameters self.convergence_time = convergence_time def get_parameters(self): """ returns a list of parameters as required by the model functions """ #Get all parameters pOut = {} for function in self.functions: pOut.update(function.get_parameters()) #Replace values with current if applicable for param in pOut: if self.parameters.has_key(param): pOut[param].value = self.parameters[param] return pOut def set_parameters(self,parameters): """ set the parameters to a given value for this and subsequent time steps """ self.parameters = parameters def get_parameter_types(self): """ return a list of parameter types """ types = {} p = self.get_parameters() for par in p: types[p[par]['type']] = 1 return types.keys() def set_state(self,state): """ set the state of the model """ self.state = state def reset(self): """ Resets the model state to the initial timestep """ self.state.reset() def run(self,steps = 1,constant_variable=None): """ run the model for one time step """ for step in range(0,steps): self.state.extend() for function in self.functions: self.state=function.execute(self.state,self.parameters,equilibrium=constant_variable!=None) class MultiThreadModelRun: class MyThread(threading.Thread): def __init__(self,function): '''Initialise the thread: function: a function to be called after run completion ''' threading.Thread.__init__(self) self.function = function self.update = False self.cancel_run = False def update_run(self,model,steps,options): '''Start a new run model: the model to use options: the run options ''' self.newmodel = copy.deepcopy(model) self.newsteps = steps self.newoptions = options self.update = True def run(self): '''The thread's run function''' import time while True: #Cancelling the thread's run for now if self.cancel_run: self.cancel_run = False self.update = False #Creating a new run if self.update: self.model = self.newmodel self.options = self.newoptions self.steps = self.newsteps self.update = False for step in range(0,self.steps): if self.update: break self.single_iteration(step) if not self.update: if not self.function==None: wx.CallAfter(self.function,self.output()) else: time.sleep(0.01) pass def cancel(self): '''Cancel this run''' self.update = True self.cancel_run = True def single_iteration(self,step): '''Perform a single iteration (to be implemented by inheriting class)''' pass def output(self): '''Return the model output (to be implemented by inheriting class)''' pass class DynamicThread(MyThread): '''Thread for dynamic model runs''' def single_iteration(self,step): '''Run a single time step''' self.model.run(1) def output(self): '''Return the model state''' return self.model.state class StaticThread(MyThread): '''Thread for static model runs''' def update_run(self,model,steps,options): '''Update the run, copying a new output state as well''' #MultiThreadModelRun.MyThread.update_run(self,model,steps,options) self.newmodel = copy.deepcopy(model) self.newsteps = steps self.newoptions = options self.update = True self.output_state = copy.deepcopy(self.newmodel.state) self.output_state.reset() def single_iteration(self,step): '''Find an equilibrium state for a single independent parameter value''' #Reset the model self.model.reset() #Set the independent value to the appropriate value self.model.state[self.options['independent_variable']] = [self.options['independent_values'][step]] self.model.parameters[self.options['independent_variable']] = self.options['independent_values'][step] self.model.run(self.options['convergence_time'],constant_variable = self.options['independent_variable']) if True: #self.model.state[self.options['independent_variable']][-1] == self.options['independent_values'][step]: for param in self.model.state.keys(): self.output_state[param].append(self.model.state[param][-1]) if self.model.state[self.options['independent_variable']][-1] < self.options['independent_values'][step]: print 'a' self.output_state[self.options['independent_variable']][-1] = self.options['independent_values'][step-1]+1e-6 # self.output_state[self.options['independent_variable']][-1] = self.options['independent_values'][step] def output(self): '''Return the output state''' return self.output_state def __init__(self,function=None): self.static_thread = self.StaticThread(function) self.static_thread.start() self.dynamic_thread = self.DynamicThread(function) self.dynamic_thread.start() def run(self,model,steps,dynamic=True,independent_variable='effort',independent_minimum = 0,independent_maximum = None,convergence_time=4): if dynamic: self.static_thread.cancel() self.dynamic_thread.update_run(model,steps,{}) else: self.dynamic_thread.cancel() self.static_thread.update_run(model,steps, { 'independent_variable': independent_variable, 'independent_values': linspace(independent_minimum,independent_maximum,steps), 'convergence_time':convergence_time}) def lobsterModel(control_type = 'catch'): '''A lobster model, loosely based on the Tasmanian Rock Lobster Fishery''' #------------------------------------------ #Parameter values customised for this model #------------------------------------------ r = {'value':1,'min':0,'max':2} K = {'value':7000000,'min':0,'max':10000000,'scale':1000,'units':'t'} catch_rate ={'value':1,'min':0.001,'max':5,'units':'kg/potlift'} catch = {'value':1500000,'min':0,'max':6000000,'scale':1000,'units':'t'} effort = {'value':1500000,'min':0,'max':5000000,'description':'Number of potlifts','scale':1e6,'scale_text':'millions'} fixed_cost ={'value':100000,'min':50000,'max':200000,'units':'$/year','scale':1000,'scale_text':'thousands'} marginal_cost= {'value':30,'min':5,'max':50,'units':'$/potlift'} movement_rate={'value':0,'min':0,'max':20,'units':'vessels/year'} beach_price = {'value':60,'min':0,'max':100,'units':'$/kg'} discount_rate = {'value':0.07,'min':0,'max':1,'units':''} #----------------------------------------- #Functions that control the model dynamics #----------------------------------------- #Discrete logistic growth growthClass = PDLogistic() growthClass.r.update(r) growthClass.K.update(K) #Catch component if control_type == 'catch': catchClass = CatchFixed() catchClass.catch.update(catch) elif control_type == 'effort': catchClass = EffortFixed() catchClass.effort.update(effort) catchClass.catch_rate.update(catch_rate) #Economics and fleet dynamics economicsClass = Economics() economicsClass.fixed_cost.update(fixed_cost) economicsClass.marginal_cost.update(marginal_cost) economicsClass.movement_rate.update(movement_rate) economicsClass.beach_price.update(beach_price) economicsClass.discount_rate.update(discount_rate) #----------------------------------------- #Set the state of the fishery #The attributes here must match what is #required by the functions PDLogistic, #CatchFixed/EffortFixed and Economics #----------------------------------------- initial_state = State( attributes = {'biomass': {'title': 'Biomass', 'units': 'tonnes','scale':1000}, 'catch': {'title': 'Catch', 'units': 'tonnes','scale':1000}, 'cpue': {'title': 'CPUE', 'units': 'kg/potlift','scale':1}, 'effort': {'title': 'Effort', 'units': 'millions of potlifts','scale':1e6}, 'fleet_size': {'title': 'Fleet Size','units': '# vessels','scale':1}, 'revenue': {'title': 'Revenue','units': '$ (millions)','scale':1e6}, 'cost': {'title': 'Cost','units': '$ (millions)','scale':1e6}, 'profit': {'title': 'Profit','units': '$ (millions)','scale':1e6}, 'discounted_profit': {'title': 'Discounted profit','units': '$ (millions)','scale':1e6}, }) initial_state.default_plot = ['biomass','catch'] # initial_state.default_plot = ['catch','revenue','cost','profit'] initial_state.attribute_order = ['biomass','catch','profit','revenue','cost','discounted_profit','cpue','effort','fleet_size'] #Set the initial fishery parameters initial_state.set(biomass=5000000,fleet_size=120) #----------------------------------------- #Create the fishery model #----------------------------------------- model = Model(functions = [growthClass,catchClass,economicsClass],initial_state = initial_state) return model
Python
#import matplotlib as mp #mp.use('GTK') #from matplotlib.figure import Figure #from matplotlib.pyplot import show import matplotlib.pyplot as plt figure = plt.figure() pos = [.1,.1,.8,.8] pos2 = list(pos) pos2[2]=.75 print pos print pos2 ax1 = figure.add_axes(pos, frameon = False,label ='a') ax2 = figure.add_axes(pos2, frameon = False,label = 'b') ax1.yaxis.tick_right() ax1.yaxis.set_label_position('right') ax2.yaxis.tick_right() ax2.yaxis.set_label_position('right') ax1.set_ylabel('fda') ax2.set_ylabel('$') ax1.plot([0,1],[1,2],'r:') ax2.plot([0,1],[10,1],'g-') plt.show()
Python
#!/usr/bin/env python """Fisheries Economics Masterclass GUI""" import wx import wx.html import fisheries_model import colourblind import matplotlib #matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import \ FigureCanvasWxAgg as FigCanvas import numpy import copy import os import sys #String constants for some menus etc MG_QUOTA='Output Controlled' MG_EFFORT='Input Controlled' SIM_DYNAMIC='Dynamic' SIM_STATIC='Static (Equilibrium)' #Version history: #1.00 Initial release from Hobart Class 1 #1.01 Made fishery crash instantaneous. #1.02 Initial version on Google Code VERSIONSTRING = '1.02' #Globals that specify the current simulation and management type #(to be subsumed at a later stage...) SIM_TYPE='' MG_TYPE='' class Frame(wx.Frame): '''The main (only?) GUI Frame''' def __init__(self,width,height): wx.Frame.__init__(self, None, size=wx.Size(width,height), title = 'Fisheries Explorer') #self.SetSize(wx.Size(width,height)) #Set the starting simulation and management types global SIM_TYPE global MG_TYPE MG_TYPE = MG_QUOTA SIM_TYPE = SIM_STATIC self.Maximize() #Initialise model components self._init_model() #Initialise model/graph update system self._init_update() #Initialise GUI components self._init_gui() def _init_update(self): '''Initialise model/graph update system''' #Will contain current parameters self.parameters= {} #Will contain last parameters for which the model run was completed self.computed_parameters = {} #Will contain last parameters for which a graph was produced self.plotted_parameters = {} #Whether current computation has been completed self.computed_complete = True #Timer for model reruns self.timer_model = wx.Timer(self) self.timer_model.Start(250) wx.EVT_TIMER(self,self.timer_model.GetId(),self.on_timer_model) #Hack to call layout after init self.timer_init_hack = wx.Timer(self) self.timer_init_hack.Start(250) wx.EVT_TIMER(self,self.timer_init_hack.GetId(),self.on_timer_init_hack) #The model execution thread self.model_thread = fisheries_model.MultiThreadModelRun(self.model_data_updater) def _init_model(self,type='catch'): '''Initialise model''' self.model = fisheries_model.lobsterModel(control_type = type) def _init_gui(self): '''Initialise GUI components''' #Setup sizers (in hierarchical order) self.sizer = wx.FlexGridSizer(rows=2,cols=1) #Create wx objects self.parameter_panel = ParameterPanel(self,self.model,sim_update_fx=self.on_simulation_change) self.plot_panel = PlotPanel(self) #Set up main sizer self.sizer.Add(self.parameter_panel,0,wx.EXPAND) self.sizer.Add(self.plot_panel,0,wx.EXPAND) self.sizer.AddGrowableCol(0,1) self.sizer.AddGrowableRow(1,1) #Set sizers self.SetSizer(self.sizer) #Set menu self.menubar = MenuBar(self,sim_update_fx=self.on_simulation_change,parameter_type_fx=self.parameter_panel.show_parameter_set,reset_model_fx=self.on_simulation_change) self.SetMenuBar(self.menubar) self.menubar.set_parameter_types(self.model.get_parameter_types()) #Bind events self.Bind(wx.EVT_SCROLL,self.on_slide_change) #self.Bind(wx.EVT_CLOSE, self.onCloseWindow) self.on_slide_change(None) self.on_timer_model(None) #Prevent the frame getting resized too small min_size = self.sizer.GetMinSize() self.SetMinSize(min_size) #Set the icon self.icon = wx.Icon(os.path.join('images','fishnet.ico'),wx.BITMAP_TYPE_ICO) self.SetIcon(self.icon) #It still doesn't close cleanly for some unknown reason.. block = False def onCloseWindow(self,event): self.timer_model.Stop() self.timer_model.Destroy() self.icon.Destroy() event.Skip() def on_timer_model(self,event): '''Rerun the model if parameters have changed''' #If parameters have changed we need to recalculate the model if self.parameters != self.computed_parameters: self.computed_complete=False self.model.set_parameters(self.parameter_panel.get_parameters()) self.model.reset() #Run the appropriate simulation if SIM_TYPE == SIM_STATIC: if MG_TYPE == MG_QUOTA: max= self.parameters['K']*self.parameters['r']/4*1.01 self.model_thread.run(self.model,20,dynamic=False,independent_variable='catch',independent_maximum=max) else: self.model_thread.run(self.model,20,dynamic=False,independent_variable='effort',independent_maximum=6e6) else: self.model_thread.run(self.model,20) self.computed_parameters = self.parameters init_hack_count = 0 def on_timer_init_hack(self,event): '''A hack to layout the plot panel after load. For some reason the legend is not displayed correctly.''' if self.init_hack_count > 0: self.timer_init_hack.Stop() self.init_hack_count += 1 self.plot_panel.update_visibility() self.plot_panel.OnSize() self.plot_panel.Layout() def on_simulation_change(self,simulation_type,control_type): '''Called if the simulation type (static/dynamic, quota/effort controlled) changes''' global SIM_TYPE global MG_TYPE SIM_TYPE = simulation_type MG_TYPE = control_type #Initialise the model with appropriate control type if MG_TYPE == MG_QUOTA: self._init_model('catch') else: self._init_model('effort') self.computed_parameters = None self.parameter_panel.set_model(self.model) self.plot_panel.update_visibility() self.plot_panel.Layout() self.on_timer_model(None) def on_slide_change(self,event): '''Get the latest set of parameters if the sliders have been moved''' #Store the latest set of parameters # if event.GetEventObject() in self.parameter_panel.GetChildren(): self.parameters = self.parameter_panel.get_parameters() def model_data_updater(self,state): self.computed_complete=True self.model.state = state self.plot_panel.update_state(self.model.state) min_size = self.sizer.GetMinSize() self.SetMinSize(min_size) class MenuBar(wx.MenuBar): def __init__(self,parent_frame,sim_update_fx=None,parameter_type_fx=None,reset_model_fx=None): wx.MenuBar.__init__(self) self.sim_update_fx = sim_update_fx self.parameter_type_fx=parameter_type_fx self.reset_model_fx = reset_model_fx self.parent_frame = parent_frame self.scenario_menu = wx.Menu() self.reset_model = self.scenario_menu.Append(-1,'Reset Model') self.scenario_menu.Append(-1,' ').Enable(False) self.scenario_menu.AppendRadioItem(-1,'Rock Lobster Fishery') self.scenario_menu.Append(-1,' ').Enable(False) self.static_simulation = self.scenario_menu.AppendRadioItem(-1,SIM_STATIC) self.dynamic_simulation = self.scenario_menu.AppendRadioItem(-1,SIM_DYNAMIC) self.scenario_menu.Append(-1,' ').Enable(False) self.input_control = self.scenario_menu.AppendRadioItem(-1,MG_EFFORT) self.output_control = self.scenario_menu.AppendRadioItem(-1,MG_QUOTA) #Bring checks in line with initial simulation state if SIM_TYPE == SIM_STATIC: self.static_simulation.Check() else: self.dynamic_simulation.Check() if MG_TYPE == MG_QUOTA: self.output_control.Check() else: self.input_control.Check() self.parameter_menu = wx.Menu() self.parameter_items = [] self.help_menu = wx.Menu() self.about = self.help_menu.Append(-1,'About') self.license = self.help_menu.Append(-1,'License') self.Append(self.scenario_menu,'Model') self.Append(self.parameter_menu,'Parameters') self.Append(self.help_menu,'Help') parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.input_control) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.output_control) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.static_simulation) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.dynamic_simulation) parent_frame.Bind(wx.EVT_MENU, self.on_about,self.about) parent_frame.Bind(wx.EVT_MENU, self.on_license,self.license) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.reset_model) def set_parameter_types(self,types): for item in self.parameter_items: self.parameter_menu.Delete(item) for type in ["All"]+types: self.parameter_items.append(self.parameter_menu.AppendRadioItem(-1,type)) self.parent_frame.Bind(wx.EVT_MENU, self.on_parameter_selection, self.parameter_items[-1]) if type == 'Management Controls': self.parameter_items[-1].Check() self.on_parameter_selection(None) def on_reset_model(self,event): '''Reset the model''' self.reset_model_fx() def on_parameter_selection(self,event): '''Called when a parameter set is selected''' for item in self.parameter_items: if item.IsChecked(): self.parameter_type_fx(item.GetText()) def on_simulation_change(self,event): if self.input_control.IsChecked(): control_type = MG_EFFORT else: control_type = MG_QUOTA if self.static_simulation.IsChecked(): simulation_type = SIM_STATIC else: simulation_type= SIM_DYNAMIC self.sim_update_fx(simulation_type = simulation_type, control_type = control_type) event.Skip() def on_about(self,event): '''About handler, shows modal AboutBox''' dlg = AboutBox(self.parent_frame,title='About Fisheries Explorer',filename='about.html') dlg.ShowModal() dlg.Destroy() def on_license(self,event): '''License handler, shows modal AboutBox''' dlg = AboutBox(self.parent_frame,title='Fisheries Explorer License',filename='license.html') dlg.ShowModal() dlg.Destroy() class ParameterPanel(wx.Panel): '''A panel for parameter input''' def __init__(self,parent,model = [],sim_update_fx=None): wx.Panel.__init__(self,parent) self.type_shown = 'All' self.model = model self.parameters = model.get_parameters() self._base_layout() self.set_model(model) self.sim_update_fx = sim_update_fx def set_model(self,model): '''Set the parameters displayed in the panel (expects a Parameter object)''' self.parameters = model.get_parameters() self.model = model self.parameter_layout() self.show_parameter_set() def _base_layout(self): #Empty lists for storing gui objects (to get parameter values etc) self.label_parameters = {} self.label_param_values = {} self.slider_parameters = {} self.sizer = wx.FlexGridSizer(rows=1,cols=2) self.sizer.AddGrowableCol(1,1) self.SetSizer(self.sizer) self.set_panel = wx.Panel(self) self.set_sizer = wx.FlexGridSizer(rows=3,cols=1) self.set_panel.SetSizer(self.set_sizer) self.control_panel = wx.Panel(self) self.control_sizer = wx.FlexGridSizer(rows=len(self.parameters),cols=3) self.control_sizer.AddGrowableCol(1,1) self.control_panel.SetSizer(self.control_sizer) self.sizer.Add(self.set_panel,0) self.sizer.Add(self.control_panel,0,flag=wx.EXPAND) if False: #Drop down box for choosing parameter types self.set_sizer.Add(wx.StaticText(self.set_panel,label='Parameter Set:')) self.parameter_choice = wx.Choice(self.set_panel,1) self.set_sizer.Add(self.parameter_choice) #Set selection items items = self.model.get_parameter_types() items.insert(0,'ALL') self.parameter_choice.SetItems(items) self.parameter_choice.SetSelection(0) if False: self.static_toggle = wx.RadioBox(self.set_panel,1,"Simulation Type",choices=[SIM_STATIC,SIM_DYNAMIC]) self.management_toggle = wx.RadioBox(self.set_panel,1,"Management Type",choices=[MG_EFFORT,MG_QUOTA]) self.set_sizer.Add(self.static_toggle) self.set_sizer.Add(self.management_toggle) self.Bind(wx.EVT_CHOICE,self.on_selection_change) self.Bind(wx.EVT_RADIOBOX,self.on_simulation_change) def parameter_layout(self): #Delete all existing objects if hasattr(self,'control_sizer'): self.control_sizer.Clear(True) #Create the caption, value and slider for each parameter count = 0 for param in self.parameters: p = self.parameters[param] self.label_parameters[param]=wx.StaticText(self.control_panel,label=p['title']+':') current_value = round((p['value']-p['min'])/float(p['max']-p['min'])*1000) self.slider_parameters[param]= wx.Slider(self.control_panel, -1, current_value, 0, 1000, wx.DefaultPosition, style= wx.SL_HORIZONTAL) self.label_param_values[param]=wx.StaticText(self.control_panel,label='') self.label_parameters[param].SetToolTipString(p['description']) self.slider_parameters[param].SetToolTipString(p['description']) self.control_sizer.Add(self.label_parameters[param],0,flag=wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT) self.control_sizer.Add(self.slider_parameters[param],0,flag=wx.EXPAND) self.control_sizer.Add(self.label_param_values[param],0,flag=wx.ALIGN_LEFT) count += 1 self.on_slide_change(None) self.Bind(wx.EVT_SCROLL,self.on_slide_change) def on_simulation_change(self,event): self.sim_update_fx(simulation_type = self.static_toggle.GetStringSelection(), control_type = self.management_toggle.GetStringSelection()) def on_selection_change(self,event): '''Update parameter list when a different parameter set is selected''' type = self.parameter_choice.GetItems()[self.parameter_choice.GetSelection()] self.show_parameter_set(type) def show_parameter_set(self,type=None): '''Show parameters of type''' #If type is unspecified we show the same parameter set if type != None: self.type_shown = type type = self.type_shown #Show the selected parameters for param in self.parameters: selected =((type == 'ALL' or type == 'All' or self.parameters[param]['type'] == type) and (SIM_TYPE == SIM_DYNAMIC or self.parameters[param]['type'] != 'Management Controls')) if SIM_TYPE == SIM_STATIC and param == 'discount_rate': selected = False self.label_param_values[param].Show(selected) self.label_parameters[param].Show(selected) self.slider_parameters[param].Show(selected) self.Fit() self.GetParent().Layout() def on_slide_change(self,event): '''Slider change event updates value label''' param_values = self.get_parameters() for param in (param_values): scale_text = '' if self.parameters[param]['scale_text'] != '': scale_text = ' (' + self.parameters[param]['scale_text'] + ')' self.label_param_values[param].SetLabel(str(param_values[param]/self.parameters[param]['scale'])+ ' ' + self.parameters[param]['units'] + scale_text) self.Layout() #Propagate the event so that the frame can process it if event != None: event.Skip() def get_parameters(self): '''Get a dict of the current parameter values''' out = {} for param in self.parameters: p = self.parameters[param] out[param] = float(self.slider_parameters[param].GetValue())/1000.0*(p['max']-p['min'])+p['min'] return out def set_parameters(self,parameter_values): '''Update parameters from a dict''' out = {} for param in parameter_values.keys(): if self.parameters.has_key(param): v = parameter_values[param] p = self.parameters[param] self.slider_parameters[param].SetValue(int((v-p['min'])/(p['max']-p['min'])*1000)) self.on_slide_change(None) class PlotPanel(wx.Panel): line_colours = colourblind.rgbScaled line_styles = [[127,1], #solid [5,5], #dashed [20,20,2,20], #dash-dot [2,2,2,2] #dotted ] def __init__(self,parent): wx.Panel.__init__(self,parent) self.last_redraw_size = [] self.fig = Figure() self.fig.set_facecolor([1,1,1]) self.control_panel = wx.Panel(self) self.canvas_panel = wx.Panel(self) self.canvas = FigCanvas(self.canvas_panel,wx.ID_ANY,self.fig) self.sizer = wx.FlexGridSizer(rows=1,cols=2,hgap=5,vgap=5) self.sizer.Add(self.canvas_panel,flag=wx.EXPAND) self.sizer.Add(self.control_panel,flag=wx.ALIGN_CENTER|wx.ALL) self.sizer.AddGrowableCol(0,1) self.sizer.AddGrowableRow(0,1) self.SetSizer(self.sizer) self.control_sizer = wx.FlexGridSizer(hgap=5,vgap=5) self.control_panel.SetSizer(self.control_sizer) self.control_panel.Bind(wx.EVT_CHECKBOX,self.redraw) # self.canvas.SetAutoLayout(True) self.canvas_panel.SetMinSize([600,300]) self.state = None self.bounds = {} self.xbound = 0 self.SetBackgroundColour(wx.WHITE) self.canvas_panel.SetBackgroundColour(wx.WHITE) self.control_panel.SetBackgroundColour(wx.WHITE) self.canvas_panel.Bind(wx.EVT_SIZE, self.OnSize) self.Fit() def OnSize(self,event=None,size=None): if event == None and size == None: size = self.canvas_panel.GetClientSize() elif event != None and size == None: size = event.GetSize() #If the size has actually changed we redraw (several events may #be intercepted here per resize) if size != self.last_redraw_size: self.last_redraw_size = size self.fig.set_figwidth(size[0]/(1.0*self.fig.get_dpi())) self.fig.set_figheight(size[1]/(1.0*self.fig.get_dpi())) self.canvas.SetClientSize(size) self.redraw(None, redraw=True) if event != None: event.Skip() def _setup_control_panel(self): self._update_line_styles() #Remove existing widgets self.control_sizer.Clear(True) parameters = self.state.attribute_order self.control_sizer.SetRows(len(parameters)) self.control_sizer.SetCols(3) #Column Labels if False: self.control_sizer.SetRows(len(parameters)+1) column_labels = ['Plot','Parameter','Style'] for col in range(len(column_labels)): self.control_sizer.Add(wx.StaticText(self.control_panel,-1,column_labels[col])) self.check_boxes = {} self.param_text = {} self.param_bitmap = {} self.pens = {} self.colours = {} self.linedc = {} self.linebitmap = {} # self.check_boxes = {} linedc = wx.MemoryDC() for param in parameters: rgbcolour = self.unit_colour[self.state.get_attribute_units(param)] self.colours[param] = wx.Colour(rgbcolour[0]*255,rgbcolour[1]*255,rgbcolour[2]*255) style = self.parameter_style[param] #Add the check box self.check_boxes[param] = wx.CheckBox(self.control_panel,-1,'') self.control_sizer.Add(self.check_boxes[param]) #Add the description self.param_text[param] = wx.StaticText(self.control_panel,-1,self.state.get_attribute_title(param)) self.control_sizer.Add(self.param_text[param]) self.param_text[param].SetForegroundColour(self.colours[param]) self.param_text[param].Refresh() #Add the linestyle self.linebitmap[param] = wx.EmptyBitmap(40,20) linedc.SelectObject(self.linebitmap[param]) linedc.Clear() self.pens[param] = wx.Pen(colour = self.colours[param], width = 1,style = wx.USER_DASH) self.pens[param].SetDashes(style) linedc.SetPen(self.pens[param]) linedc.DrawLine(0,10,40,10) self.param_bitmap[param] = wx.StaticBitmap(self.control_panel,-1,self.linebitmap[param]) self.control_sizer.Add(self.param_bitmap[param]) #Enable the default plot parameters for param in self.state.default_plot: self.check_boxes[param].SetValue(True) def _colour_control(self): ''' updates the colours of the control elements ''' selected = self.get_selected_parameters() for param in self.state.attributes: if param in selected: self.param_text[param].Enable() self.param_bitmap[param].Enable() else: self.param_text[param].Disable() #self.param_bitmap[param].Disable() def _update_line_styles(self): ''' Update the colour and style associated with each unit and parameter ''' self.unit_colour = {} self.parameter_style = {} #For tracking the number of parameters per unit unit_count = {} #Determine colours for units for unit in self.state.unit_order: self.unit_colour[unit] = self.line_colours[len(self.unit_colour)] unit_count[unit] = 0 #Determine line styles for parameters for param in self.state.attribute_order: unit = self.state.get_attribute_units(param) print param, unit self.parameter_style[param] = self.line_styles[unit_count[unit]] unit_count[unit] += 1 def _select_parameters(self,parameters = [],redraw=True): '''Set the parameters to be plotted''' self.parameters = parameters if redraw: self.redraw_fromscratch() def update_visibility(self): if SIM_TYPE == SIM_STATIC: enabled = False else: enabled = True self.check_boxes['discounted_profit'].Show(enabled) self.param_text['discounted_profit'].Show(enabled) self.param_bitmap['discounted_profit'].Show(enabled) def update_state(self,state,redraw=True): '''Update the state that is being plotted''' self.state = copy.deepcopy(state) if not hasattr(self,'last_parameters'): self.last_parameters = {} print self.state['discounted_profit'] import numpy self.npv = numpy.nansum(self.state['discounted_profit']) # discount_rate = 0.05 # for index in range(len(self.state['revenue'])): # if self.state['revenue'][index] != None and ~numpy.isnan(self.state['revenue'][index]): # self.npv += (self.state['revenue'][index]-self.state['cost'][index])*(1-discount_rate)**index if redraw: #Update the parameter selection controls if necessary if state.attributes != self.last_parameters: self._setup_control_panel() self.last_parameters = state.attributes self.redraw() def _update_bounds(self): '''Update the figure bounds''' def sig_round(number): '''Ceil a number to a nice round figure for limits''' if number == 0: return 0 sig = number/(10**numpy.floor(numpy.log10(number*2))) if sig < 2: factor_multiple = 2.0 elif sig < 5: factor_multiple = 2.0 else: factor_multiple = 1.0 factor = 10**(numpy.floor(numpy.log10(number*factor_multiple)))/factor_multiple rounded = numpy.ceil(number/factor)*factor print number, rounded return rounded self.xbound = 0 self.bounds = {} for unit in self._get_units(): self.bounds[unit]=[float('inf'), -float('inf')] for param in self.get_selected_parameters(): unit = self.state.get_attribute_units(param) yv = numpy.asarray(self.state[param])/self.state.attributes[param]['scale'] self.bounds[unit][0] = min(self.bounds[unit][0], numpy.nanmin(yv)) self.bounds[unit][1] = max(self.bounds[unit][1], numpy.nanmax(yv)) self.bounds[unit][0] = sig_round(self.bounds[unit][0]) self.bounds[unit][1] = sig_round(self.bounds[unit][1]) if SIM_TYPE == SIM_DYNAMIC: self.xbound = max(self.xbound,len(self.state[param])-1) if SIM_TYPE == SIM_STATIC: if MG_TYPE == MG_QUOTA: self.xbound = numpy.nanmax(numpy.asarray(self.state['catch'])/self.state.attributes['catch']['scale']) else: self.xbound = numpy.nanmax(numpy.asarray(self.state['effort'])/self.state.attributes['effort']['scale']) self.xbound = sig_round(self.xbound) def get_selected_parameters(self): '''Return the parameters that have been selected for plotting''' out = [] for param in self.state.attribute_order: if self.check_boxes[param].GetValue(): out.append(param) return out def _get_units(self): ''' Returns a list of units that will be plotted ''' units = {} for param in self.get_selected_parameters(): units[self.state.get_attribute_units(param)]=1 return units.keys() def _setup_axes(self): ''' Redraw the figure from scratch required if the number of axes etc. have changed ''' #Clear the figure self.fig.clf() #Add the new axes self.axes = {} self.plot_data = {} self.axes_xscale = {} max_width = 0.87 width_increment = 0.07 bottom_space = .13 pos=[.05, bottom_space, max_width-width_increment*(len(self._get_units())-1), 1-bottom_space-0.05] #Create the axes, one for each unit for unit in self._get_units(): first_figure = len(self.axes)==0 colour = self.unit_colour[unit] self.axes[unit] = self.fig.add_axes(pos,frameon=True,label=unit) self.axes[unit].yaxis.tick_right() self.axes[unit].yaxis.set_label_position('right') self.axes[unit].set_ylabel(unit) self.axes_xscale[unit] = pos[2]/(max_width-width_increment*(len(self._get_units())-1)) if not first_figure: self.axes[unit].patch.set_alpha(0) else: self.firstaxes = self.axes[unit] self.axes[unit].set_xlabel('Years') self._modify_axes(self.axes[unit],colour,not first_figure) pos[2] += width_increment #Create the plot lines, one for each parameter for param in self.get_selected_parameters(): unit = self.state.get_attribute_units(param) colour = self.unit_colour[unit] style = self.parameter_style[param] self.plot_data[param] = self.axes[unit].plot([0,0],[0,0],linewidth=2)[0] self.plot_data[param].set_color(colour) self.plot_data[param].set_dashes(style) #Text for npv self.npvtext = self.fig.text(.1,bottom_space,'NPV') def redraw(self,event=None,redraw=False): ''' Update the plots using data in the current state ''' if self.state == None: return if not hasattr(self,'last_selected_parameters'): self.last_selected_parameters = {} #If the selected parameters have changed we need new axes if self.last_selected_parameters != self.get_selected_parameters() or redraw: self.last_selected_parameters = self.get_selected_parameters() self._colour_control() self._setup_axes() self._update_bounds() #Update axes bounds for unit in self._get_units(): bounds = self.bounds[unit] self.axes[unit].set_ybound(lower = 0,upper = bounds[1]) self.axes[unit].set_xbound(lower = 0,upper=self.xbound*self.axes_xscale[unit]) #Update plot data for param in self.get_selected_parameters(): data = self.state[param] if SIM_TYPE == SIM_DYNAMIC: self.plot_data[param].set_xdata(range(len(data))) else: if MG_TYPE == MG_QUOTA: self.plot_data[param].set_xdata(numpy.asarray(self.state['catch'])/self.state.attributes['catch']['scale']) else: self.plot_data[param].set_xdata(numpy.asarray(self.state['effort'])/self.state.attributes['effort']['scale']) self.plot_data[param].set_ydata(numpy.asarray(data)/self.state.attributes[param]['scale']) if SIM_TYPE == SIM_DYNAMIC: self.firstaxes.set_xlabel('Years') else: if MG_TYPE == MG_QUOTA: xunit = 'catch' else: xunit = 'effort' self.firstaxes.set_xlabel('Management Control: ' + self.state.attributes[xunit]['title'] + ' (' + self.state.attributes[xunit]['units'] + ')') if SIM_TYPE == SIM_DYNAMIC and ~numpy.isnan(self.npv): self.npvtext.set_text('NPV: $' + str(int(round(self.npv/self.state.attributes['revenue']['scale']))) + ' million') else: self.npvtext.set_text('') self.canvas.draw() @staticmethod def _modify_axes(axes,color,remove = False): ''' Set the colour of the y axis to color and optionally remove the remaining borders of the graph ''' def modify_all(object,color=None,remove=False): for child in object.get_children(): modify_all(child,color,remove) if remove and hasattr(object,'set_visible'): object.set_visible(not remove) if color != None and hasattr(object,'set_color'): object.set_color(color) for child in axes.get_children(): if isinstance(child, matplotlib.spines.Spine): if child.spine_type == 'right': modify_all(child,color=color) elif remove == True: modify_all(child,remove=True) modify_all(axes.yaxis,color=color) if remove: modify_all(axes.xaxis,remove=True) class AboutBox(wx.Dialog): '''An about dialog box, which displays a html file''' replacements = {'_VERSION_': VERSIONSTRING} def __init__(self,parent,title,filename): ''' parent: parent window title: dialog box title filename: the html file to show ''' wx.Dialog.__init__(self,parent,-1,title,size=(500,550)) #Read the html source file fid = open(filename,'r') self.abouthtml = fid.read() fid.close() #Replace tokens for key in self.replacements.keys(): self.abouthtml = self.abouthtml.replace(key,self.replacements[key]) self.html = wx.html.HtmlWindow(self) self.html.SetPage(self.abouthtml) self.ok_button = wx.Button(self,wx.ID_OK,"Ok") self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.html,1,wx.EXPAND|wx.ALL,5) self.sizer.Add(self.ok_button,0,wx.ALIGN_CENTER|wx.ALL,5) self.SetSizer(self.sizer) self.Layout() x=1366 y=768 class App(wx.App): def OnInit(self): self.frame = Frame(x,y) self.SetTopWindow(self.frame) self.frame.Show() self.frame.Layout() return True if __name__ == '__main__': app = App(redirect=False) # app = App(redirect=False) app.MainLoop()
Python
#By running "python setup.py py2exe" this script generates a windows stand-alone #distribution of the Fisheries Explorer from distutils.core import setup import py2exe import matplotlib import shutil # Remove the build folder shutil.rmtree("build", ignore_errors=True) # do the same for dist folder shutil.rmtree("dist", ignore_errors=True) data_files = matplotlib.get_py2exe_datafiles() data_files += ['license.html','about.html',('images',["images/fishnet.ico","images/seafoodcrc.png",'images/fishnet.png','images/about.png','images/fish.png'])] dll_excludes = ['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll', 'tk84.dll', 'MSVCP90.dll', 'mswsock.dll', 'powrprof.dll'] excludes = ['_gtkagg' ] setup( windows = [ { "script": "fisheries_gui.py", "icon_resources": [(1, "images\\fishnet.ico")], #"other_resources": [(24,1,manifest)] } ], options = {"py2exe": { 'excludes': excludes, 'includes': ['matplotlib.backends.backend_tkagg','unittest','inspect'], "dll_excludes": dll_excludes, # "compressed": 2, # "optimize": 2, # "bundle_files": 2, # "xref": False, # "skip_archive": False, # "ascii": False, # "custom_boot_script": '' } }, data_files=data_files )
Python
#!/usr/bin/env python """Fisheries Economics Masterclass GUI""" import wx import wx.html import fisheries_model import colourblind import matplotlib #matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import \ FigureCanvasWxAgg as FigCanvas import numpy import copy import os import sys #String constants for some menus etc MG_QUOTA='Output Controlled' MG_EFFORT='Input Controlled' SIM_DYNAMIC='Dynamic' SIM_STATIC='Static (Equilibrium)' #Version history: #1.00 Initial release from Hobart Class 1 #1.01 Made fishery crash instantaneous. #1.02 Initial version on Google Code VERSIONSTRING = '1.02' #Globals that specify the current simulation and management type #(to be subsumed at a later stage...) SIM_TYPE='' MG_TYPE='' class Frame(wx.Frame): '''The main (only?) GUI Frame''' def __init__(self,width,height): wx.Frame.__init__(self, None, size=wx.Size(width,height), title = 'Fisheries Explorer') #self.SetSize(wx.Size(width,height)) #Set the starting simulation and management types global SIM_TYPE global MG_TYPE MG_TYPE = MG_QUOTA SIM_TYPE = SIM_STATIC self.Maximize() #Initialise model components self._init_model() #Initialise model/graph update system self._init_update() #Initialise GUI components self._init_gui() def _init_update(self): '''Initialise model/graph update system''' #Will contain current parameters self.parameters= {} #Will contain last parameters for which the model run was completed self.computed_parameters = {} #Will contain last parameters for which a graph was produced self.plotted_parameters = {} #Whether current computation has been completed self.computed_complete = True #Timer for model reruns self.timer_model = wx.Timer(self) self.timer_model.Start(250) wx.EVT_TIMER(self,self.timer_model.GetId(),self.on_timer_model) #Hack to call layout after init self.timer_init_hack = wx.Timer(self) self.timer_init_hack.Start(250) wx.EVT_TIMER(self,self.timer_init_hack.GetId(),self.on_timer_init_hack) #The model execution thread self.model_thread = fisheries_model.MultiThreadModelRun(self.model_data_updater) def _init_model(self,type='catch'): '''Initialise model''' self.model = fisheries_model.lobsterModel(control_type = type) def _init_gui(self): '''Initialise GUI components''' #Setup sizers (in hierarchical order) self.sizer = wx.FlexGridSizer(rows=2,cols=1) #Create wx objects self.parameter_panel = ParameterPanel(self,self.model,sim_update_fx=self.on_simulation_change) self.plot_panel = PlotPanel(self) #Set up main sizer self.sizer.Add(self.parameter_panel,0,wx.EXPAND) self.sizer.Add(self.plot_panel,0,wx.EXPAND) self.sizer.AddGrowableCol(0,1) self.sizer.AddGrowableRow(1,1) #Set sizers self.SetSizer(self.sizer) #Set menu self.menubar = MenuBar(self,sim_update_fx=self.on_simulation_change,parameter_type_fx=self.parameter_panel.show_parameter_set,reset_model_fx=self.on_simulation_change) self.SetMenuBar(self.menubar) self.menubar.set_parameter_types(self.model.get_parameter_types()) #Bind events self.Bind(wx.EVT_SCROLL,self.on_slide_change) #self.Bind(wx.EVT_CLOSE, self.onCloseWindow) self.on_slide_change(None) self.on_timer_model(None) #Prevent the frame getting resized too small min_size = self.sizer.GetMinSize() self.SetMinSize(min_size) #Set the icon self.icon = wx.Icon(os.path.join('images','fishnet.ico'),wx.BITMAP_TYPE_ICO) self.SetIcon(self.icon) #It still doesn't close cleanly for some unknown reason.. block = False def onCloseWindow(self,event): self.timer_model.Stop() self.timer_model.Destroy() self.icon.Destroy() event.Skip() def on_timer_model(self,event): '''Rerun the model if parameters have changed''' #If parameters have changed we need to recalculate the model if self.parameters != self.computed_parameters: self.computed_complete=False self.model.set_parameters(self.parameter_panel.get_parameters()) self.model.reset() #Run the appropriate simulation if SIM_TYPE == SIM_STATIC: if MG_TYPE == MG_QUOTA: max= self.parameters['K']*self.parameters['r']/4*1.01 self.model_thread.run(self.model,20,dynamic=False,independent_variable='catch',independent_maximum=max) else: self.model_thread.run(self.model,20,dynamic=False,independent_variable='effort',independent_maximum=6e6) else: self.model_thread.run(self.model,20) self.computed_parameters = self.parameters init_hack_count = 0 def on_timer_init_hack(self,event): '''A hack to layout the plot panel after load. For some reason the legend is not displayed correctly.''' if self.init_hack_count > 0: self.timer_init_hack.Stop() self.init_hack_count += 1 self.plot_panel.update_visibility() self.plot_panel.OnSize() self.plot_panel.Layout() def on_simulation_change(self,simulation_type,control_type): '''Called if the simulation type (static/dynamic, quota/effort controlled) changes''' global SIM_TYPE global MG_TYPE SIM_TYPE = simulation_type MG_TYPE = control_type #Initialise the model with appropriate control type if MG_TYPE == MG_QUOTA: self._init_model('catch') else: self._init_model('effort') self.computed_parameters = None self.parameter_panel.set_model(self.model) self.plot_panel.update_visibility() self.plot_panel.Layout() self.on_timer_model(None) def on_slide_change(self,event): '''Get the latest set of parameters if the sliders have been moved''' #Store the latest set of parameters # if event.GetEventObject() in self.parameter_panel.GetChildren(): self.parameters = self.parameter_panel.get_parameters() def model_data_updater(self,state): self.computed_complete=True self.model.state = state self.plot_panel.update_state(self.model.state) min_size = self.sizer.GetMinSize() self.SetMinSize(min_size) class MenuBar(wx.MenuBar): def __init__(self,parent_frame,sim_update_fx=None,parameter_type_fx=None,reset_model_fx=None): wx.MenuBar.__init__(self) self.sim_update_fx = sim_update_fx self.parameter_type_fx=parameter_type_fx self.reset_model_fx = reset_model_fx self.parent_frame = parent_frame self.scenario_menu = wx.Menu() self.reset_model = self.scenario_menu.Append(-1,'Reset Model') self.scenario_menu.Append(-1,' ').Enable(False) self.scenario_menu.AppendRadioItem(-1,'Rock Lobster Fishery') self.scenario_menu.Append(-1,' ').Enable(False) self.static_simulation = self.scenario_menu.AppendRadioItem(-1,SIM_STATIC) self.dynamic_simulation = self.scenario_menu.AppendRadioItem(-1,SIM_DYNAMIC) self.scenario_menu.Append(-1,' ').Enable(False) self.input_control = self.scenario_menu.AppendRadioItem(-1,MG_EFFORT) self.output_control = self.scenario_menu.AppendRadioItem(-1,MG_QUOTA) #Bring checks in line with initial simulation state if SIM_TYPE == SIM_STATIC: self.static_simulation.Check() else: self.dynamic_simulation.Check() if MG_TYPE == MG_QUOTA: self.output_control.Check() else: self.input_control.Check() self.parameter_menu = wx.Menu() self.parameter_items = [] self.help_menu = wx.Menu() self.about = self.help_menu.Append(-1,'About') self.license = self.help_menu.Append(-1,'License') self.Append(self.scenario_menu,'Model') self.Append(self.parameter_menu,'Parameters') self.Append(self.help_menu,'Help') parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.input_control) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.output_control) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.static_simulation) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.dynamic_simulation) parent_frame.Bind(wx.EVT_MENU, self.on_about,self.about) parent_frame.Bind(wx.EVT_MENU, self.on_license,self.license) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.reset_model) def set_parameter_types(self,types): for item in self.parameter_items: self.parameter_menu.Delete(item) for type in ["All"]+types: self.parameter_items.append(self.parameter_menu.AppendRadioItem(-1,type)) self.parent_frame.Bind(wx.EVT_MENU, self.on_parameter_selection, self.parameter_items[-1]) if type == 'Management Controls': self.parameter_items[-1].Check() self.on_parameter_selection(None) def on_reset_model(self,event): '''Reset the model''' self.reset_model_fx() def on_parameter_selection(self,event): '''Called when a parameter set is selected''' for item in self.parameter_items: if item.IsChecked(): self.parameter_type_fx(item.GetText()) def on_simulation_change(self,event): if self.input_control.IsChecked(): control_type = MG_EFFORT else: control_type = MG_QUOTA if self.static_simulation.IsChecked(): simulation_type = SIM_STATIC else: simulation_type= SIM_DYNAMIC self.sim_update_fx(simulation_type = simulation_type, control_type = control_type) event.Skip() def on_about(self,event): '''About handler, shows modal AboutBox''' dlg = AboutBox(self.parent_frame,title='About Fisheries Explorer',filename='about.html') dlg.ShowModal() dlg.Destroy() def on_license(self,event): '''License handler, shows modal AboutBox''' dlg = AboutBox(self.parent_frame,title='Fisheries Explorer License',filename='license.html') dlg.ShowModal() dlg.Destroy() class ParameterPanel(wx.Panel): '''A panel for parameter input''' def __init__(self,parent,model = [],sim_update_fx=None): wx.Panel.__init__(self,parent) self.type_shown = 'All' self.model = model self.parameters = model.get_parameters() self._base_layout() self.set_model(model) self.sim_update_fx = sim_update_fx def set_model(self,model): '''Set the parameters displayed in the panel (expects a Parameter object)''' self.parameters = model.get_parameters() self.model = model self.parameter_layout() self.show_parameter_set() def _base_layout(self): #Empty lists for storing gui objects (to get parameter values etc) self.label_parameters = {} self.label_param_values = {} self.slider_parameters = {} self.sizer = wx.FlexGridSizer(rows=1,cols=2) self.sizer.AddGrowableCol(1,1) self.SetSizer(self.sizer) self.set_panel = wx.Panel(self) self.set_sizer = wx.FlexGridSizer(rows=3,cols=1) self.set_panel.SetSizer(self.set_sizer) self.control_panel = wx.Panel(self) self.control_sizer = wx.FlexGridSizer(rows=len(self.parameters),cols=3) self.control_sizer.AddGrowableCol(1,1) self.control_panel.SetSizer(self.control_sizer) self.sizer.Add(self.set_panel,0) self.sizer.Add(self.control_panel,0,flag=wx.EXPAND) if False: #Drop down box for choosing parameter types self.set_sizer.Add(wx.StaticText(self.set_panel,label='Parameter Set:')) self.parameter_choice = wx.Choice(self.set_panel,1) self.set_sizer.Add(self.parameter_choice) #Set selection items items = self.model.get_parameter_types() items.insert(0,'ALL') self.parameter_choice.SetItems(items) self.parameter_choice.SetSelection(0) if False: self.static_toggle = wx.RadioBox(self.set_panel,1,"Simulation Type",choices=[SIM_STATIC,SIM_DYNAMIC]) self.management_toggle = wx.RadioBox(self.set_panel,1,"Management Type",choices=[MG_EFFORT,MG_QUOTA]) self.set_sizer.Add(self.static_toggle) self.set_sizer.Add(self.management_toggle) self.Bind(wx.EVT_CHOICE,self.on_selection_change) self.Bind(wx.EVT_RADIOBOX,self.on_simulation_change) def parameter_layout(self): #Delete all existing objects if hasattr(self,'control_sizer'): self.control_sizer.Clear(True) #Create the caption, value and slider for each parameter count = 0 for param in self.parameters: p = self.parameters[param] self.label_parameters[param]=wx.StaticText(self.control_panel,label=p['title']+':') current_value = round((p['value']-p['min'])/float(p['max']-p['min'])*1000) self.slider_parameters[param]= wx.Slider(self.control_panel, -1, current_value, 0, 1000, wx.DefaultPosition, style= wx.SL_HORIZONTAL) self.label_param_values[param]=wx.StaticText(self.control_panel,label='') self.label_parameters[param].SetToolTipString(p['description']) self.slider_parameters[param].SetToolTipString(p['description']) self.control_sizer.Add(self.label_parameters[param],0,flag=wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT) self.control_sizer.Add(self.slider_parameters[param],0,flag=wx.EXPAND) self.control_sizer.Add(self.label_param_values[param],0,flag=wx.ALIGN_LEFT) count += 1 self.on_slide_change(None) self.Bind(wx.EVT_SCROLL,self.on_slide_change) def on_simulation_change(self,event): self.sim_update_fx(simulation_type = self.static_toggle.GetStringSelection(), control_type = self.management_toggle.GetStringSelection()) def on_selection_change(self,event): '''Update parameter list when a different parameter set is selected''' type = self.parameter_choice.GetItems()[self.parameter_choice.GetSelection()] self.show_parameter_set(type) def show_parameter_set(self,type=None): '''Show parameters of type''' #If type is unspecified we show the same parameter set if type != None: self.type_shown = type type = self.type_shown #Show the selected parameters for param in self.parameters: selected =((type == 'ALL' or type == 'All' or self.parameters[param]['type'] == type) and (SIM_TYPE == SIM_DYNAMIC or self.parameters[param]['type'] != 'Management Controls')) if SIM_TYPE == SIM_STATIC and param == 'discount_rate': selected = False self.label_param_values[param].Show(selected) self.label_parameters[param].Show(selected) self.slider_parameters[param].Show(selected) self.Fit() self.GetParent().Layout() def on_slide_change(self,event): '''Slider change event updates value label''' param_values = self.get_parameters() for param in (param_values): scale_text = '' if self.parameters[param]['scale_text'] != '': scale_text = ' (' + self.parameters[param]['scale_text'] + ')' self.label_param_values[param].SetLabel(str(param_values[param]/self.parameters[param]['scale'])+ ' ' + self.parameters[param]['units'] + scale_text) self.Layout() #Propagate the event so that the frame can process it if event != None: event.Skip() def get_parameters(self): '''Get a dict of the current parameter values''' out = {} for param in self.parameters: p = self.parameters[param] out[param] = float(self.slider_parameters[param].GetValue())/1000.0*(p['max']-p['min'])+p['min'] return out def set_parameters(self,parameter_values): '''Update parameters from a dict''' out = {} for param in parameter_values.keys(): if self.parameters.has_key(param): v = parameter_values[param] p = self.parameters[param] self.slider_parameters[param].SetValue(int((v-p['min'])/(p['max']-p['min'])*1000)) self.on_slide_change(None) class PlotPanel(wx.Panel): line_colours = colourblind.rgbScaled line_styles = [[127,1], #solid [5,5], #dashed [20,20,2,20], #dash-dot [2,2,2,2] #dotted ] def __init__(self,parent): wx.Panel.__init__(self,parent) self.last_redraw_size = [] self.fig = Figure() self.fig.set_facecolor([1,1,1]) self.control_panel = wx.Panel(self) self.canvas_panel = wx.Panel(self) self.canvas = FigCanvas(self.canvas_panel,wx.ID_ANY,self.fig) self.sizer = wx.FlexGridSizer(rows=1,cols=2,hgap=5,vgap=5) self.sizer.Add(self.canvas_panel,flag=wx.EXPAND) self.sizer.Add(self.control_panel,flag=wx.ALIGN_CENTER|wx.ALL) self.sizer.AddGrowableCol(0,1) self.sizer.AddGrowableRow(0,1) self.SetSizer(self.sizer) self.control_sizer = wx.FlexGridSizer(hgap=5,vgap=5) self.control_panel.SetSizer(self.control_sizer) self.control_panel.Bind(wx.EVT_CHECKBOX,self.redraw) # self.canvas.SetAutoLayout(True) self.canvas_panel.SetMinSize([600,300]) self.state = None self.bounds = {} self.xbound = 0 self.SetBackgroundColour(wx.WHITE) self.canvas_panel.SetBackgroundColour(wx.WHITE) self.control_panel.SetBackgroundColour(wx.WHITE) self.canvas_panel.Bind(wx.EVT_SIZE, self.OnSize) self.Fit() def OnSize(self,event=None,size=None): if event == None and size == None: size = self.canvas_panel.GetClientSize() elif event != None and size == None: size = event.GetSize() #If the size has actually changed we redraw (several events may #be intercepted here per resize) if size != self.last_redraw_size: self.last_redraw_size = size self.fig.set_figwidth(size[0]/(1.0*self.fig.get_dpi())) self.fig.set_figheight(size[1]/(1.0*self.fig.get_dpi())) self.canvas.SetClientSize(size) self.redraw(None, redraw=True) if event != None: event.Skip() def _setup_control_panel(self): self._update_line_styles() #Remove existing widgets self.control_sizer.Clear(True) parameters = self.state.attribute_order self.control_sizer.SetRows(len(parameters)) self.control_sizer.SetCols(3) #Column Labels if False: self.control_sizer.SetRows(len(parameters)+1) column_labels = ['Plot','Parameter','Style'] for col in range(len(column_labels)): self.control_sizer.Add(wx.StaticText(self.control_panel,-1,column_labels[col])) self.check_boxes = {} self.param_text = {} self.param_bitmap = {} self.pens = {} self.colours = {} self.linedc = {} self.linebitmap = {} # self.check_boxes = {} linedc = wx.MemoryDC() for param in parameters: rgbcolour = self.unit_colour[self.state.get_attribute_units(param)] self.colours[param] = wx.Colour(rgbcolour[0]*255,rgbcolour[1]*255,rgbcolour[2]*255) style = self.parameter_style[param] #Add the check box self.check_boxes[param] = wx.CheckBox(self.control_panel,-1,'') self.control_sizer.Add(self.check_boxes[param]) #Add the description self.param_text[param] = wx.StaticText(self.control_panel,-1,self.state.get_attribute_title(param)) self.control_sizer.Add(self.param_text[param]) self.param_text[param].SetForegroundColour(self.colours[param]) self.param_text[param].Refresh() #Add the linestyle self.linebitmap[param] = wx.EmptyBitmap(40,20) linedc.SelectObject(self.linebitmap[param]) linedc.Clear() self.pens[param] = wx.Pen(colour = self.colours[param], width = 1,style = wx.USER_DASH) self.pens[param].SetDashes(style) linedc.SetPen(self.pens[param]) linedc.DrawLine(0,10,40,10) self.param_bitmap[param] = wx.StaticBitmap(self.control_panel,-1,self.linebitmap[param]) self.control_sizer.Add(self.param_bitmap[param]) #Enable the default plot parameters for param in self.state.default_plot: self.check_boxes[param].SetValue(True) def _colour_control(self): ''' updates the colours of the control elements ''' selected = self.get_selected_parameters() for param in self.state.attributes: if param in selected: self.param_text[param].Enable() self.param_bitmap[param].Enable() else: self.param_text[param].Disable() #self.param_bitmap[param].Disable() def _update_line_styles(self): ''' Update the colour and style associated with each unit and parameter ''' self.unit_colour = {} self.parameter_style = {} #For tracking the number of parameters per unit unit_count = {} #Determine colours for units for unit in self.state.unit_order: self.unit_colour[unit] = self.line_colours[len(self.unit_colour)] unit_count[unit] = 0 #Determine line styles for parameters for param in self.state.attribute_order: unit = self.state.get_attribute_units(param) print param, unit self.parameter_style[param] = self.line_styles[unit_count[unit]] unit_count[unit] += 1 def _select_parameters(self,parameters = [],redraw=True): '''Set the parameters to be plotted''' self.parameters = parameters if redraw: self.redraw_fromscratch() def update_visibility(self): if SIM_TYPE == SIM_STATIC: enabled = False else: enabled = True self.check_boxes['discounted_profit'].Show(enabled) self.param_text['discounted_profit'].Show(enabled) self.param_bitmap['discounted_profit'].Show(enabled) def update_state(self,state,redraw=True): '''Update the state that is being plotted''' self.state = copy.deepcopy(state) if not hasattr(self,'last_parameters'): self.last_parameters = {} print self.state['discounted_profit'] import numpy self.npv = numpy.nansum(self.state['discounted_profit']) # discount_rate = 0.05 # for index in range(len(self.state['revenue'])): # if self.state['revenue'][index] != None and ~numpy.isnan(self.state['revenue'][index]): # self.npv += (self.state['revenue'][index]-self.state['cost'][index])*(1-discount_rate)**index if redraw: #Update the parameter selection controls if necessary if state.attributes != self.last_parameters: self._setup_control_panel() self.last_parameters = state.attributes self.redraw() def _update_bounds(self): '''Update the figure bounds''' def sig_round(number): '''Ceil a number to a nice round figure for limits''' if number == 0: return 0 sig = number/(10**numpy.floor(numpy.log10(number*2))) if sig < 2: factor_multiple = 2.0 elif sig < 5: factor_multiple = 2.0 else: factor_multiple = 1.0 factor = 10**(numpy.floor(numpy.log10(number*factor_multiple)))/factor_multiple rounded = numpy.ceil(number/factor)*factor print number, rounded return rounded self.xbound = 0 self.bounds = {} for unit in self._get_units(): self.bounds[unit]=[float('inf'), -float('inf')] for param in self.get_selected_parameters(): unit = self.state.get_attribute_units(param) yv = numpy.asarray(self.state[param])/self.state.attributes[param]['scale'] self.bounds[unit][0] = min(self.bounds[unit][0], numpy.nanmin(yv)) self.bounds[unit][1] = max(self.bounds[unit][1], numpy.nanmax(yv)) self.bounds[unit][0] = sig_round(self.bounds[unit][0]) self.bounds[unit][1] = sig_round(self.bounds[unit][1]) if SIM_TYPE == SIM_DYNAMIC: self.xbound = max(self.xbound,len(self.state[param])-1) if SIM_TYPE == SIM_STATIC: if MG_TYPE == MG_QUOTA: self.xbound = numpy.nanmax(numpy.asarray(self.state['catch'])/self.state.attributes['catch']['scale']) else: self.xbound = numpy.nanmax(numpy.asarray(self.state['effort'])/self.state.attributes['effort']['scale']) self.xbound = sig_round(self.xbound) def get_selected_parameters(self): '''Return the parameters that have been selected for plotting''' out = [] for param in self.state.attribute_order: if self.check_boxes[param].GetValue(): out.append(param) return out def _get_units(self): ''' Returns a list of units that will be plotted ''' units = {} for param in self.get_selected_parameters(): units[self.state.get_attribute_units(param)]=1 return units.keys() def _setup_axes(self): ''' Redraw the figure from scratch required if the number of axes etc. have changed ''' #Clear the figure self.fig.clf() #Add the new axes self.axes = {} self.plot_data = {} self.axes_xscale = {} max_width = 0.87 width_increment = 0.07 bottom_space = .13 pos=[.05, bottom_space, max_width-width_increment*(len(self._get_units())-1), 1-bottom_space-0.05] #Create the axes, one for each unit for unit in self._get_units(): first_figure = len(self.axes)==0 colour = self.unit_colour[unit] self.axes[unit] = self.fig.add_axes(pos,frameon=True,label=unit) self.axes[unit].yaxis.tick_right() self.axes[unit].yaxis.set_label_position('right') self.axes[unit].set_ylabel(unit) self.axes_xscale[unit] = pos[2]/(max_width-width_increment*(len(self._get_units())-1)) if not first_figure: self.axes[unit].patch.set_alpha(0) else: self.firstaxes = self.axes[unit] self.axes[unit].set_xlabel('Years') self._modify_axes(self.axes[unit],colour,not first_figure) pos[2] += width_increment #Create the plot lines, one for each parameter for param in self.get_selected_parameters(): unit = self.state.get_attribute_units(param) colour = self.unit_colour[unit] style = self.parameter_style[param] self.plot_data[param] = self.axes[unit].plot([0,0],[0,0],linewidth=2)[0] self.plot_data[param].set_color(colour) self.plot_data[param].set_dashes(style) #Text for npv self.npvtext = self.fig.text(.1,bottom_space,'NPV') def redraw(self,event=None,redraw=False): ''' Update the plots using data in the current state ''' if self.state == None: return if not hasattr(self,'last_selected_parameters'): self.last_selected_parameters = {} #If the selected parameters have changed we need new axes if self.last_selected_parameters != self.get_selected_parameters() or redraw: self.last_selected_parameters = self.get_selected_parameters() self._colour_control() self._setup_axes() self._update_bounds() #Update axes bounds for unit in self._get_units(): bounds = self.bounds[unit] self.axes[unit].set_ybound(lower = 0,upper = bounds[1]) self.axes[unit].set_xbound(lower = 0,upper=self.xbound*self.axes_xscale[unit]) #Update plot data for param in self.get_selected_parameters(): data = self.state[param] if SIM_TYPE == SIM_DYNAMIC: self.plot_data[param].set_xdata(range(len(data))) else: if MG_TYPE == MG_QUOTA: self.plot_data[param].set_xdata(numpy.asarray(self.state['catch'])/self.state.attributes['catch']['scale']) else: self.plot_data[param].set_xdata(numpy.asarray(self.state['effort'])/self.state.attributes['effort']['scale']) self.plot_data[param].set_ydata(numpy.asarray(data)/self.state.attributes[param]['scale']) if SIM_TYPE == SIM_DYNAMIC: self.firstaxes.set_xlabel('Years') else: if MG_TYPE == MG_QUOTA: xunit = 'catch' else: xunit = 'effort' self.firstaxes.set_xlabel('Management Control: ' + self.state.attributes[xunit]['title'] + ' (' + self.state.attributes[xunit]['units'] + ')') if SIM_TYPE == SIM_DYNAMIC and ~numpy.isnan(self.npv): self.npvtext.set_text('NPV: $' + str(int(round(self.npv/self.state.attributes['revenue']['scale']))) + ' million') else: self.npvtext.set_text('') self.canvas.draw() @staticmethod def _modify_axes(axes,color,remove = False): ''' Set the colour of the y axis to color and optionally remove the remaining borders of the graph ''' def modify_all(object,color=None,remove=False): for child in object.get_children(): modify_all(child,color,remove) if remove and hasattr(object,'set_visible'): object.set_visible(not remove) if color != None and hasattr(object,'set_color'): object.set_color(color) for child in axes.get_children(): if isinstance(child, matplotlib.spines.Spine): if child.spine_type == 'right': modify_all(child,color=color) elif remove == True: modify_all(child,remove=True) modify_all(axes.yaxis,color=color) if remove: modify_all(axes.xaxis,remove=True) class AboutBox(wx.Dialog): '''An about dialog box, which displays a html file''' replacements = {'_VERSION_': VERSIONSTRING} def __init__(self,parent,title,filename): ''' parent: parent window title: dialog box title filename: the html file to show ''' wx.Dialog.__init__(self,parent,-1,title,size=(500,550)) #Read the html source file fid = open(filename,'r') self.abouthtml = fid.read() fid.close() #Replace tokens for key in self.replacements.keys(): self.abouthtml = self.abouthtml.replace(key,self.replacements[key]) self.html = wx.html.HtmlWindow(self) self.html.SetPage(self.abouthtml) self.ok_button = wx.Button(self,wx.ID_OK,"Ok") self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.html,1,wx.EXPAND|wx.ALL,5) self.sizer.Add(self.ok_button,0,wx.ALIGN_CENTER|wx.ALL,5) self.SetSizer(self.sizer) self.Layout() x=1366 y=768 class App(wx.App): def OnInit(self): self.frame = Frame(x,y) self.SetTopWindow(self.frame) self.frame.Show() self.frame.Layout() return True if __name__ == '__main__': app = App(redirect=False) # app = App(redirect=False) app.MainLoop()
Python
#!/usr/bin/env python '''Fisheries Economics Masterclass model''' import threading import wx from pylab import * import copy class Parameter(dict): """ Model parameter class A simple dict with some default values """ def __init__(self,value=0,min=0,max=1,units='',title='',description='',type='Miscellaneous',scale=1,scale_text=''): """Initialise the parameter""" self['value'] = value self['min'] = min self['max'] = max self['units'] = units self['title'] = title self['description'] = description self['type'] = type self['scale'] = scale self['scale_text']=scale_text class Component: """ Model component class All model classes should inherit this """ def get_parameters(self): """ Returns the parameters required by this component The format is a dictionary, keys are parameter name, value is a list of minimum value, maximum value, default value, """ return {} def execute(self,state,parameters): """Executes this component and returns the modified state""" return state class PDLogistic(Component): """Population Dynamics Logistic growth component""" def __init__(self): self.r = Parameter(title='Population growth rate', description='The maximum growth rate of the population', type='Population dynamics') self.K = Parameter(title='Maximum population size', description='The size of a unfished (virgin) population', type='Population dynamics') def get_parameters(self): return {'r': self.r,'K': self.K} #Execute a logistic step def execute(self,state,parameters,equilibrium=False): if equilibrium: r = parameters['r'] K = parameters['K'] if parameters.has_key('catch'): C = parameters['catch'] # [r-1 + (1-2r+r2+4Cr/K)^.5]/(2r/K) term = (r)**2-4*C*r/K #term = (1-4*parameters['catch']/parameters['r']/parameters['K']) if term < 0: state['biomass'][-1] = 0 else: #state['biomass'][-1] = parameters['K']/2*(1+term**0.5)#+parameters['catch'] #Catch is added back on as the catch step removes it state['biomass'][-1] = (r+term**.5)/(2*r/K) state['biomass'][-1] += parameters['catch'] #Catch is added back on as the catch step removes it else: catch = state['biomass'][-1]* parameters['catch_rate']*parameters['effort']/parameters['K'] state['biomass'][-1] = parameters['K']-parameters['catch_rate']*parameters['effort']/parameters['r'] state['biomass'][-1] += catch #state['biomass'][-1] = K*(1-r) else: b = state['biomass'][-1] state['biomass'][-1] = b+b*parameters['r']*(1-b/parameters['K']) return state #Catch component removes catch determines CPUE class CatchFixed(Component): """Fixed catch component with simplistic CPUE/effort calculation""" catch_rate = Parameter(title='Max catch rate', description='The biomass caught per unit of effort', type='Fleet dynamics') catch = Parameter(title='TAC', description='Total allowable catch', type='Management Controls' ) def get_parameters(self): return {'catch_rate': self.catch_rate, 'catch': self.catch} def execute(self,state,parameters,equilibrium=False): preCatchBiomass = state.get('biomass') previousBiomass = state['biomass'][-2] state.set(cpue=previousBiomass/parameters['K']*parameters['catch_rate']) state.set(biomass=preCatchBiomass-parameters['catch']) state.set(catch=parameters['catch']) if state.get('biomass') < 0: state.set(biomass=0,catch= preCatchBiomass) if state.get('cpue') <= 0: state.set(effort=0) else: state.set(effort=state.get('catch')/state.get('cpue')) return state #Constant effort class EffortFixed(Component): """Fixed catch component with simplistic CPUE/effort calculation""" catch_rate = Parameter(title='Max catch rate', description='The biomass caught per unit of effort', type='Fleet dynamics') effort = Parameter( title='Effort', description='Fishing effort', type='Management Controls' ) def get_parameters(self): return {'catch_rate': self.catch_rate, 'effort': self.effort} def execute(self,state,parameters,equilibrium=False): previousBiomass = state['biomass'][-2] preCatchBiomass = state['biomass'][-1] state.set(cpue=previousBiomass/parameters['K']*parameters['catch_rate']) state.set(catch=parameters['effort']*state.get('cpue')) state.set(biomass=preCatchBiomass-state.get('catch')) if state.get('biomass') < 0: state.set(biomass=0,catch= preCatchBiomass) state.set(effort=parameters['effort']) return state class Economics(Component): fixed_cost = Parameter( title='Operator fixed cost', description='An individual operator\s fixed annual cost', type='Economics') marginal_cost= Parameter( title='Operator marginal cost', description='An individual operator\s marginal cost per unit effort', type='Economics') movement_rate= Parameter( title='Fleet resize rate', description='The maximum rate at which vessels can enter or exit the fishery', type='Fleet dynamics') beach_price = Parameter( title='Beach price', description='The price per kg of landed fish', type='Economics') discount_rate = Parameter( title='Discount Rate', description='The discount rate', type='Economics') def get_parameters(self): return {'fixed_cost': self.fixed_cost, 'marginal_cost': self.marginal_cost, 'movement_rate': self.movement_rate, 'beach_price': self.beach_price, 'discount_rate': self.discount_rate} @staticmethod def _calculate_revenue(state,parameters): return state.get('catch')*parameters['beach_price'] @staticmethod def _calculate_cost(state,parameters): return (state.get('fleet_size')*parameters['fixed_cost']+\ state.get('effort')*parameters['marginal_cost']) @staticmethod def _calculate_profit(state,parameters): return Economics._calculate_revenue(state,parameters)-Economics._calculate_cost(state,parameters) def execute(self,state,parameters,equilibrium=False): #Adjust the fleet size original_fleet_size = state.get('fleet_size') while abs(self._calculate_profit(state,parameters))>parameters['fixed_cost'] and \ ((equilibrium and parameters['movement_rate'] > 0) or abs(original_fleet_size - state.get('fleet_size')) < parameters['movement_rate']): if self._calculate_profit(state,parameters) > 0: state.set(fleet_size = state.get('fleet_size')+1) else: state.set(fleet_size = state.get('fleet_size')-1) #Set the cost, revenue and profit state.set(cost = self._calculate_cost(state, parameters)) state.set(revenue = self._calculate_revenue(state,parameters)) profit = state.get('revenue')-state.get('cost') if abs(profit)<1000000: profit = 0 state.set(profit = profit) state.set(discounted_profit = profit*(1-parameters['discount_rate'])**(len(state['cost'])-2)) return state class State(dict): """Model state A dictionary where each key corresponds to an attribute of a fishery state (eg. biomass) all keys are the same length and can be extended trivially """ def __init__(self, attributes): """ Constructor attribute_list is a dictionary for the attributes of the fishery see example fishery models for details """ for key in attributes: self[key] = [nan] self.attributes = attributes self.attribute_order = self.attributes.keys() #The attributes to plot first up by default self.default_plot = self.attributes.keys() self.unit_order = [] units = {} for att in self.attributes: unit = self.attributes[att]['units'] if not units.has_key(unit): units[unit]=1 self.unit_order.append(unit) def extend(self): """Extend all the lists by one, using the previous value for the new value""" for att in self: self[att].append(self[att][-1]) return def set(self,**kwargs): """Set the current (last item) of one or more of the lists""" for key in kwargs: self[key][-1]=kwargs[key] def get(self,item): """Get the current (last item) of one of the lists""" return self[item][-1] def get_attribute_title(self,attribute): return self.attributes[attribute]['title'] def get_attribute_units(self,attribute): return self.attributes[attribute]['units'] def reset(self): """ Resets the state to the initial timestep """ for att in self: self[att]=self[att][0:1] return class Model(): """Model Definition By combining a set of model functions this class creates a complete model definition""" def __init__(self,functions=[],parameters={},initial_state = None,convergence_time=3): """ functions: a list of functions in the order that they are to be run parameters: a dict of parameters as required by the functions (can be set later) initial_state: initial state of the fishery convergence_time: number of steps required to convergence of static version """ if initial_state == None: self.state = State() else: self.state = initial_state self.functions = functions self.parameters = parameters self.convergence_time = convergence_time def get_parameters(self): """ returns a list of parameters as required by the model functions """ #Get all parameters pOut = {} for function in self.functions: pOut.update(function.get_parameters()) #Replace values with current if applicable for param in pOut: if self.parameters.has_key(param): pOut[param].value = self.parameters[param] return pOut def set_parameters(self,parameters): """ set the parameters to a given value for this and subsequent time steps """ self.parameters = parameters def get_parameter_types(self): """ return a list of parameter types """ types = {} p = self.get_parameters() for par in p: types[p[par]['type']] = 1 return types.keys() def set_state(self,state): """ set the state of the model """ self.state = state def reset(self): """ Resets the model state to the initial timestep """ self.state.reset() def run(self,steps = 1,constant_variable=None): """ run the model for one time step """ for step in range(0,steps): self.state.extend() for function in self.functions: self.state=function.execute(self.state,self.parameters,equilibrium=constant_variable!=None) class MultiThreadModelRun: class MyThread(threading.Thread): def __init__(self,function): '''Initialise the thread: function: a function to be called after run completion ''' threading.Thread.__init__(self) self.function = function self.update = False self.cancel_run = False def update_run(self,model,steps,options): '''Start a new run model: the model to use options: the run options ''' self.newmodel = copy.deepcopy(model) self.newsteps = steps self.newoptions = options self.update = True def run(self): '''The thread's run function''' import time while True: #Cancelling the thread's run for now if self.cancel_run: self.cancel_run = False self.update = False #Creating a new run if self.update: self.model = self.newmodel self.options = self.newoptions self.steps = self.newsteps self.update = False for step in range(0,self.steps): if self.update: break self.single_iteration(step) if not self.update: if not self.function==None: wx.CallAfter(self.function,self.output()) else: time.sleep(0.01) pass def cancel(self): '''Cancel this run''' self.update = True self.cancel_run = True def single_iteration(self,step): '''Perform a single iteration (to be implemented by inheriting class)''' pass def output(self): '''Return the model output (to be implemented by inheriting class)''' pass class DynamicThread(MyThread): '''Thread for dynamic model runs''' def single_iteration(self,step): '''Run a single time step''' self.model.run(1) def output(self): '''Return the model state''' return self.model.state class StaticThread(MyThread): '''Thread for static model runs''' def update_run(self,model,steps,options): '''Update the run, copying a new output state as well''' #MultiThreadModelRun.MyThread.update_run(self,model,steps,options) self.newmodel = copy.deepcopy(model) self.newsteps = steps self.newoptions = options self.update = True self.output_state = copy.deepcopy(self.newmodel.state) self.output_state.reset() def single_iteration(self,step): '''Find an equilibrium state for a single independent parameter value''' #Reset the model self.model.reset() #Set the independent value to the appropriate value self.model.state[self.options['independent_variable']] = [self.options['independent_values'][step]] self.model.parameters[self.options['independent_variable']] = self.options['independent_values'][step] self.model.run(self.options['convergence_time'],constant_variable = self.options['independent_variable']) if True: #self.model.state[self.options['independent_variable']][-1] == self.options['independent_values'][step]: for param in self.model.state.keys(): self.output_state[param].append(self.model.state[param][-1]) if self.model.state[self.options['independent_variable']][-1] < self.options['independent_values'][step]: print 'a' self.output_state[self.options['independent_variable']][-1] = self.options['independent_values'][step-1]+1e-6 # self.output_state[self.options['independent_variable']][-1] = self.options['independent_values'][step] def output(self): '''Return the output state''' return self.output_state def __init__(self,function=None): self.static_thread = self.StaticThread(function) self.static_thread.start() self.dynamic_thread = self.DynamicThread(function) self.dynamic_thread.start() def run(self,model,steps,dynamic=True,independent_variable='effort',independent_minimum = 0,independent_maximum = None,convergence_time=4): if dynamic: self.static_thread.cancel() self.dynamic_thread.update_run(model,steps,{}) else: self.dynamic_thread.cancel() self.static_thread.update_run(model,steps, { 'independent_variable': independent_variable, 'independent_values': linspace(independent_minimum,independent_maximum,steps), 'convergence_time':convergence_time}) def lobsterModel(control_type = 'catch'): '''A lobster model, loosely based on the Tasmanian Rock Lobster Fishery''' #------------------------------------------ #Parameter values customised for this model #------------------------------------------ r = {'value':1,'min':0,'max':2} K = {'value':7000000,'min':0,'max':10000000,'scale':1000,'units':'t'} catch_rate ={'value':1,'min':0.001,'max':5,'units':'kg/potlift'} catch = {'value':1500000,'min':0,'max':6000000,'scale':1000,'units':'t'} effort = {'value':1500000,'min':0,'max':5000000,'description':'Number of potlifts','scale':1e6,'scale_text':'millions'} fixed_cost ={'value':100000,'min':50000,'max':200000,'units':'$/year','scale':1000,'scale_text':'thousands'} marginal_cost= {'value':30,'min':5,'max':50,'units':'$/potlift'} movement_rate={'value':0,'min':0,'max':20,'units':'vessels/year'} beach_price = {'value':60,'min':0,'max':100,'units':'$/kg'} discount_rate = {'value':0.07,'min':0,'max':1,'units':''} #----------------------------------------- #Functions that control the model dynamics #----------------------------------------- #Discrete logistic growth growthClass = PDLogistic() growthClass.r.update(r) growthClass.K.update(K) #Catch component if control_type == 'catch': catchClass = CatchFixed() catchClass.catch.update(catch) elif control_type == 'effort': catchClass = EffortFixed() catchClass.effort.update(effort) catchClass.catch_rate.update(catch_rate) #Economics and fleet dynamics economicsClass = Economics() economicsClass.fixed_cost.update(fixed_cost) economicsClass.marginal_cost.update(marginal_cost) economicsClass.movement_rate.update(movement_rate) economicsClass.beach_price.update(beach_price) economicsClass.discount_rate.update(discount_rate) #----------------------------------------- #Set the state of the fishery #The attributes here must match what is #required by the functions PDLogistic, #CatchFixed/EffortFixed and Economics #----------------------------------------- initial_state = State( attributes = {'biomass': {'title': 'Biomass', 'units': 'tonnes','scale':1000}, 'catch': {'title': 'Catch', 'units': 'tonnes','scale':1000}, 'cpue': {'title': 'CPUE', 'units': 'kg/potlift','scale':1}, 'effort': {'title': 'Effort', 'units': 'millions of potlifts','scale':1e6}, 'fleet_size': {'title': 'Fleet Size','units': '# vessels','scale':1}, 'revenue': {'title': 'Revenue','units': '$ (millions)','scale':1e6}, 'cost': {'title': 'Cost','units': '$ (millions)','scale':1e6}, 'profit': {'title': 'Profit','units': '$ (millions)','scale':1e6}, 'discounted_profit': {'title': 'Discounted profit','units': '$ (millions)','scale':1e6}, }) initial_state.default_plot = ['biomass','catch'] # initial_state.default_plot = ['catch','revenue','cost','profit'] initial_state.attribute_order = ['biomass','catch','profit','revenue','cost','discounted_profit','cpue','effort','fleet_size'] #Set the initial fishery parameters initial_state.set(biomass=5000000,fleet_size=120) #----------------------------------------- #Create the fishery model #----------------------------------------- model = Model(functions = [growthClass,catchClass,economicsClass],initial_state = initial_state) return model
Python
import numpy as np #A set of safe plotting colours from http://jfly.iam.u-tokyo.ac.jp/color/ rgb = np.array([[0,0,0],[230,159,0],[86,180,233],[0,158,115],[240,228,66],[0,114,178],[213,94,0],[204,121,167]]) rgbScaled = rgb/255.0 #Colormaps from #A. Light & P.J. Bartlein, "The End of the Rainbow? Color Schemes for #Improved Data Graphics," Eos,Vol. 85, No. 40, 5 October 2004. #http://geography.uoregon.edu/datagraphics/EOS/Light&Bartlein_EOS2004.pdf def makeMap(inMap,name): import numpy import matplotlib inMap = numpy.array(inMap)/255.0 return matplotlib.colors.LinearSegmentedColormap.from_list(name,inMap) blueMap = makeMap([[243,246,248],[224,232,240],[171,209,236],[115,180,224],[35,157,213],[0,142,205],[0,122,192]],'cbBlue') blueGrayMap = makeMap([[0,170,227],[53,196,238],[133,212,234],[190,230,242],[217,224,230],[146,161,170],[109,122,129],[65,79,81]],'cbBlueGray') brownBlueMap = makeMap([[144,100,44],[187,120,54],[225,146,65],[248,184,139],[244,218,200],[241,244,245],[207,226,240],[160,190,225],[109,153,206],[70,99,174],[24,79,162]],'cbBrownBlue') redBlueMap = makeMap([[175,53,71],[216,82,88],[239,133,122],[245,177,139],[249,216,168],[242,238,197],[216,236,241],[154,217,238],[68,199,239],[0,170,226],[0,116,188]],'cbRedBlue')
Python
#!/usr/bin/env python ''' Fisheries Economics Masterclass model Copyright 2010, University of Tasmania, Australian Seafood CRC This program is released under the Open Software License ("OSL") v. 3.0. See OSL3.0.htm for details. ''' import threading import wx from pylab import * import copy class Parameter(dict): """ Model parameter class A simple dict with some default values """ def __init__(self,value=0,min=0,max=1,units='',title='',description='',type='Miscellaneous',scale=1,scale_text=''): """Initialise the parameter""" self['value'] = value self['min'] = min self['max'] = max self['units'] = units self['title'] = title self['description'] = description self['type'] = type self['scale'] = scale self['scale_text']=scale_text class Component: """ Model component class All model classes should inherit this """ def get_parameters(self): """ Returns the parameters required by this component The format is a dictionary, keys are parameter name, value is a list of minimum value, maximum value, default value, """ return {} def execute(self,state,parameters): """Executes this component and returns the modified state""" return state class PDLogistic(Component): """Population Dynamics Logistic growth component""" def __init__(self): self.r = Parameter(title='Population growth rate', description='The maximum growth rate of the population', type='Population dynamics') self.K = Parameter(title='Maximum population size', description='The size of a unfished (virgin) population', type='Population dynamics') def get_parameters(self): return {'r': self.r,'K': self.K} #Execute a logistic step def execute(self,state,parameters,equilibrium=False): if equilibrium: r = parameters['r'] K = parameters['K'] if parameters.has_key('catch'): C = parameters['catch'] # [r-1 + (1-2r+r2+4Cr/K)^.5]/(2r/K) term = (r)**2-4*C*r/K #term = (1-4*parameters['catch']/parameters['r']/parameters['K']) if term < 0: state['biomass'][-1] = 0 else: #state['biomass'][-1] = parameters['K']/2*(1+term**0.5)#+parameters['catch'] #Catch is added back on as the catch step removes it state['biomass'][-1] = (r+term**.5)/(2*r/K) state['biomass'][-1] += parameters['catch'] #Catch is added back on as the catch step removes it else: catch = state['biomass'][-1]* parameters['catch_rate']*parameters['effort']/parameters['K'] state['biomass'][-1] = parameters['K']-parameters['catch_rate']*parameters['effort']/parameters['r'] state['biomass'][-1] += catch #state['biomass'][-1] = K*(1-r) else: b = state['biomass'][-1] state['biomass'][-1] = b+b*parameters['r']*(1-b/parameters['K']) return state #Catch component removes catch determines CPUE class CatchFixed(Component): """Fixed catch component with simplistic CPUE/effort calculation""" catch_rate = Parameter(title='Max catch rate', description='The biomass caught per unit of effort', type='Fleet dynamics') catch = Parameter(title='TAC', description='Total allowable catch', type='Management Controls' ) def get_parameters(self): return {'catch_rate': self.catch_rate, 'catch': self.catch} def execute(self,state,parameters,equilibrium=False): preCatchBiomass = state.get('biomass') previousBiomass = state['biomass'][-2] state.set(cpue=previousBiomass/parameters['K']*parameters['catch_rate']) state.set(biomass=preCatchBiomass-parameters['catch']) state.set(catch=parameters['catch']) if state.get('biomass') < 0: state.set(biomass=0,catch= preCatchBiomass) if state.get('cpue') <= 0: state.set(effort=0) else: state.set(effort=state.get('catch')/state.get('cpue')) return state #Constant effort class EffortFixed(Component): """Fixed catch component with simplistic CPUE/effort calculation""" catch_rate = Parameter(title='Max catch rate', description='The biomass caught per unit of effort', type='Fleet dynamics') effort = Parameter( title='Effort', description='Fishing effort', type='Management Controls' ) def get_parameters(self): return {'catch_rate': self.catch_rate, 'effort': self.effort} def execute(self,state,parameters,equilibrium=False): previousBiomass = state['biomass'][-2] preCatchBiomass = state['biomass'][-1] state.set(cpue=previousBiomass/parameters['K']*parameters['catch_rate']) state.set(catch=parameters['effort']*state.get('cpue')) state.set(biomass=preCatchBiomass-state.get('catch')) if state.get('biomass') < 0: state.set(biomass=0,catch= preCatchBiomass) state.set(effort=parameters['effort']) return state class Economics(Component): fixed_cost = Parameter( title='Operator fixed cost', description='An individual operator\s fixed annual cost', type='Economics') marginal_cost= Parameter( title='Operator marginal cost', description='An individual operator\s marginal cost per unit effort', type='Economics') movement_rate= Parameter( title='Fleet resize rate', description='The maximum rate at which vessels can enter or exit the fishery', type='Fleet dynamics') beach_price = Parameter( title='Beach price', description='The price per kg of landed fish', type='Economics') discount_rate = Parameter( title='Discount Rate', description='The discount rate', type='Economics') def get_parameters(self): return {'fixed_cost': self.fixed_cost, 'marginal_cost': self.marginal_cost, 'movement_rate': self.movement_rate, 'beach_price': self.beach_price, 'discount_rate': self.discount_rate} @staticmethod def _calculate_revenue(state,parameters): return state.get('catch')*parameters['beach_price'] @staticmethod def _calculate_cost(state,parameters): return (state.get('fleet_size')*parameters['fixed_cost']+\ state.get('effort')*parameters['marginal_cost']) @staticmethod def _calculate_profit(state,parameters): return Economics._calculate_revenue(state,parameters)-Economics._calculate_cost(state,parameters) def execute(self,state,parameters,equilibrium=False): #Adjust the fleet size original_fleet_size = state.get('fleet_size') while abs(self._calculate_profit(state,parameters))>parameters['fixed_cost'] and \ ((equilibrium and parameters['movement_rate'] > 0) or abs(original_fleet_size - state.get('fleet_size')) < parameters['movement_rate']): if self._calculate_profit(state,parameters) > 0: state.set(fleet_size = state.get('fleet_size')+1) else: state.set(fleet_size = state.get('fleet_size')-1) #Set the cost, revenue and profit state.set(cost = self._calculate_cost(state, parameters)) state.set(revenue = self._calculate_revenue(state,parameters)) profit = state.get('revenue')-state.get('cost') if abs(profit)<1000000: profit = 0 state.set(profit = profit) state.set(discounted_profit = profit*(1-parameters['discount_rate'])**(len(state['cost'])-2)) return state class State(dict): """Model state A dictionary where each key corresponds to an attribute of a fishery state (eg. biomass) all keys are the same length and can be extended trivially """ def __init__(self, attributes): """ Constructor attribute_list is a dictionary for the attributes of the fishery see example fishery models for details """ for key in attributes: self[key] = [nan] self.attributes = attributes self.attribute_order = self.attributes.keys() #The attributes to plot first up by default self.default_plot = self.attributes.keys() self.unit_order = [] units = {} for att in self.attributes: unit = self.attributes[att]['units'] if not units.has_key(unit): units[unit]=1 self.unit_order.append(unit) def extend(self): """Extend all the lists by one, using the previous value for the new value""" for att in self: self[att].append(self[att][-1]) return def set(self,**kwargs): """Set the current (last item) of one or more of the lists""" for key in kwargs: self[key][-1]=kwargs[key] def get(self,item): """Get the current (last item) of one of the lists""" return self[item][-1] def get_attribute_title(self,attribute): return self.attributes[attribute]['title'] def get_attribute_units(self,attribute): return self.attributes[attribute]['units'] def reset(self): """ Resets the state to the initial timestep """ for att in self: self[att]=self[att][0:1] return class Model(): """Model Definition By combining a set of model functions this class creates a complete model definition""" def __init__(self,functions=[],parameters={},initial_state = None,convergence_time=3): """ functions: a list of functions in the order that they are to be run parameters: a dict of parameters as required by the functions (can be set later) initial_state: initial state of the fishery convergence_time: number of steps required to convergence of static version """ if initial_state == None: self.state = State() else: self.state = initial_state self.functions = functions self.parameters = parameters self.convergence_time = convergence_time def get_parameters(self): """ returns a list of parameters as required by the model functions """ #Get all parameters pOut = {} for function in self.functions: pOut.update(function.get_parameters()) #Replace values with current if applicable for param in pOut: if self.parameters.has_key(param): pOut[param].value = self.parameters[param] return pOut def set_parameters(self,parameters): """ set the parameters to a given value for this and subsequent time steps """ self.parameters = parameters def get_parameter_types(self): """ return a list of parameter types """ types = {} p = self.get_parameters() for par in p: types[p[par]['type']] = 1 return types.keys() def set_state(self,state): """ set the state of the model """ self.state = state def reset(self): """ Resets the model state to the initial timestep """ self.state.reset() def run(self,steps = 1,constant_variable=None): """ run the model for one time step """ for step in range(0,steps): self.state.extend() for function in self.functions: self.state=function.execute(self.state,self.parameters,equilibrium=constant_variable!=None) class MultiThreadModelRun: class MyThread(threading.Thread): def __init__(self,function): '''Initialise the thread: function: a function to be called after run completion ''' threading.Thread.__init__(self) self.function = function self.update = False self.cancel_run = False def update_run(self,model,steps,options): '''Start a new run model: the model to use options: the run options ''' self.newmodel = copy.deepcopy(model) self.newsteps = steps self.newoptions = options self.update = True def run(self): '''The thread's run function''' import time while True: #Cancelling the thread's run for now if self.cancel_run: self.cancel_run = False self.update = False #Creating a new run if self.update: self.model = self.newmodel self.options = self.newoptions self.steps = self.newsteps self.update = False for step in range(0,self.steps): if self.update: break self.single_iteration(step) if not self.update: if not self.function==None: wx.CallAfter(self.function,self.output()) else: time.sleep(0.01) pass def cancel(self): '''Cancel this run''' self.update = True self.cancel_run = True def single_iteration(self,step): '''Perform a single iteration (to be implemented by inheriting class)''' pass def output(self): '''Return the model output (to be implemented by inheriting class)''' pass class DynamicThread(MyThread): '''Thread for dynamic model runs''' def single_iteration(self,step): '''Run a single time step''' self.model.run(1) def output(self): '''Return the model state''' return self.model.state class StaticThread(MyThread): '''Thread for static model runs''' def update_run(self,model,steps,options): '''Update the run, copying a new output state as well''' #MultiThreadModelRun.MyThread.update_run(self,model,steps,options) self.newmodel = copy.deepcopy(model) self.newsteps = steps self.newoptions = options self.update = True self.output_state = copy.deepcopy(self.newmodel.state) self.output_state.reset() def single_iteration(self,step): '''Find an equilibrium state for a single independent parameter value''' #Reset the model self.model.reset() #Set the independent value to the appropriate value self.model.state[self.options['independent_variable']] = [self.options['independent_values'][step]] self.model.parameters[self.options['independent_variable']] = self.options['independent_values'][step] self.model.run(self.options['convergence_time'],constant_variable = self.options['independent_variable']) if True: #self.model.state[self.options['independent_variable']][-1] == self.options['independent_values'][step]: for param in self.model.state.keys(): self.output_state[param].append(self.model.state[param][-1]) if self.model.state[self.options['independent_variable']][-1] < self.options['independent_values'][step]: print 'a' self.output_state[self.options['independent_variable']][-1] = self.options['independent_values'][step-1]+1e-6 # self.output_state[self.options['independent_variable']][-1] = self.options['independent_values'][step] def output(self): '''Return the output state''' return self.output_state def __init__(self,function=None): self.static_thread = self.StaticThread(function) self.static_thread.start() self.dynamic_thread = self.DynamicThread(function) self.dynamic_thread.start() def run(self,model,steps,dynamic=True,independent_variable='effort',independent_minimum = 0,independent_maximum = None,convergence_time=4): if dynamic: self.static_thread.cancel() self.dynamic_thread.update_run(model,steps,{}) else: self.dynamic_thread.cancel() self.static_thread.update_run(model,steps, { 'independent_variable': independent_variable, 'independent_values': linspace(independent_minimum,independent_maximum,steps), 'convergence_time':convergence_time}) def lobsterModel(control_type = 'catch'): '''A lobster model, loosely based on the Tasmanian Rock Lobster Fishery''' #------------------------------------------ #Parameter values customised for this model #------------------------------------------ r = {'value':1,'min':0,'max':2} K = {'value':7000000,'min':0,'max':10000000,'scale':1000,'units':'t'} catch_rate ={'value':1,'min':0.001,'max':5,'units':'kg/potlift'} catch = {'value':1500000,'min':0,'max':6000000,'scale':1000,'units':'t'} effort = {'value':1500000,'min':0,'max':5000000,'description':'Number of potlifts','scale':1e6,'scale_text':'millions'} fixed_cost ={'value':100000,'min':50000,'max':200000,'units':'$/year','scale':1000,'scale_text':'thousands'} marginal_cost= {'value':30,'min':5,'max':50,'units':'$/potlift'} movement_rate={'value':0,'min':0,'max':20,'units':'vessels/year'} beach_price = {'value':60,'min':0,'max':100,'units':'$/kg'} discount_rate = {'value':0.07,'min':0,'max':1,'units':''} #----------------------------------------- #Functions that control the model dynamics #----------------------------------------- #Discrete logistic growth growthClass = PDLogistic() growthClass.r.update(r) growthClass.K.update(K) #Catch component if control_type == 'catch': catchClass = CatchFixed() catchClass.catch.update(catch) elif control_type == 'effort': catchClass = EffortFixed() catchClass.effort.update(effort) catchClass.catch_rate.update(catch_rate) #Economics and fleet dynamics economicsClass = Economics() economicsClass.fixed_cost.update(fixed_cost) economicsClass.marginal_cost.update(marginal_cost) economicsClass.movement_rate.update(movement_rate) economicsClass.beach_price.update(beach_price) economicsClass.discount_rate.update(discount_rate) #----------------------------------------- #Set the state of the fishery #The attributes here must match what is #required by the functions PDLogistic, #CatchFixed/EffortFixed and Economics #----------------------------------------- initial_state = State( attributes = {'biomass': {'title': 'Biomass', 'units': 'tonnes','scale':1000}, 'catch': {'title': 'Catch', 'units': 'tonnes','scale':1000}, 'cpue': {'title': 'CPUE', 'units': 'kg/potlift','scale':1}, 'effort': {'title': 'Effort', 'units': 'millions of potlifts','scale':1e6}, 'fleet_size': {'title': 'Fleet Size','units': '# vessels','scale':1}, 'revenue': {'title': 'Revenue','units': '$ (millions)','scale':1e6}, 'cost': {'title': 'Cost','units': '$ (millions)','scale':1e6}, 'profit': {'title': 'Profit','units': '$ (millions)','scale':1e6}, 'discounted_profit': {'title': 'Discounted profit','units': '$ (millions)','scale':1e6}, }) initial_state.default_plot = ['biomass','catch'] # initial_state.default_plot = ['catch','revenue','cost','profit'] initial_state.attribute_order = ['biomass','catch','profit','revenue','cost','discounted_profit','cpue','effort','fleet_size'] #Set the initial fishery parameters initial_state.set(biomass=5000000,fleet_size=120) #----------------------------------------- #Create the fishery model #----------------------------------------- model = Model(functions = [growthClass,catchClass,economicsClass],initial_state = initial_state) return model
Python
#import matplotlib as mp #mp.use('GTK') #from matplotlib.figure import Figure #from matplotlib.pyplot import show import matplotlib.pyplot as plt figure = plt.figure() pos = [.1,.1,.8,.8] pos2 = list(pos) pos2[2]=.75 print pos print pos2 ax1 = figure.add_axes(pos, frameon = False,label ='a') ax2 = figure.add_axes(pos2, frameon = False,label = 'b') ax1.yaxis.tick_right() ax1.yaxis.set_label_position('right') ax2.yaxis.tick_right() ax2.yaxis.set_label_position('right') ax1.set_ylabel('fda') ax2.set_ylabel('$') ax1.plot([0,1],[1,2],'r:') ax2.plot([0,1],[10,1],'g-') plt.show()
Python
#!/usr/bin/env python """ Fisheries Economics Masterclass GUI Klaas Hartmann 2010 Copyright 2010, University of Tasmania, Australian Seafood CRC This program is released under the Open Software License ("OSL") v. 3.0. See OSL3.0.htm for details. """ import wx import wx.html import fisheries_model import colourblind import matplotlib #matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import \ FigureCanvasWxAgg as FigCanvas import numpy import copy import os import sys #String constants for some menus etc MG_QUOTA='Output Controlled' MG_EFFORT='Input Controlled' SIM_DYNAMIC='Dynamic' SIM_STATIC='Static (Equilibrium)' #Version history: #1.00 Initial release from Hobart Class 1 #1.01 Made fishery crash instantaneous. #1.02 Initial version on Google Code #1.03 Included licencing information VERSIONSTRING = '1.03' #Globals that specify the current simulation and management type #(to be subsumed at a later stage...) SIM_TYPE='' MG_TYPE='' class Frame(wx.Frame): '''The main (only?) GUI Frame''' def __init__(self,width,height): wx.Frame.__init__(self, None, size=wx.Size(width,height), title = 'Fisheries Explorer') #self.SetSize(wx.Size(width,height)) #Set the starting simulation and management types global SIM_TYPE global MG_TYPE MG_TYPE = MG_QUOTA SIM_TYPE = SIM_STATIC self.Maximize() #Initialise model components self._init_model() #Initialise model/graph update system self._init_update() #Initialise GUI components self._init_gui() def _init_update(self): '''Initialise model/graph update system''' #Will contain current parameters self.parameters= {} #Will contain last parameters for which the model run was completed self.computed_parameters = {} #Will contain last parameters for which a graph was produced self.plotted_parameters = {} #Whether current computation has been completed self.computed_complete = True #Timer for model reruns self.timer_model = wx.Timer(self) self.timer_model.Start(250) wx.EVT_TIMER(self,self.timer_model.GetId(),self.on_timer_model) #Hack to call layout after init self.timer_init_hack = wx.Timer(self) self.timer_init_hack.Start(250) wx.EVT_TIMER(self,self.timer_init_hack.GetId(),self.on_timer_init_hack) #The model execution thread self.model_thread = fisheries_model.MultiThreadModelRun(self.model_data_updater) def _init_model(self,type='catch'): '''Initialise model''' self.model = fisheries_model.lobsterModel(control_type = type) def _init_gui(self): '''Initialise GUI components''' #Setup sizers (in hierarchical order) self.sizer = wx.FlexGridSizer(rows=2,cols=1) #Create wx objects self.parameter_panel = ParameterPanel(self,self.model,sim_update_fx=self.on_simulation_change) self.plot_panel = PlotPanel(self) #Set up main sizer self.sizer.Add(self.parameter_panel,0,wx.EXPAND) self.sizer.Add(self.plot_panel,0,wx.EXPAND) self.sizer.AddGrowableCol(0,1) self.sizer.AddGrowableRow(1,1) #Set sizers self.SetSizer(self.sizer) #Set menu self.menubar = MenuBar(self,sim_update_fx=self.on_simulation_change,parameter_type_fx=self.parameter_panel.show_parameter_set,reset_model_fx=self.on_simulation_change) self.SetMenuBar(self.menubar) self.menubar.set_parameter_types(self.model.get_parameter_types()) #Bind events self.Bind(wx.EVT_SCROLL,self.on_slide_change) #self.Bind(wx.EVT_CLOSE, self.onCloseWindow) self.on_slide_change(None) self.on_timer_model(None) #Prevent the frame getting resized too small min_size = self.sizer.GetMinSize() self.SetMinSize(min_size) #Set the icon self.icon = wx.Icon(os.path.join('images','fishnet.ico'),wx.BITMAP_TYPE_ICO) self.SetIcon(self.icon) #It still doesn't close cleanly for some unknown reason.. block = False def onCloseWindow(self,event): self.timer_model.Stop() self.timer_model.Destroy() self.icon.Destroy() event.Skip() def on_timer_model(self,event): '''Rerun the model if parameters have changed''' #If parameters have changed we need to recalculate the model if self.parameters != self.computed_parameters: self.computed_complete=False self.model.set_parameters(self.parameter_panel.get_parameters()) self.model.reset() #Run the appropriate simulation if SIM_TYPE == SIM_STATIC: if MG_TYPE == MG_QUOTA: max= self.parameters['K']*self.parameters['r']/4*1.01 self.model_thread.run(self.model,20,dynamic=False,independent_variable='catch',independent_maximum=max) else: self.model_thread.run(self.model,20,dynamic=False,independent_variable='effort',independent_maximum=6e6) else: self.model_thread.run(self.model,20) self.computed_parameters = self.parameters init_hack_count = 0 def on_timer_init_hack(self,event): '''A hack to layout the plot panel after load. For some reason the legend is not displayed correctly.''' if self.init_hack_count > 0: self.timer_init_hack.Stop() self.init_hack_count += 1 self.plot_panel.update_visibility() self.plot_panel.OnSize() self.plot_panel.Layout() def on_simulation_change(self,simulation_type,control_type): '''Called if the simulation type (static/dynamic, quota/effort controlled) changes''' global SIM_TYPE global MG_TYPE SIM_TYPE = simulation_type MG_TYPE = control_type #Initialise the model with appropriate control type if MG_TYPE == MG_QUOTA: self._init_model('catch') else: self._init_model('effort') self.computed_parameters = None self.parameter_panel.set_model(self.model) self.plot_panel.update_visibility() self.plot_panel.Layout() self.on_timer_model(None) def on_slide_change(self,event): '''Get the latest set of parameters if the sliders have been moved''' #Store the latest set of parameters # if event.GetEventObject() in self.parameter_panel.GetChildren(): self.parameters = self.parameter_panel.get_parameters() def model_data_updater(self,state): self.computed_complete=True self.model.state = state self.plot_panel.update_state(self.model.state) min_size = self.sizer.GetMinSize() self.SetMinSize(min_size) class MenuBar(wx.MenuBar): def __init__(self,parent_frame,sim_update_fx=None,parameter_type_fx=None,reset_model_fx=None): wx.MenuBar.__init__(self) self.sim_update_fx = sim_update_fx self.parameter_type_fx=parameter_type_fx self.reset_model_fx = reset_model_fx self.parent_frame = parent_frame self.scenario_menu = wx.Menu() self.reset_model = self.scenario_menu.Append(-1,'Reset Model') self.scenario_menu.Append(-1,' ').Enable(False) self.scenario_menu.AppendRadioItem(-1,'Rock Lobster Fishery') self.scenario_menu.Append(-1,' ').Enable(False) self.static_simulation = self.scenario_menu.AppendRadioItem(-1,SIM_STATIC) self.dynamic_simulation = self.scenario_menu.AppendRadioItem(-1,SIM_DYNAMIC) self.scenario_menu.Append(-1,' ').Enable(False) self.input_control = self.scenario_menu.AppendRadioItem(-1,MG_EFFORT) self.output_control = self.scenario_menu.AppendRadioItem(-1,MG_QUOTA) #Bring checks in line with initial simulation state if SIM_TYPE == SIM_STATIC: self.static_simulation.Check() else: self.dynamic_simulation.Check() if MG_TYPE == MG_QUOTA: self.output_control.Check() else: self.input_control.Check() self.parameter_menu = wx.Menu() self.parameter_items = [] self.help_menu = wx.Menu() self.about = self.help_menu.Append(-1,'About') self.license = self.help_menu.Append(-1,'License') self.Append(self.scenario_menu,'Model') self.Append(self.parameter_menu,'Parameters') self.Append(self.help_menu,'Help') parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.input_control) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.output_control) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.static_simulation) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.dynamic_simulation) parent_frame.Bind(wx.EVT_MENU, self.on_about,self.about) parent_frame.Bind(wx.EVT_MENU, self.on_license,self.license) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.reset_model) def set_parameter_types(self,types): for item in self.parameter_items: self.parameter_menu.Delete(item) for type in ["All"]+types: self.parameter_items.append(self.parameter_menu.AppendRadioItem(-1,type)) self.parent_frame.Bind(wx.EVT_MENU, self.on_parameter_selection, self.parameter_items[-1]) if type == 'Management Controls': self.parameter_items[-1].Check() self.on_parameter_selection(None) def on_reset_model(self,event): '''Reset the model''' self.reset_model_fx() def on_parameter_selection(self,event): '''Called when a parameter set is selected''' for item in self.parameter_items: if item.IsChecked(): self.parameter_type_fx(item.GetText()) def on_simulation_change(self,event): if self.input_control.IsChecked(): control_type = MG_EFFORT else: control_type = MG_QUOTA if self.static_simulation.IsChecked(): simulation_type = SIM_STATIC else: simulation_type= SIM_DYNAMIC self.sim_update_fx(simulation_type = simulation_type, control_type = control_type) event.Skip() def on_about(self,event): '''About handler, shows modal AboutBox''' dlg = AboutBox(self.parent_frame,title='About Fisheries Explorer',filename='about.html') dlg.ShowModal() dlg.Destroy() def on_license(self,event): '''License handler, shows modal AboutBox''' dlg = AboutBox(self.parent_frame,title='Fisheries Explorer License',filename='OSL3.0.htm') dlg.ShowModal() dlg.Destroy() class ParameterPanel(wx.Panel): '''A panel for parameter input''' def __init__(self,parent,model = [],sim_update_fx=None): wx.Panel.__init__(self,parent) self.type_shown = 'All' self.model = model self.parameters = model.get_parameters() self._base_layout() self.set_model(model) self.sim_update_fx = sim_update_fx def set_model(self,model): '''Set the parameters displayed in the panel (expects a Parameter object)''' self.parameters = model.get_parameters() self.model = model self.parameter_layout() self.show_parameter_set() def _base_layout(self): #Empty lists for storing gui objects (to get parameter values etc) self.label_parameters = {} self.label_param_values = {} self.slider_parameters = {} self.sizer = wx.FlexGridSizer(rows=1,cols=2) self.sizer.AddGrowableCol(1,1) self.SetSizer(self.sizer) self.set_panel = wx.Panel(self) self.set_sizer = wx.FlexGridSizer(rows=3,cols=1) self.set_panel.SetSizer(self.set_sizer) self.control_panel = wx.Panel(self) self.control_sizer = wx.FlexGridSizer(rows=len(self.parameters),cols=3) self.control_sizer.AddGrowableCol(1,1) self.control_panel.SetSizer(self.control_sizer) self.sizer.Add(self.set_panel,0) self.sizer.Add(self.control_panel,0,flag=wx.EXPAND) if False: #Drop down box for choosing parameter types self.set_sizer.Add(wx.StaticText(self.set_panel,label='Parameter Set:')) self.parameter_choice = wx.Choice(self.set_panel,1) self.set_sizer.Add(self.parameter_choice) #Set selection items items = self.model.get_parameter_types() items.insert(0,'ALL') self.parameter_choice.SetItems(items) self.parameter_choice.SetSelection(0) if False: self.static_toggle = wx.RadioBox(self.set_panel,1,"Simulation Type",choices=[SIM_STATIC,SIM_DYNAMIC]) self.management_toggle = wx.RadioBox(self.set_panel,1,"Management Type",choices=[MG_EFFORT,MG_QUOTA]) self.set_sizer.Add(self.static_toggle) self.set_sizer.Add(self.management_toggle) self.Bind(wx.EVT_CHOICE,self.on_selection_change) self.Bind(wx.EVT_RADIOBOX,self.on_simulation_change) def parameter_layout(self): #Delete all existing objects if hasattr(self,'control_sizer'): self.control_sizer.Clear(True) #Create the caption, value and slider for each parameter count = 0 for param in self.parameters: p = self.parameters[param] self.label_parameters[param]=wx.StaticText(self.control_panel,label=p['title']+':') current_value = round((p['value']-p['min'])/float(p['max']-p['min'])*1000) self.slider_parameters[param]= wx.Slider(self.control_panel, -1, current_value, 0, 1000, wx.DefaultPosition, style= wx.SL_HORIZONTAL) self.label_param_values[param]=wx.StaticText(self.control_panel,label='') self.label_parameters[param].SetToolTipString(p['description']) self.slider_parameters[param].SetToolTipString(p['description']) self.control_sizer.Add(self.label_parameters[param],0,flag=wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT) self.control_sizer.Add(self.slider_parameters[param],0,flag=wx.EXPAND) self.control_sizer.Add(self.label_param_values[param],0,flag=wx.ALIGN_LEFT) count += 1 self.on_slide_change(None) self.Bind(wx.EVT_SCROLL,self.on_slide_change) def on_simulation_change(self,event): self.sim_update_fx(simulation_type = self.static_toggle.GetStringSelection(), control_type = self.management_toggle.GetStringSelection()) def on_selection_change(self,event): '''Update parameter list when a different parameter set is selected''' type = self.parameter_choice.GetItems()[self.parameter_choice.GetSelection()] self.show_parameter_set(type) def show_parameter_set(self,type=None): '''Show parameters of type''' #If type is unspecified we show the same parameter set if type != None: self.type_shown = type type = self.type_shown #Show the selected parameters for param in self.parameters: selected =((type == 'ALL' or type == 'All' or self.parameters[param]['type'] == type) and (SIM_TYPE == SIM_DYNAMIC or self.parameters[param]['type'] != 'Management Controls')) if SIM_TYPE == SIM_STATIC and param == 'discount_rate': selected = False self.label_param_values[param].Show(selected) self.label_parameters[param].Show(selected) self.slider_parameters[param].Show(selected) self.Fit() self.GetParent().Layout() def on_slide_change(self,event): '''Slider change event updates value label''' param_values = self.get_parameters() for param in (param_values): scale_text = '' if self.parameters[param]['scale_text'] != '': scale_text = ' (' + self.parameters[param]['scale_text'] + ')' self.label_param_values[param].SetLabel(str(param_values[param]/self.parameters[param]['scale'])+ ' ' + self.parameters[param]['units'] + scale_text) self.Layout() #Propagate the event so that the frame can process it if event != None: event.Skip() def get_parameters(self): '''Get a dict of the current parameter values''' out = {} for param in self.parameters: p = self.parameters[param] out[param] = float(self.slider_parameters[param].GetValue())/1000.0*(p['max']-p['min'])+p['min'] return out def set_parameters(self,parameter_values): '''Update parameters from a dict''' out = {} for param in parameter_values.keys(): if self.parameters.has_key(param): v = parameter_values[param] p = self.parameters[param] self.slider_parameters[param].SetValue(int((v-p['min'])/(p['max']-p['min'])*1000)) self.on_slide_change(None) class PlotPanel(wx.Panel): line_colours = colourblind.rgbScaled line_styles = [[127,1], #solid [5,5], #dashed [20,20,2,20], #dash-dot [2,2,2,2] #dotted ] def __init__(self,parent): wx.Panel.__init__(self,parent) self.last_redraw_size = [] self.fig = Figure() self.fig.set_facecolor([1,1,1]) self.control_panel = wx.Panel(self) self.canvas_panel = wx.Panel(self) self.canvas = FigCanvas(self.canvas_panel,wx.ID_ANY,self.fig) self.sizer = wx.FlexGridSizer(rows=1,cols=2,hgap=5,vgap=5) self.sizer.Add(self.canvas_panel,flag=wx.EXPAND) self.sizer.Add(self.control_panel,flag=wx.ALIGN_CENTER|wx.ALL) self.sizer.AddGrowableCol(0,1) self.sizer.AddGrowableRow(0,1) self.SetSizer(self.sizer) self.control_sizer = wx.FlexGridSizer(hgap=5,vgap=5) self.control_panel.SetSizer(self.control_sizer) self.control_panel.Bind(wx.EVT_CHECKBOX,self.redraw) # self.canvas.SetAutoLayout(True) self.canvas_panel.SetMinSize([600,300]) self.state = None self.bounds = {} self.xbound = 0 self.SetBackgroundColour(wx.WHITE) self.canvas_panel.SetBackgroundColour(wx.WHITE) self.control_panel.SetBackgroundColour(wx.WHITE) self.canvas_panel.Bind(wx.EVT_SIZE, self.OnSize) self.Fit() def OnSize(self,event=None,size=None): if event == None and size == None: size = self.canvas_panel.GetClientSize() elif event != None and size == None: size = event.GetSize() #If the size has actually changed we redraw (several events may #be intercepted here per resize) if size != self.last_redraw_size: self.last_redraw_size = size self.fig.set_figwidth(size[0]/(1.0*self.fig.get_dpi())) self.fig.set_figheight(size[1]/(1.0*self.fig.get_dpi())) self.canvas.SetClientSize(size) self.redraw(None, redraw=True) if event != None: event.Skip() def _setup_control_panel(self): self._update_line_styles() #Remove existing widgets self.control_sizer.Clear(True) parameters = self.state.attribute_order self.control_sizer.SetRows(len(parameters)) self.control_sizer.SetCols(3) #Column Labels if False: self.control_sizer.SetRows(len(parameters)+1) column_labels = ['Plot','Parameter','Style'] for col in range(len(column_labels)): self.control_sizer.Add(wx.StaticText(self.control_panel,-1,column_labels[col])) self.check_boxes = {} self.param_text = {} self.param_bitmap = {} self.pens = {} self.colours = {} self.linedc = {} self.linebitmap = {} # self.check_boxes = {} linedc = wx.MemoryDC() for param in parameters: rgbcolour = self.unit_colour[self.state.get_attribute_units(param)] self.colours[param] = wx.Colour(rgbcolour[0]*255,rgbcolour[1]*255,rgbcolour[2]*255) style = self.parameter_style[param] #Add the check box self.check_boxes[param] = wx.CheckBox(self.control_panel,-1,'') self.control_sizer.Add(self.check_boxes[param]) #Add the description self.param_text[param] = wx.StaticText(self.control_panel,-1,self.state.get_attribute_title(param)) self.control_sizer.Add(self.param_text[param]) self.param_text[param].SetForegroundColour(self.colours[param]) self.param_text[param].Refresh() #Add the linestyle self.linebitmap[param] = wx.EmptyBitmap(40,20) linedc.SelectObject(self.linebitmap[param]) linedc.Clear() self.pens[param] = wx.Pen(colour = self.colours[param], width = 1,style = wx.USER_DASH) self.pens[param].SetDashes(style) linedc.SetPen(self.pens[param]) linedc.DrawLine(0,10,40,10) self.param_bitmap[param] = wx.StaticBitmap(self.control_panel,-1,self.linebitmap[param]) self.control_sizer.Add(self.param_bitmap[param]) #Enable the default plot parameters for param in self.state.default_plot: self.check_boxes[param].SetValue(True) def _colour_control(self): ''' updates the colours of the control elements ''' selected = self.get_selected_parameters() for param in self.state.attributes: if param in selected: self.param_text[param].Enable() self.param_bitmap[param].Enable() else: self.param_text[param].Disable() #self.param_bitmap[param].Disable() def _update_line_styles(self): ''' Update the colour and style associated with each unit and parameter ''' self.unit_colour = {} self.parameter_style = {} #For tracking the number of parameters per unit unit_count = {} #Determine colours for units for unit in self.state.unit_order: self.unit_colour[unit] = self.line_colours[len(self.unit_colour)] unit_count[unit] = 0 #Determine line styles for parameters for param in self.state.attribute_order: unit = self.state.get_attribute_units(param) print param, unit self.parameter_style[param] = self.line_styles[unit_count[unit]] unit_count[unit] += 1 def _select_parameters(self,parameters = [],redraw=True): '''Set the parameters to be plotted''' self.parameters = parameters if redraw: self.redraw_fromscratch() def update_visibility(self): if SIM_TYPE == SIM_STATIC: enabled = False else: enabled = True self.check_boxes['discounted_profit'].Show(enabled) self.param_text['discounted_profit'].Show(enabled) self.param_bitmap['discounted_profit'].Show(enabled) def update_state(self,state,redraw=True): '''Update the state that is being plotted''' self.state = copy.deepcopy(state) if not hasattr(self,'last_parameters'): self.last_parameters = {} print self.state['discounted_profit'] import numpy self.npv = numpy.nansum(self.state['discounted_profit']) # discount_rate = 0.05 # for index in range(len(self.state['revenue'])): # if self.state['revenue'][index] != None and ~numpy.isnan(self.state['revenue'][index]): # self.npv += (self.state['revenue'][index]-self.state['cost'][index])*(1-discount_rate)**index if redraw: #Update the parameter selection controls if necessary if state.attributes != self.last_parameters: self._setup_control_panel() self.last_parameters = state.attributes self.redraw() def _update_bounds(self): '''Update the figure bounds''' def sig_round(number): '''Ceil a number to a nice round figure for limits''' if number == 0: return 0 sig = number/(10**numpy.floor(numpy.log10(number*2))) if sig < 2: factor_multiple = 2.0 elif sig < 5: factor_multiple = 2.0 else: factor_multiple = 1.0 factor = 10**(numpy.floor(numpy.log10(number*factor_multiple)))/factor_multiple rounded = numpy.ceil(number/factor)*factor print number, rounded return rounded self.xbound = 0 self.bounds = {} for unit in self._get_units(): self.bounds[unit]=[float('inf'), -float('inf')] for param in self.get_selected_parameters(): unit = self.state.get_attribute_units(param) yv = numpy.asarray(self.state[param])/self.state.attributes[param]['scale'] self.bounds[unit][0] = min(self.bounds[unit][0], numpy.nanmin(yv)) self.bounds[unit][1] = max(self.bounds[unit][1], numpy.nanmax(yv)) self.bounds[unit][0] = sig_round(self.bounds[unit][0]) self.bounds[unit][1] = sig_round(self.bounds[unit][1]) if SIM_TYPE == SIM_DYNAMIC: self.xbound = max(self.xbound,len(self.state[param])-1) if SIM_TYPE == SIM_STATIC: if MG_TYPE == MG_QUOTA: self.xbound = numpy.nanmax(numpy.asarray(self.state['catch'])/self.state.attributes['catch']['scale']) else: self.xbound = numpy.nanmax(numpy.asarray(self.state['effort'])/self.state.attributes['effort']['scale']) self.xbound = sig_round(self.xbound) def get_selected_parameters(self): '''Return the parameters that have been selected for plotting''' out = [] for param in self.state.attribute_order: if self.check_boxes[param].GetValue(): out.append(param) return out def _get_units(self): ''' Returns a list of units that will be plotted ''' units = {} for param in self.get_selected_parameters(): units[self.state.get_attribute_units(param)]=1 return units.keys() def _setup_axes(self): ''' Redraw the figure from scratch required if the number of axes etc. have changed ''' #Clear the figure self.fig.clf() #Add the new axes self.axes = {} self.plot_data = {} self.axes_xscale = {} max_width = 0.87 width_increment = 0.07 bottom_space = .13 pos=[.05, bottom_space, max_width-width_increment*(len(self._get_units())-1), 1-bottom_space-0.05] #Create the axes, one for each unit for unit in self._get_units(): first_figure = len(self.axes)==0 colour = self.unit_colour[unit] self.axes[unit] = self.fig.add_axes(pos,frameon=True,label=unit) self.axes[unit].yaxis.tick_right() self.axes[unit].yaxis.set_label_position('right') self.axes[unit].set_ylabel(unit) self.axes_xscale[unit] = pos[2]/(max_width-width_increment*(len(self._get_units())-1)) if not first_figure: self.axes[unit].patch.set_alpha(0) else: self.firstaxes = self.axes[unit] self.axes[unit].set_xlabel('Years') self._modify_axes(self.axes[unit],colour,not first_figure) pos[2] += width_increment #Create the plot lines, one for each parameter for param in self.get_selected_parameters(): unit = self.state.get_attribute_units(param) colour = self.unit_colour[unit] style = self.parameter_style[param] self.plot_data[param] = self.axes[unit].plot([0,0],[0,0],linewidth=2)[0] self.plot_data[param].set_color(colour) self.plot_data[param].set_dashes(style) #Text for npv self.npvtext = self.fig.text(.1,bottom_space,'NPV') def redraw(self,event=None,redraw=False): ''' Update the plots using data in the current state ''' if self.state == None: return if not hasattr(self,'last_selected_parameters'): self.last_selected_parameters = {} #If the selected parameters have changed we need new axes if self.last_selected_parameters != self.get_selected_parameters() or redraw: self.last_selected_parameters = self.get_selected_parameters() self._colour_control() self._setup_axes() self._update_bounds() #Update axes bounds for unit in self._get_units(): bounds = self.bounds[unit] self.axes[unit].set_ybound(lower = 0,upper = bounds[1]) self.axes[unit].set_xbound(lower = 0,upper=self.xbound*self.axes_xscale[unit]) #Update plot data for param in self.get_selected_parameters(): data = self.state[param] if SIM_TYPE == SIM_DYNAMIC: self.plot_data[param].set_xdata(range(len(data))) else: if MG_TYPE == MG_QUOTA: self.plot_data[param].set_xdata(numpy.asarray(self.state['catch'])/self.state.attributes['catch']['scale']) else: self.plot_data[param].set_xdata(numpy.asarray(self.state['effort'])/self.state.attributes['effort']['scale']) self.plot_data[param].set_ydata(numpy.asarray(data)/self.state.attributes[param]['scale']) if SIM_TYPE == SIM_DYNAMIC: self.firstaxes.set_xlabel('Years') else: if MG_TYPE == MG_QUOTA: xunit = 'catch' else: xunit = 'effort' self.firstaxes.set_xlabel('Management Control: ' + self.state.attributes[xunit]['title'] + ' (' + self.state.attributes[xunit]['units'] + ')') if SIM_TYPE == SIM_DYNAMIC and ~numpy.isnan(self.npv): self.npvtext.set_text('NPV: $' + str(int(round(self.npv/self.state.attributes['revenue']['scale']))) + ' million') else: self.npvtext.set_text('') self.canvas.draw() @staticmethod def _modify_axes(axes,color,remove = False): ''' Set the colour of the y axis to color and optionally remove the remaining borders of the graph ''' def modify_all(object,color=None,remove=False): for child in object.get_children(): modify_all(child,color,remove) if remove and hasattr(object,'set_visible'): object.set_visible(not remove) if color != None and hasattr(object,'set_color'): object.set_color(color) for child in axes.get_children(): if isinstance(child, matplotlib.spines.Spine): if child.spine_type == 'right': modify_all(child,color=color) elif remove == True: modify_all(child,remove=True) modify_all(axes.yaxis,color=color) if remove: modify_all(axes.xaxis,remove=True) class AboutBox(wx.Dialog): '''An about dialog box, which displays a html file''' replacements = {'_VERSION_': VERSIONSTRING} def __init__(self,parent,title,filename): ''' parent: parent window title: dialog box title filename: the html file to show ''' wx.Dialog.__init__(self,parent,-1,title,size=(500,550)) #Read the html source file fid = open(filename,'r') self.abouthtml = fid.read() fid.close() #Replace tokens for key in self.replacements.keys(): self.abouthtml = self.abouthtml.replace(key,self.replacements[key]) self.html = wx.html.HtmlWindow(self) self.html.SetPage(self.abouthtml) self.ok_button = wx.Button(self,wx.ID_OK,"Ok") self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.html,1,wx.EXPAND|wx.ALL,5) self.sizer.Add(self.ok_button,0,wx.ALIGN_CENTER|wx.ALL,5) self.SetSizer(self.sizer) self.Layout() x=1366 y=768 class App(wx.App): def OnInit(self): self.frame = Frame(x,y) self.SetTopWindow(self.frame) self.frame.Show() self.frame.Layout() return True if __name__ == '__main__': app = App(redirect=False) # app = App(redirect=False) app.MainLoop()
Python
#By running "python setup.py py2exe" this script generates a windows stand-alone #distribution of the Fisheries Explorer #Copyright 2010, University of Tasmania, Australian Seafood CRC #This program is released under the Open Software License ("OSL") v. 3.0. See OSL3.0.htm for details. from distutils.core import setup import py2exe import matplotlib import shutil # Remove the build folder shutil.rmtree("build", ignore_errors=True) # do the same for dist folder shutil.rmtree("dist", ignore_errors=True) data_files = matplotlib.get_py2exe_datafiles() data_files += ['OSL3.0.htm','about.html',('images',["images/fishnet.ico","images/seafoodcrc.png",'images/fishnet.png','images/about.png','images/fish.png'])] dll_excludes = ['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll', 'tk84.dll', 'MSVCP90.dll', 'mswsock.dll', 'powrprof.dll'] excludes = ['_gtkagg' ] setup( windows = [ { "script": "fisheries_gui.py", "icon_resources": [(1, "images\\fishnet.ico")], #"other_resources": [(24,1,manifest)] } ], options = {"py2exe": { 'excludes': excludes, 'includes': ['matplotlib.backends.backend_tkagg','unittest','inspect'], "dll_excludes": dll_excludes, # "compressed": 2, # "optimize": 2, # "bundle_files": 2, # "xref": False, # "skip_archive": False, # "ascii": False, # "custom_boot_script": '' } }, data_files=data_files )
Python
#!/usr/bin/env python """ Fisheries Economics Masterclass GUI Klaas Hartmann 2010 Copyright 2010, University of Tasmania, Australian Seafood CRC This program is released under the Open Software License ("OSL") v. 3.0. See OSL3.0.htm for details. """ import wx import wx.html import fisheries_model import colourblind import matplotlib #matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import \ FigureCanvasWxAgg as FigCanvas import numpy import copy import os import sys #String constants for some menus etc MG_QUOTA='Output Controlled' MG_EFFORT='Input Controlled' SIM_DYNAMIC='Dynamic' SIM_STATIC='Static (Equilibrium)' #Version history: #1.00 Initial release from Hobart Class 1 #1.01 Made fishery crash instantaneous. #1.02 Initial version on Google Code #1.03 Included licencing information VERSIONSTRING = '1.03' #Globals that specify the current simulation and management type #(to be subsumed at a later stage...) SIM_TYPE='' MG_TYPE='' class Frame(wx.Frame): '''The main (only?) GUI Frame''' def __init__(self,width,height): wx.Frame.__init__(self, None, size=wx.Size(width,height), title = 'Fisheries Explorer') #self.SetSize(wx.Size(width,height)) #Set the starting simulation and management types global SIM_TYPE global MG_TYPE MG_TYPE = MG_QUOTA SIM_TYPE = SIM_STATIC self.Maximize() #Initialise model components self._init_model() #Initialise model/graph update system self._init_update() #Initialise GUI components self._init_gui() def _init_update(self): '''Initialise model/graph update system''' #Will contain current parameters self.parameters= {} #Will contain last parameters for which the model run was completed self.computed_parameters = {} #Will contain last parameters for which a graph was produced self.plotted_parameters = {} #Whether current computation has been completed self.computed_complete = True #Timer for model reruns self.timer_model = wx.Timer(self) self.timer_model.Start(250) wx.EVT_TIMER(self,self.timer_model.GetId(),self.on_timer_model) #Hack to call layout after init self.timer_init_hack = wx.Timer(self) self.timer_init_hack.Start(250) wx.EVT_TIMER(self,self.timer_init_hack.GetId(),self.on_timer_init_hack) #The model execution thread self.model_thread = fisheries_model.MultiThreadModelRun(self.model_data_updater) def _init_model(self,type='catch'): '''Initialise model''' self.model = fisheries_model.lobsterModel(control_type = type) def _init_gui(self): '''Initialise GUI components''' #Setup sizers (in hierarchical order) self.sizer = wx.FlexGridSizer(rows=2,cols=1) #Create wx objects self.parameter_panel = ParameterPanel(self,self.model,sim_update_fx=self.on_simulation_change) self.plot_panel = PlotPanel(self) #Set up main sizer self.sizer.Add(self.parameter_panel,0,wx.EXPAND) self.sizer.Add(self.plot_panel,0,wx.EXPAND) self.sizer.AddGrowableCol(0,1) self.sizer.AddGrowableRow(1,1) #Set sizers self.SetSizer(self.sizer) #Set menu self.menubar = MenuBar(self,sim_update_fx=self.on_simulation_change,parameter_type_fx=self.parameter_panel.show_parameter_set,reset_model_fx=self.on_simulation_change) self.SetMenuBar(self.menubar) self.menubar.set_parameter_types(self.model.get_parameter_types()) #Bind events self.Bind(wx.EVT_SCROLL,self.on_slide_change) #self.Bind(wx.EVT_CLOSE, self.onCloseWindow) self.on_slide_change(None) self.on_timer_model(None) #Prevent the frame getting resized too small min_size = self.sizer.GetMinSize() self.SetMinSize(min_size) #Set the icon self.icon = wx.Icon(os.path.join('images','fishnet.ico'),wx.BITMAP_TYPE_ICO) self.SetIcon(self.icon) #It still doesn't close cleanly for some unknown reason.. block = False def onCloseWindow(self,event): self.timer_model.Stop() self.timer_model.Destroy() self.icon.Destroy() event.Skip() def on_timer_model(self,event): '''Rerun the model if parameters have changed''' #If parameters have changed we need to recalculate the model if self.parameters != self.computed_parameters: self.computed_complete=False self.model.set_parameters(self.parameter_panel.get_parameters()) self.model.reset() #Run the appropriate simulation if SIM_TYPE == SIM_STATIC: if MG_TYPE == MG_QUOTA: max= self.parameters['K']*self.parameters['r']/4*1.01 self.model_thread.run(self.model,20,dynamic=False,independent_variable='catch',independent_maximum=max) else: self.model_thread.run(self.model,20,dynamic=False,independent_variable='effort',independent_maximum=6e6) else: self.model_thread.run(self.model,20) self.computed_parameters = self.parameters init_hack_count = 0 def on_timer_init_hack(self,event): '''A hack to layout the plot panel after load. For some reason the legend is not displayed correctly.''' if self.init_hack_count > 0: self.timer_init_hack.Stop() self.init_hack_count += 1 self.plot_panel.update_visibility() self.plot_panel.OnSize() self.plot_panel.Layout() def on_simulation_change(self,simulation_type,control_type): '''Called if the simulation type (static/dynamic, quota/effort controlled) changes''' global SIM_TYPE global MG_TYPE SIM_TYPE = simulation_type MG_TYPE = control_type #Initialise the model with appropriate control type if MG_TYPE == MG_QUOTA: self._init_model('catch') else: self._init_model('effort') self.computed_parameters = None self.parameter_panel.set_model(self.model) self.plot_panel.update_visibility() self.plot_panel.Layout() self.on_timer_model(None) def on_slide_change(self,event): '''Get the latest set of parameters if the sliders have been moved''' #Store the latest set of parameters # if event.GetEventObject() in self.parameter_panel.GetChildren(): self.parameters = self.parameter_panel.get_parameters() def model_data_updater(self,state): self.computed_complete=True self.model.state = state self.plot_panel.update_state(self.model.state) min_size = self.sizer.GetMinSize() self.SetMinSize(min_size) class MenuBar(wx.MenuBar): def __init__(self,parent_frame,sim_update_fx=None,parameter_type_fx=None,reset_model_fx=None): wx.MenuBar.__init__(self) self.sim_update_fx = sim_update_fx self.parameter_type_fx=parameter_type_fx self.reset_model_fx = reset_model_fx self.parent_frame = parent_frame self.scenario_menu = wx.Menu() self.reset_model = self.scenario_menu.Append(-1,'Reset Model') self.scenario_menu.Append(-1,' ').Enable(False) self.scenario_menu.AppendRadioItem(-1,'Rock Lobster Fishery') self.scenario_menu.Append(-1,' ').Enable(False) self.static_simulation = self.scenario_menu.AppendRadioItem(-1,SIM_STATIC) self.dynamic_simulation = self.scenario_menu.AppendRadioItem(-1,SIM_DYNAMIC) self.scenario_menu.Append(-1,' ').Enable(False) self.input_control = self.scenario_menu.AppendRadioItem(-1,MG_EFFORT) self.output_control = self.scenario_menu.AppendRadioItem(-1,MG_QUOTA) #Bring checks in line with initial simulation state if SIM_TYPE == SIM_STATIC: self.static_simulation.Check() else: self.dynamic_simulation.Check() if MG_TYPE == MG_QUOTA: self.output_control.Check() else: self.input_control.Check() self.parameter_menu = wx.Menu() self.parameter_items = [] self.help_menu = wx.Menu() self.about = self.help_menu.Append(-1,'About') self.license = self.help_menu.Append(-1,'License') self.Append(self.scenario_menu,'Model') self.Append(self.parameter_menu,'Parameters') self.Append(self.help_menu,'Help') parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.input_control) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.output_control) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.static_simulation) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.dynamic_simulation) parent_frame.Bind(wx.EVT_MENU, self.on_about,self.about) parent_frame.Bind(wx.EVT_MENU, self.on_license,self.license) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.reset_model) def set_parameter_types(self,types): for item in self.parameter_items: self.parameter_menu.Delete(item) for type in ["All"]+types: self.parameter_items.append(self.parameter_menu.AppendRadioItem(-1,type)) self.parent_frame.Bind(wx.EVT_MENU, self.on_parameter_selection, self.parameter_items[-1]) if type == 'Management Controls': self.parameter_items[-1].Check() self.on_parameter_selection(None) def on_reset_model(self,event): '''Reset the model''' self.reset_model_fx() def on_parameter_selection(self,event): '''Called when a parameter set is selected''' for item in self.parameter_items: if item.IsChecked(): self.parameter_type_fx(item.GetText()) def on_simulation_change(self,event): if self.input_control.IsChecked(): control_type = MG_EFFORT else: control_type = MG_QUOTA if self.static_simulation.IsChecked(): simulation_type = SIM_STATIC else: simulation_type= SIM_DYNAMIC self.sim_update_fx(simulation_type = simulation_type, control_type = control_type) event.Skip() def on_about(self,event): '''About handler, shows modal AboutBox''' dlg = AboutBox(self.parent_frame,title='About Fisheries Explorer',filename='about.html') dlg.ShowModal() dlg.Destroy() def on_license(self,event): '''License handler, shows modal AboutBox''' dlg = AboutBox(self.parent_frame,title='Fisheries Explorer License',filename='OSL3.0.htm') dlg.ShowModal() dlg.Destroy() class ParameterPanel(wx.Panel): '''A panel for parameter input''' def __init__(self,parent,model = [],sim_update_fx=None): wx.Panel.__init__(self,parent) self.type_shown = 'All' self.model = model self.parameters = model.get_parameters() self._base_layout() self.set_model(model) self.sim_update_fx = sim_update_fx def set_model(self,model): '''Set the parameters displayed in the panel (expects a Parameter object)''' self.parameters = model.get_parameters() self.model = model self.parameter_layout() self.show_parameter_set() def _base_layout(self): #Empty lists for storing gui objects (to get parameter values etc) self.label_parameters = {} self.label_param_values = {} self.slider_parameters = {} self.sizer = wx.FlexGridSizer(rows=1,cols=2) self.sizer.AddGrowableCol(1,1) self.SetSizer(self.sizer) self.set_panel = wx.Panel(self) self.set_sizer = wx.FlexGridSizer(rows=3,cols=1) self.set_panel.SetSizer(self.set_sizer) self.control_panel = wx.Panel(self) self.control_sizer = wx.FlexGridSizer(rows=len(self.parameters),cols=3) self.control_sizer.AddGrowableCol(1,1) self.control_panel.SetSizer(self.control_sizer) self.sizer.Add(self.set_panel,0) self.sizer.Add(self.control_panel,0,flag=wx.EXPAND) if False: #Drop down box for choosing parameter types self.set_sizer.Add(wx.StaticText(self.set_panel,label='Parameter Set:')) self.parameter_choice = wx.Choice(self.set_panel,1) self.set_sizer.Add(self.parameter_choice) #Set selection items items = self.model.get_parameter_types() items.insert(0,'ALL') self.parameter_choice.SetItems(items) self.parameter_choice.SetSelection(0) if False: self.static_toggle = wx.RadioBox(self.set_panel,1,"Simulation Type",choices=[SIM_STATIC,SIM_DYNAMIC]) self.management_toggle = wx.RadioBox(self.set_panel,1,"Management Type",choices=[MG_EFFORT,MG_QUOTA]) self.set_sizer.Add(self.static_toggle) self.set_sizer.Add(self.management_toggle) self.Bind(wx.EVT_CHOICE,self.on_selection_change) self.Bind(wx.EVT_RADIOBOX,self.on_simulation_change) def parameter_layout(self): #Delete all existing objects if hasattr(self,'control_sizer'): self.control_sizer.Clear(True) #Create the caption, value and slider for each parameter count = 0 for param in self.parameters: p = self.parameters[param] self.label_parameters[param]=wx.StaticText(self.control_panel,label=p['title']+':') current_value = round((p['value']-p['min'])/float(p['max']-p['min'])*1000) self.slider_parameters[param]= wx.Slider(self.control_panel, -1, current_value, 0, 1000, wx.DefaultPosition, style= wx.SL_HORIZONTAL) self.label_param_values[param]=wx.StaticText(self.control_panel,label='') self.label_parameters[param].SetToolTipString(p['description']) self.slider_parameters[param].SetToolTipString(p['description']) self.control_sizer.Add(self.label_parameters[param],0,flag=wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT) self.control_sizer.Add(self.slider_parameters[param],0,flag=wx.EXPAND) self.control_sizer.Add(self.label_param_values[param],0,flag=wx.ALIGN_LEFT) count += 1 self.on_slide_change(None) self.Bind(wx.EVT_SCROLL,self.on_slide_change) def on_simulation_change(self,event): self.sim_update_fx(simulation_type = self.static_toggle.GetStringSelection(), control_type = self.management_toggle.GetStringSelection()) def on_selection_change(self,event): '''Update parameter list when a different parameter set is selected''' type = self.parameter_choice.GetItems()[self.parameter_choice.GetSelection()] self.show_parameter_set(type) def show_parameter_set(self,type=None): '''Show parameters of type''' #If type is unspecified we show the same parameter set if type != None: self.type_shown = type type = self.type_shown #Show the selected parameters for param in self.parameters: selected =((type == 'ALL' or type == 'All' or self.parameters[param]['type'] == type) and (SIM_TYPE == SIM_DYNAMIC or self.parameters[param]['type'] != 'Management Controls')) if SIM_TYPE == SIM_STATIC and param == 'discount_rate': selected = False self.label_param_values[param].Show(selected) self.label_parameters[param].Show(selected) self.slider_parameters[param].Show(selected) self.Fit() self.GetParent().Layout() def on_slide_change(self,event): '''Slider change event updates value label''' param_values = self.get_parameters() for param in (param_values): scale_text = '' if self.parameters[param]['scale_text'] != '': scale_text = ' (' + self.parameters[param]['scale_text'] + ')' self.label_param_values[param].SetLabel(str(param_values[param]/self.parameters[param]['scale'])+ ' ' + self.parameters[param]['units'] + scale_text) self.Layout() #Propagate the event so that the frame can process it if event != None: event.Skip() def get_parameters(self): '''Get a dict of the current parameter values''' out = {} for param in self.parameters: p = self.parameters[param] out[param] = float(self.slider_parameters[param].GetValue())/1000.0*(p['max']-p['min'])+p['min'] return out def set_parameters(self,parameter_values): '''Update parameters from a dict''' out = {} for param in parameter_values.keys(): if self.parameters.has_key(param): v = parameter_values[param] p = self.parameters[param] self.slider_parameters[param].SetValue(int((v-p['min'])/(p['max']-p['min'])*1000)) self.on_slide_change(None) class PlotPanel(wx.Panel): line_colours = colourblind.rgbScaled line_styles = [[127,1], #solid [5,5], #dashed [20,20,2,20], #dash-dot [2,2,2,2] #dotted ] def __init__(self,parent): wx.Panel.__init__(self,parent) self.last_redraw_size = [] self.fig = Figure() self.fig.set_facecolor([1,1,1]) self.control_panel = wx.Panel(self) self.canvas_panel = wx.Panel(self) self.canvas = FigCanvas(self.canvas_panel,wx.ID_ANY,self.fig) self.sizer = wx.FlexGridSizer(rows=1,cols=2,hgap=5,vgap=5) self.sizer.Add(self.canvas_panel,flag=wx.EXPAND) self.sizer.Add(self.control_panel,flag=wx.ALIGN_CENTER|wx.ALL) self.sizer.AddGrowableCol(0,1) self.sizer.AddGrowableRow(0,1) self.SetSizer(self.sizer) self.control_sizer = wx.FlexGridSizer(hgap=5,vgap=5) self.control_panel.SetSizer(self.control_sizer) self.control_panel.Bind(wx.EVT_CHECKBOX,self.redraw) # self.canvas.SetAutoLayout(True) self.canvas_panel.SetMinSize([600,300]) self.state = None self.bounds = {} self.xbound = 0 self.SetBackgroundColour(wx.WHITE) self.canvas_panel.SetBackgroundColour(wx.WHITE) self.control_panel.SetBackgroundColour(wx.WHITE) self.canvas_panel.Bind(wx.EVT_SIZE, self.OnSize) self.Fit() def OnSize(self,event=None,size=None): if event == None and size == None: size = self.canvas_panel.GetClientSize() elif event != None and size == None: size = event.GetSize() #If the size has actually changed we redraw (several events may #be intercepted here per resize) if size != self.last_redraw_size: self.last_redraw_size = size self.fig.set_figwidth(size[0]/(1.0*self.fig.get_dpi())) self.fig.set_figheight(size[1]/(1.0*self.fig.get_dpi())) self.canvas.SetClientSize(size) self.redraw(None, redraw=True) if event != None: event.Skip() def _setup_control_panel(self): self._update_line_styles() #Remove existing widgets self.control_sizer.Clear(True) parameters = self.state.attribute_order self.control_sizer.SetRows(len(parameters)) self.control_sizer.SetCols(3) #Column Labels if False: self.control_sizer.SetRows(len(parameters)+1) column_labels = ['Plot','Parameter','Style'] for col in range(len(column_labels)): self.control_sizer.Add(wx.StaticText(self.control_panel,-1,column_labels[col])) self.check_boxes = {} self.param_text = {} self.param_bitmap = {} self.pens = {} self.colours = {} self.linedc = {} self.linebitmap = {} # self.check_boxes = {} linedc = wx.MemoryDC() for param in parameters: rgbcolour = self.unit_colour[self.state.get_attribute_units(param)] self.colours[param] = wx.Colour(rgbcolour[0]*255,rgbcolour[1]*255,rgbcolour[2]*255) style = self.parameter_style[param] #Add the check box self.check_boxes[param] = wx.CheckBox(self.control_panel,-1,'') self.control_sizer.Add(self.check_boxes[param]) #Add the description self.param_text[param] = wx.StaticText(self.control_panel,-1,self.state.get_attribute_title(param)) self.control_sizer.Add(self.param_text[param]) self.param_text[param].SetForegroundColour(self.colours[param]) self.param_text[param].Refresh() #Add the linestyle self.linebitmap[param] = wx.EmptyBitmap(40,20) linedc.SelectObject(self.linebitmap[param]) linedc.Clear() self.pens[param] = wx.Pen(colour = self.colours[param], width = 1,style = wx.USER_DASH) self.pens[param].SetDashes(style) linedc.SetPen(self.pens[param]) linedc.DrawLine(0,10,40,10) self.param_bitmap[param] = wx.StaticBitmap(self.control_panel,-1,self.linebitmap[param]) self.control_sizer.Add(self.param_bitmap[param]) #Enable the default plot parameters for param in self.state.default_plot: self.check_boxes[param].SetValue(True) def _colour_control(self): ''' updates the colours of the control elements ''' selected = self.get_selected_parameters() for param in self.state.attributes: if param in selected: self.param_text[param].Enable() self.param_bitmap[param].Enable() else: self.param_text[param].Disable() #self.param_bitmap[param].Disable() def _update_line_styles(self): ''' Update the colour and style associated with each unit and parameter ''' self.unit_colour = {} self.parameter_style = {} #For tracking the number of parameters per unit unit_count = {} #Determine colours for units for unit in self.state.unit_order: self.unit_colour[unit] = self.line_colours[len(self.unit_colour)] unit_count[unit] = 0 #Determine line styles for parameters for param in self.state.attribute_order: unit = self.state.get_attribute_units(param) print param, unit self.parameter_style[param] = self.line_styles[unit_count[unit]] unit_count[unit] += 1 def _select_parameters(self,parameters = [],redraw=True): '''Set the parameters to be plotted''' self.parameters = parameters if redraw: self.redraw_fromscratch() def update_visibility(self): if SIM_TYPE == SIM_STATIC: enabled = False else: enabled = True self.check_boxes['discounted_profit'].Show(enabled) self.param_text['discounted_profit'].Show(enabled) self.param_bitmap['discounted_profit'].Show(enabled) def update_state(self,state,redraw=True): '''Update the state that is being plotted''' self.state = copy.deepcopy(state) if not hasattr(self,'last_parameters'): self.last_parameters = {} print self.state['discounted_profit'] import numpy self.npv = numpy.nansum(self.state['discounted_profit']) # discount_rate = 0.05 # for index in range(len(self.state['revenue'])): # if self.state['revenue'][index] != None and ~numpy.isnan(self.state['revenue'][index]): # self.npv += (self.state['revenue'][index]-self.state['cost'][index])*(1-discount_rate)**index if redraw: #Update the parameter selection controls if necessary if state.attributes != self.last_parameters: self._setup_control_panel() self.last_parameters = state.attributes self.redraw() def _update_bounds(self): '''Update the figure bounds''' def sig_round(number): '''Ceil a number to a nice round figure for limits''' if number == 0: return 0 sig = number/(10**numpy.floor(numpy.log10(number*2))) if sig < 2: factor_multiple = 2.0 elif sig < 5: factor_multiple = 2.0 else: factor_multiple = 1.0 factor = 10**(numpy.floor(numpy.log10(number*factor_multiple)))/factor_multiple rounded = numpy.ceil(number/factor)*factor print number, rounded return rounded self.xbound = 0 self.bounds = {} for unit in self._get_units(): self.bounds[unit]=[float('inf'), -float('inf')] for param in self.get_selected_parameters(): unit = self.state.get_attribute_units(param) yv = numpy.asarray(self.state[param])/self.state.attributes[param]['scale'] self.bounds[unit][0] = min(self.bounds[unit][0], numpy.nanmin(yv)) self.bounds[unit][1] = max(self.bounds[unit][1], numpy.nanmax(yv)) self.bounds[unit][0] = sig_round(self.bounds[unit][0]) self.bounds[unit][1] = sig_round(self.bounds[unit][1]) if SIM_TYPE == SIM_DYNAMIC: self.xbound = max(self.xbound,len(self.state[param])-1) if SIM_TYPE == SIM_STATIC: if MG_TYPE == MG_QUOTA: self.xbound = numpy.nanmax(numpy.asarray(self.state['catch'])/self.state.attributes['catch']['scale']) else: self.xbound = numpy.nanmax(numpy.asarray(self.state['effort'])/self.state.attributes['effort']['scale']) self.xbound = sig_round(self.xbound) def get_selected_parameters(self): '''Return the parameters that have been selected for plotting''' out = [] for param in self.state.attribute_order: if self.check_boxes[param].GetValue(): out.append(param) return out def _get_units(self): ''' Returns a list of units that will be plotted ''' units = {} for param in self.get_selected_parameters(): units[self.state.get_attribute_units(param)]=1 return units.keys() def _setup_axes(self): ''' Redraw the figure from scratch required if the number of axes etc. have changed ''' #Clear the figure self.fig.clf() #Add the new axes self.axes = {} self.plot_data = {} self.axes_xscale = {} max_width = 0.87 width_increment = 0.07 bottom_space = .13 pos=[.05, bottom_space, max_width-width_increment*(len(self._get_units())-1), 1-bottom_space-0.05] #Create the axes, one for each unit for unit in self._get_units(): first_figure = len(self.axes)==0 colour = self.unit_colour[unit] self.axes[unit] = self.fig.add_axes(pos,frameon=True,label=unit) self.axes[unit].yaxis.tick_right() self.axes[unit].yaxis.set_label_position('right') self.axes[unit].set_ylabel(unit) self.axes_xscale[unit] = pos[2]/(max_width-width_increment*(len(self._get_units())-1)) if not first_figure: self.axes[unit].patch.set_alpha(0) else: self.firstaxes = self.axes[unit] self.axes[unit].set_xlabel('Years') self._modify_axes(self.axes[unit],colour,not first_figure) pos[2] += width_increment #Create the plot lines, one for each parameter for param in self.get_selected_parameters(): unit = self.state.get_attribute_units(param) colour = self.unit_colour[unit] style = self.parameter_style[param] self.plot_data[param] = self.axes[unit].plot([0,0],[0,0],linewidth=2)[0] self.plot_data[param].set_color(colour) self.plot_data[param].set_dashes(style) #Text for npv self.npvtext = self.fig.text(.1,bottom_space,'NPV') def redraw(self,event=None,redraw=False): ''' Update the plots using data in the current state ''' if self.state == None: return if not hasattr(self,'last_selected_parameters'): self.last_selected_parameters = {} #If the selected parameters have changed we need new axes if self.last_selected_parameters != self.get_selected_parameters() or redraw: self.last_selected_parameters = self.get_selected_parameters() self._colour_control() self._setup_axes() self._update_bounds() #Update axes bounds for unit in self._get_units(): bounds = self.bounds[unit] self.axes[unit].set_ybound(lower = 0,upper = bounds[1]) self.axes[unit].set_xbound(lower = 0,upper=self.xbound*self.axes_xscale[unit]) #Update plot data for param in self.get_selected_parameters(): data = self.state[param] if SIM_TYPE == SIM_DYNAMIC: self.plot_data[param].set_xdata(range(len(data))) else: if MG_TYPE == MG_QUOTA: self.plot_data[param].set_xdata(numpy.asarray(self.state['catch'])/self.state.attributes['catch']['scale']) else: self.plot_data[param].set_xdata(numpy.asarray(self.state['effort'])/self.state.attributes['effort']['scale']) self.plot_data[param].set_ydata(numpy.asarray(data)/self.state.attributes[param]['scale']) if SIM_TYPE == SIM_DYNAMIC: self.firstaxes.set_xlabel('Years') else: if MG_TYPE == MG_QUOTA: xunit = 'catch' else: xunit = 'effort' self.firstaxes.set_xlabel('Management Control: ' + self.state.attributes[xunit]['title'] + ' (' + self.state.attributes[xunit]['units'] + ')') if SIM_TYPE == SIM_DYNAMIC and ~numpy.isnan(self.npv): self.npvtext.set_text('NPV: $' + str(int(round(self.npv/self.state.attributes['revenue']['scale']))) + ' million') else: self.npvtext.set_text('') self.canvas.draw() @staticmethod def _modify_axes(axes,color,remove = False): ''' Set the colour of the y axis to color and optionally remove the remaining borders of the graph ''' def modify_all(object,color=None,remove=False): for child in object.get_children(): modify_all(child,color,remove) if remove and hasattr(object,'set_visible'): object.set_visible(not remove) if color != None and hasattr(object,'set_color'): object.set_color(color) for child in axes.get_children(): if isinstance(child, matplotlib.spines.Spine): if child.spine_type == 'right': modify_all(child,color=color) elif remove == True: modify_all(child,remove=True) modify_all(axes.yaxis,color=color) if remove: modify_all(axes.xaxis,remove=True) class AboutBox(wx.Dialog): '''An about dialog box, which displays a html file''' replacements = {'_VERSION_': VERSIONSTRING} def __init__(self,parent,title,filename): ''' parent: parent window title: dialog box title filename: the html file to show ''' wx.Dialog.__init__(self,parent,-1,title,size=(500,550)) #Read the html source file fid = open(filename,'r') self.abouthtml = fid.read() fid.close() #Replace tokens for key in self.replacements.keys(): self.abouthtml = self.abouthtml.replace(key,self.replacements[key]) self.html = wx.html.HtmlWindow(self) self.html.SetPage(self.abouthtml) self.ok_button = wx.Button(self,wx.ID_OK,"Ok") self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.html,1,wx.EXPAND|wx.ALL,5) self.sizer.Add(self.ok_button,0,wx.ALIGN_CENTER|wx.ALL,5) self.SetSizer(self.sizer) self.Layout() x=1366 y=768 class App(wx.App): def OnInit(self): self.frame = Frame(x,y) self.SetTopWindow(self.frame) self.frame.Show() self.frame.Layout() return True if __name__ == '__main__': app = App(redirect=False) # app = App(redirect=False) app.MainLoop()
Python
#!/usr/bin/env python ''' Fisheries Economics Masterclass model Copyright 2010, University of Tasmania, Australian Seafood CRC This program is released under the Open Software License ("OSL") v. 3.0. See OSL3.0.htm for details. ''' import threading import wx from pylab import * import copy class Parameter(dict): """ Model parameter class A simple dict with some default values """ def __init__(self,value=0,min=0,max=1,units='',title='',description='',type='Miscellaneous',scale=1,scale_text=''): """Initialise the parameter""" self['value'] = value self['min'] = min self['max'] = max self['units'] = units self['title'] = title self['description'] = description self['type'] = type self['scale'] = scale self['scale_text']=scale_text class Component: """ Model component class All model classes should inherit this """ def get_parameters(self): """ Returns the parameters required by this component The format is a dictionary, keys are parameter name, value is a list of minimum value, maximum value, default value, """ return {} def execute(self,state,parameters): """Executes this component and returns the modified state""" return state class PDLogistic(Component): """Population Dynamics Logistic growth component""" def __init__(self): self.r = Parameter(title='Population growth rate', description='The maximum growth rate of the population', type='Population dynamics') self.K = Parameter(title='Maximum population size', description='The size of a unfished (virgin) population', type='Population dynamics') def get_parameters(self): return {'r': self.r,'K': self.K} #Execute a logistic step def execute(self,state,parameters,equilibrium=False): if equilibrium: r = parameters['r'] K = parameters['K'] if parameters.has_key('catch'): C = parameters['catch'] # [r-1 + (1-2r+r2+4Cr/K)^.5]/(2r/K) term = (r)**2-4*C*r/K #term = (1-4*parameters['catch']/parameters['r']/parameters['K']) if term < 0: state['biomass'][-1] = 0 else: #state['biomass'][-1] = parameters['K']/2*(1+term**0.5)#+parameters['catch'] #Catch is added back on as the catch step removes it state['biomass'][-1] = (r+term**.5)/(2*r/K) state['biomass'][-1] += parameters['catch'] #Catch is added back on as the catch step removes it else: catch = state['biomass'][-1]* parameters['catch_rate']*parameters['effort']/parameters['K'] state['biomass'][-1] = parameters['K']-parameters['catch_rate']*parameters['effort']/parameters['r'] state['biomass'][-1] += catch #state['biomass'][-1] = K*(1-r) else: b = state['biomass'][-1] state['biomass'][-1] = b+b*parameters['r']*(1-b/parameters['K']) return state #Catch component removes catch determines CPUE class CatchFixed(Component): """Fixed catch component with simplistic CPUE/effort calculation""" catch_rate = Parameter(title='Max catch rate', description='The biomass caught per unit of effort', type='Fleet dynamics') catch = Parameter(title='TAC', description='Total allowable catch', type='Management Controls' ) def get_parameters(self): return {'catch_rate': self.catch_rate, 'catch': self.catch} def execute(self,state,parameters,equilibrium=False): preCatchBiomass = state.get('biomass') previousBiomass = state['biomass'][-2] state.set(cpue=previousBiomass/parameters['K']*parameters['catch_rate']) state.set(biomass=preCatchBiomass-parameters['catch']) state.set(catch=parameters['catch']) if state.get('biomass') < 0: state.set(biomass=0,catch= preCatchBiomass) if state.get('cpue') <= 0: state.set(effort=0) else: state.set(effort=state.get('catch')/state.get('cpue')) return state #Constant effort class EffortFixed(Component): """Fixed catch component with simplistic CPUE/effort calculation""" catch_rate = Parameter(title='Max catch rate', description='The biomass caught per unit of effort', type='Fleet dynamics') effort = Parameter( title='Effort', description='Fishing effort', type='Management Controls' ) def get_parameters(self): return {'catch_rate': self.catch_rate, 'effort': self.effort} def execute(self,state,parameters,equilibrium=False): previousBiomass = state['biomass'][-2] preCatchBiomass = state['biomass'][-1] state.set(cpue=previousBiomass/parameters['K']*parameters['catch_rate']) state.set(catch=parameters['effort']*state.get('cpue')) state.set(biomass=preCatchBiomass-state.get('catch')) if state.get('biomass') < 0: state.set(biomass=0,catch= preCatchBiomass) state.set(effort=parameters['effort']) return state class Economics(Component): fixed_cost = Parameter( title='Operator fixed cost', description='An individual operator\s fixed annual cost', type='Economics') marginal_cost= Parameter( title='Operator marginal cost', description='An individual operator\s marginal cost per unit effort', type='Economics') movement_rate= Parameter( title='Fleet resize rate', description='The maximum rate at which vessels can enter or exit the fishery', type='Fleet dynamics') beach_price = Parameter( title='Beach price', description='The price per kg of landed fish', type='Economics') discount_rate = Parameter( title='Discount Rate', description='The discount rate', type='Economics') def get_parameters(self): return {'fixed_cost': self.fixed_cost, 'marginal_cost': self.marginal_cost, 'movement_rate': self.movement_rate, 'beach_price': self.beach_price, 'discount_rate': self.discount_rate} @staticmethod def _calculate_revenue(state,parameters): return state.get('catch')*parameters['beach_price'] @staticmethod def _calculate_cost(state,parameters): return (state.get('fleet_size')*parameters['fixed_cost']+\ state.get('effort')*parameters['marginal_cost']) @staticmethod def _calculate_profit(state,parameters): return Economics._calculate_revenue(state,parameters)-Economics._calculate_cost(state,parameters) def execute(self,state,parameters,equilibrium=False): #Adjust the fleet size original_fleet_size = state.get('fleet_size') while abs(self._calculate_profit(state,parameters))>parameters['fixed_cost'] and \ ((equilibrium and parameters['movement_rate'] > 0) or abs(original_fleet_size - state.get('fleet_size')) < parameters['movement_rate']): if self._calculate_profit(state,parameters) > 0: state.set(fleet_size = state.get('fleet_size')+1) else: state.set(fleet_size = state.get('fleet_size')-1) #Set the cost, revenue and profit state.set(cost = self._calculate_cost(state, parameters)) state.set(revenue = self._calculate_revenue(state,parameters)) profit = state.get('revenue')-state.get('cost') if abs(profit)<1000000: profit = 0 state.set(profit = profit) state.set(discounted_profit = profit*(1-parameters['discount_rate'])**(len(state['cost'])-2)) return state class State(dict): """Model state A dictionary where each key corresponds to an attribute of a fishery state (eg. biomass) all keys are the same length and can be extended trivially """ def __init__(self, attributes): """ Constructor attribute_list is a dictionary for the attributes of the fishery see example fishery models for details """ for key in attributes: self[key] = [nan] self.attributes = attributes self.attribute_order = self.attributes.keys() #The attributes to plot first up by default self.default_plot = self.attributes.keys() self.unit_order = [] units = {} for att in self.attributes: unit = self.attributes[att]['units'] if not units.has_key(unit): units[unit]=1 self.unit_order.append(unit) def extend(self): """Extend all the lists by one, using the previous value for the new value""" for att in self: self[att].append(self[att][-1]) return def set(self,**kwargs): """Set the current (last item) of one or more of the lists""" for key in kwargs: self[key][-1]=kwargs[key] def get(self,item): """Get the current (last item) of one of the lists""" return self[item][-1] def get_attribute_title(self,attribute): return self.attributes[attribute]['title'] def get_attribute_units(self,attribute): return self.attributes[attribute]['units'] def reset(self): """ Resets the state to the initial timestep """ for att in self: self[att]=self[att][0:1] return class Model(): """Model Definition By combining a set of model functions this class creates a complete model definition""" def __init__(self,functions=[],parameters={},initial_state = None,convergence_time=3): """ functions: a list of functions in the order that they are to be run parameters: a dict of parameters as required by the functions (can be set later) initial_state: initial state of the fishery convergence_time: number of steps required to convergence of static version """ if initial_state == None: self.state = State() else: self.state = initial_state self.functions = functions self.parameters = parameters self.convergence_time = convergence_time def get_parameters(self): """ returns a list of parameters as required by the model functions """ #Get all parameters pOut = {} for function in self.functions: pOut.update(function.get_parameters()) #Replace values with current if applicable for param in pOut: if self.parameters.has_key(param): pOut[param].value = self.parameters[param] return pOut def set_parameters(self,parameters): """ set the parameters to a given value for this and subsequent time steps """ self.parameters = parameters def get_parameter_types(self): """ return a list of parameter types """ types = {} p = self.get_parameters() for par in p: types[p[par]['type']] = 1 return types.keys() def set_state(self,state): """ set the state of the model """ self.state = state def reset(self): """ Resets the model state to the initial timestep """ self.state.reset() def run(self,steps = 1,constant_variable=None): """ run the model for one time step """ for step in range(0,steps): self.state.extend() for function in self.functions: self.state=function.execute(self.state,self.parameters,equilibrium=constant_variable!=None) class MultiThreadModelRun: class MyThread(threading.Thread): def __init__(self,function): '''Initialise the thread: function: a function to be called after run completion ''' threading.Thread.__init__(self) self.function = function self.update = False self.cancel_run = False def update_run(self,model,steps,options): '''Start a new run model: the model to use options: the run options ''' self.newmodel = copy.deepcopy(model) self.newsteps = steps self.newoptions = options self.update = True def run(self): '''The thread's run function''' import time while True: #Cancelling the thread's run for now if self.cancel_run: self.cancel_run = False self.update = False #Creating a new run if self.update: self.model = self.newmodel self.options = self.newoptions self.steps = self.newsteps self.update = False for step in range(0,self.steps): if self.update: break self.single_iteration(step) if not self.update: if not self.function==None: wx.CallAfter(self.function,self.output()) else: time.sleep(0.01) pass def cancel(self): '''Cancel this run''' self.update = True self.cancel_run = True def single_iteration(self,step): '''Perform a single iteration (to be implemented by inheriting class)''' pass def output(self): '''Return the model output (to be implemented by inheriting class)''' pass class DynamicThread(MyThread): '''Thread for dynamic model runs''' def single_iteration(self,step): '''Run a single time step''' self.model.run(1) def output(self): '''Return the model state''' return self.model.state class StaticThread(MyThread): '''Thread for static model runs''' def update_run(self,model,steps,options): '''Update the run, copying a new output state as well''' #MultiThreadModelRun.MyThread.update_run(self,model,steps,options) self.newmodel = copy.deepcopy(model) self.newsteps = steps self.newoptions = options self.update = True self.output_state = copy.deepcopy(self.newmodel.state) self.output_state.reset() def single_iteration(self,step): '''Find an equilibrium state for a single independent parameter value''' #Reset the model self.model.reset() #Set the independent value to the appropriate value self.model.state[self.options['independent_variable']] = [self.options['independent_values'][step]] self.model.parameters[self.options['independent_variable']] = self.options['independent_values'][step] self.model.run(self.options['convergence_time'],constant_variable = self.options['independent_variable']) if True: #self.model.state[self.options['independent_variable']][-1] == self.options['independent_values'][step]: for param in self.model.state.keys(): self.output_state[param].append(self.model.state[param][-1]) if self.model.state[self.options['independent_variable']][-1] < self.options['independent_values'][step]: print 'a' self.output_state[self.options['independent_variable']][-1] = self.options['independent_values'][step-1]+1e-6 # self.output_state[self.options['independent_variable']][-1] = self.options['independent_values'][step] def output(self): '''Return the output state''' return self.output_state def __init__(self,function=None): self.static_thread = self.StaticThread(function) self.static_thread.start() self.dynamic_thread = self.DynamicThread(function) self.dynamic_thread.start() def run(self,model,steps,dynamic=True,independent_variable='effort',independent_minimum = 0,independent_maximum = None,convergence_time=4): if dynamic: self.static_thread.cancel() self.dynamic_thread.update_run(model,steps,{}) else: self.dynamic_thread.cancel() self.static_thread.update_run(model,steps, { 'independent_variable': independent_variable, 'independent_values': linspace(independent_minimum,independent_maximum,steps), 'convergence_time':convergence_time}) def lobsterModel(control_type = 'catch'): '''A lobster model, loosely based on the Tasmanian Rock Lobster Fishery''' #------------------------------------------ #Parameter values customised for this model #------------------------------------------ r = {'value':1,'min':0,'max':2} K = {'value':7000000,'min':0,'max':10000000,'scale':1000,'units':'t'} catch_rate ={'value':1,'min':0.001,'max':5,'units':'kg/potlift'} catch = {'value':1500000,'min':0,'max':6000000,'scale':1000,'units':'t'} effort = {'value':1500000,'min':0,'max':5000000,'description':'Number of potlifts','scale':1e6,'scale_text':'millions'} fixed_cost ={'value':100000,'min':50000,'max':200000,'units':'$/year','scale':1000,'scale_text':'thousands'} marginal_cost= {'value':30,'min':5,'max':50,'units':'$/potlift'} movement_rate={'value':0,'min':0,'max':20,'units':'vessels/year'} beach_price = {'value':60,'min':0,'max':100,'units':'$/kg'} discount_rate = {'value':0.07,'min':0,'max':1,'units':''} #----------------------------------------- #Functions that control the model dynamics #----------------------------------------- #Discrete logistic growth growthClass = PDLogistic() growthClass.r.update(r) growthClass.K.update(K) #Catch component if control_type == 'catch': catchClass = CatchFixed() catchClass.catch.update(catch) elif control_type == 'effort': catchClass = EffortFixed() catchClass.effort.update(effort) catchClass.catch_rate.update(catch_rate) #Economics and fleet dynamics economicsClass = Economics() economicsClass.fixed_cost.update(fixed_cost) economicsClass.marginal_cost.update(marginal_cost) economicsClass.movement_rate.update(movement_rate) economicsClass.beach_price.update(beach_price) economicsClass.discount_rate.update(discount_rate) #----------------------------------------- #Set the state of the fishery #The attributes here must match what is #required by the functions PDLogistic, #CatchFixed/EffortFixed and Economics #----------------------------------------- initial_state = State( attributes = {'biomass': {'title': 'Biomass', 'units': 'tonnes','scale':1000}, 'catch': {'title': 'Catch', 'units': 'tonnes','scale':1000}, 'cpue': {'title': 'CPUE', 'units': 'kg/potlift','scale':1}, 'effort': {'title': 'Effort', 'units': 'millions of potlifts','scale':1e6}, 'fleet_size': {'title': 'Fleet Size','units': '# vessels','scale':1}, 'revenue': {'title': 'Revenue','units': '$ (millions)','scale':1e6}, 'cost': {'title': 'Cost','units': '$ (millions)','scale':1e6}, 'profit': {'title': 'Profit','units': '$ (millions)','scale':1e6}, 'discounted_profit': {'title': 'Discounted profit','units': '$ (millions)','scale':1e6}, }) initial_state.default_plot = ['biomass','catch'] # initial_state.default_plot = ['catch','revenue','cost','profit'] initial_state.attribute_order = ['biomass','catch','profit','revenue','cost','discounted_profit','cpue','effort','fleet_size'] #Set the initial fishery parameters initial_state.set(biomass=5000000,fleet_size=120) #----------------------------------------- #Create the fishery model #----------------------------------------- model = Model(functions = [growthClass,catchClass,economicsClass],initial_state = initial_state) return model
Python
import numpy as np # Colours and colourmaps that are readable by most colourblind people # Copyright 2010, University of Tasmania, Australian Seafood CRC # This program is released under the Open Software License ("OSL") v. 3.0. See OSL3.0.htm for details. #A set of safe plotting colours from http://jfly.iam.u-tokyo.ac.jp/color/ rgb = np.array([[0,0,0],[230,159,0],[86,180,233],[0,158,115],[240,228,66],[0,114,178],[213,94,0],[204,121,167]]) rgbScaled = rgb/255.0 #Colormaps from #A. Light & P.J. Bartlein, "The End of the Rainbow? Color Schemes for #Improved Data Graphics," Eos,Vol. 85, No. 40, 5 October 2004. #http://geography.uoregon.edu/datagraphics/EOS/Light&Bartlein_EOS2004.pdf def makeMap(inMap,name): import numpy import matplotlib inMap = numpy.array(inMap)/255.0 return matplotlib.colors.LinearSegmentedColormap.from_list(name,inMap) blueMap = makeMap([[243,246,248],[224,232,240],[171,209,236],[115,180,224],[35,157,213],[0,142,205],[0,122,192]],'cbBlue') blueGrayMap = makeMap([[0,170,227],[53,196,238],[133,212,234],[190,230,242],[217,224,230],[146,161,170],[109,122,129],[65,79,81]],'cbBlueGray') brownBlueMap = makeMap([[144,100,44],[187,120,54],[225,146,65],[248,184,139],[244,218,200],[241,244,245],[207,226,240],[160,190,225],[109,153,206],[70,99,174],[24,79,162]],'cbBrownBlue') redBlueMap = makeMap([[175,53,71],[216,82,88],[239,133,122],[245,177,139],[249,216,168],[242,238,197],[216,236,241],[154,217,238],[68,199,239],[0,170,226],[0,116,188]],'cbRedBlue')
Python
#!/usr/bin/env python ''' Fisheries Economics Masterclass model Copyright 2010, University of Tasmania, Australian Seafood CRC This program is released under the Open Software License ("OSL") v. 3.0. See OSL3.0.htm for details. ''' import threading import wx from pylab import * import copy class Parameter(dict): """ Model parameter class A simple dict with some default values """ def __init__(self,value=0,min=0,max=1,units='',title='',description='',type='Miscellaneous',scale=1,scale_text=''): """Initialise the parameter""" self['value'] = value self['min'] = min self['max'] = max self['units'] = units self['title'] = title self['description'] = description self['type'] = type self['scale'] = scale self['scale_text']=scale_text class Component: """ Model component class All model classes should inherit this """ def get_parameters(self): """ Returns the parameters required by this component The format is a dictionary, keys are parameter name, value is a list of minimum value, maximum value, default value, """ return {} def execute(self,state,parameters): """Executes this component and returns the modified state""" return state class PDLogistic(Component): """Population Dynamics Logistic growth component""" def __init__(self): self.r = Parameter(title='Population growth rate', description='The maximum growth rate of the population', type='Population dynamics') self.K = Parameter(title='Maximum population size', description='The size of a unfished (virgin) population', type='Population dynamics') def get_parameters(self): return {'r': self.r,'K': self.K} #Execute a logistic step def execute(self,state,parameters,equilibrium=False): if equilibrium: r = parameters['r'] K = parameters['K'] if parameters.has_key('catch'): C = parameters['catch'] # [r-1 + (1-2r+r2+4Cr/K)^.5]/(2r/K) term = (r)**2-4*C*r/K #term = (1-4*parameters['catch']/parameters['r']/parameters['K']) if term < 0: state['biomass'][-1] = 0 else: #state['biomass'][-1] = parameters['K']/2*(1+term**0.5)#+parameters['catch'] #Catch is added back on as the catch step removes it state['biomass'][-1] = (r+term**.5)/(2*r/K) state['biomass'][-1] += parameters['catch'] #Catch is added back on as the catch step removes it else: catch = state['biomass'][-1]* parameters['catch_rate']*parameters['effort']/parameters['K'] state['biomass'][-1] = parameters['K']-parameters['catch_rate']*parameters['effort']/parameters['r'] state['biomass'][-1] += catch #state['biomass'][-1] = K*(1-r) else: b = state['biomass'][-1] state['biomass'][-1] = b+b*parameters['r']*(1-b/parameters['K']) return state #Catch component removes catch determines CPUE class CatchFixed(Component): """Fixed catch component with simplistic CPUE/effort calculation""" catch_rate = Parameter(title='Max catch rate', description='The biomass caught per unit of effort', type='Fleet dynamics') catch = Parameter(title='TAC', description='Total allowable catch', type='Management Controls' ) def get_parameters(self): return {'catch_rate': self.catch_rate, 'catch': self.catch} def execute(self,state,parameters,equilibrium=False): preCatchBiomass = state.get('biomass') previousBiomass = state['biomass'][-2] state.set(cpue=previousBiomass/parameters['K']*parameters['catch_rate']) state.set(biomass=preCatchBiomass-parameters['catch']) state.set(catch=parameters['catch']) if state.get('biomass') < 0: state.set(biomass=0,catch= preCatchBiomass) if state.get('cpue') <= 0: state.set(effort=0) else: state.set(effort=state.get('catch')/state.get('cpue')) return state #Constant effort class EffortFixed(Component): """Fixed catch component with simplistic CPUE/effort calculation""" catch_rate = Parameter(title='Max catch rate', description='The biomass caught per unit of effort', type='Fleet dynamics') effort = Parameter( title='Effort', description='Fishing effort', type='Management Controls' ) def get_parameters(self): return {'catch_rate': self.catch_rate, 'effort': self.effort} def execute(self,state,parameters,equilibrium=False): previousBiomass = state['biomass'][-2] preCatchBiomass = state['biomass'][-1] state.set(cpue=previousBiomass/parameters['K']*parameters['catch_rate']) state.set(catch=parameters['effort']*state.get('cpue')) state.set(biomass=preCatchBiomass-state.get('catch')) if state.get('biomass') < 0: state.set(biomass=0,catch= preCatchBiomass) state.set(effort=parameters['effort']) return state class Economics(Component): fixed_cost = Parameter( title='Operator fixed cost', description='An individual operator\s fixed annual cost', type='Economics') marginal_cost= Parameter( title='Operator marginal cost', description='An individual operator\s marginal cost per unit effort', type='Economics') movement_rate= Parameter( title='Fleet resize rate', description='The maximum rate at which vessels can enter or exit the fishery', type='Fleet dynamics') beach_price = Parameter( title='Beach price', description='The price per kg of landed fish', type='Economics') discount_rate = Parameter( title='Discount Rate', description='The discount rate', type='Economics') def get_parameters(self): return {'fixed_cost': self.fixed_cost, 'marginal_cost': self.marginal_cost, 'movement_rate': self.movement_rate, 'beach_price': self.beach_price, 'discount_rate': self.discount_rate} @staticmethod def _calculate_revenue(state,parameters): return state.get('catch')*parameters['beach_price'] @staticmethod def _calculate_cost(state,parameters): return (state.get('fleet_size')*parameters['fixed_cost']+\ state.get('effort')*parameters['marginal_cost']) @staticmethod def _calculate_profit(state,parameters): return Economics._calculate_revenue(state,parameters)-Economics._calculate_cost(state,parameters) def execute(self,state,parameters,equilibrium=False): #Adjust the fleet size original_fleet_size = state.get('fleet_size') while abs(self._calculate_profit(state,parameters))>parameters['fixed_cost'] and \ ((equilibrium and parameters['movement_rate'] > 0) or abs(original_fleet_size - state.get('fleet_size')) < parameters['movement_rate']): if self._calculate_profit(state,parameters) > 0: state.set(fleet_size = state.get('fleet_size')+1) else: state.set(fleet_size = state.get('fleet_size')-1) #Set the cost, revenue and profit state.set(cost = self._calculate_cost(state, parameters)) state.set(revenue = self._calculate_revenue(state,parameters)) profit = state.get('revenue')-state.get('cost') if abs(profit)<1000000: profit = 0 state.set(profit = profit) state.set(discounted_profit = profit*(1-parameters['discount_rate'])**(len(state['cost'])-2)) return state class State(dict): """Model state A dictionary where each key corresponds to an attribute of a fishery state (eg. biomass) all keys are the same length and can be extended trivially """ def __init__(self, attributes): """ Constructor attribute_list is a dictionary for the attributes of the fishery see example fishery models for details """ for key in attributes: self[key] = [nan] self.attributes = attributes self.attribute_order = self.attributes.keys() #The attributes to plot first up by default self.default_plot = self.attributes.keys() self.unit_order = [] units = {} for att in self.attributes: unit = self.attributes[att]['units'] if not units.has_key(unit): units[unit]=1 self.unit_order.append(unit) def extend(self): """Extend all the lists by one, using the previous value for the new value""" for att in self: self[att].append(self[att][-1]) return def set(self,**kwargs): """Set the current (last item) of one or more of the lists""" for key in kwargs: self[key][-1]=kwargs[key] def get(self,item): """Get the current (last item) of one of the lists""" return self[item][-1] def get_attribute_title(self,attribute): return self.attributes[attribute]['title'] def get_attribute_units(self,attribute): return self.attributes[attribute]['units'] def reset(self): """ Resets the state to the initial timestep """ for att in self: self[att]=self[att][0:1] return class Model(): """Model Definition By combining a set of model functions this class creates a complete model definition""" def __init__(self,functions=[],parameters={},initial_state = None,convergence_time=3): """ functions: a list of functions in the order that they are to be run parameters: a dict of parameters as required by the functions (can be set later) initial_state: initial state of the fishery convergence_time: number of steps required to convergence of static version """ if initial_state == None: self.state = State() else: self.state = initial_state self.functions = functions self.parameters = parameters self.convergence_time = convergence_time def get_parameters(self): """ returns a list of parameters as required by the model functions """ #Get all parameters pOut = {} for function in self.functions: pOut.update(function.get_parameters()) #Replace values with current if applicable for param in pOut: if self.parameters.has_key(param): pOut[param].value = self.parameters[param] return pOut def set_parameters(self,parameters): """ set the parameters to a given value for this and subsequent time steps """ self.parameters = parameters def get_parameter_types(self): """ return a list of parameter types """ types = {} p = self.get_parameters() for par in p: types[p[par]['type']] = 1 return types.keys() def set_state(self,state): """ set the state of the model """ self.state = state def reset(self): """ Resets the model state to the initial timestep """ self.state.reset() def run(self,steps = 1,constant_variable=None): """ run the model for one time step """ for step in range(0,steps): self.state.extend() for function in self.functions: self.state=function.execute(self.state,self.parameters,equilibrium=constant_variable!=None) class MultiThreadModelRun: class MyThread(threading.Thread): def __init__(self,function): '''Initialise the thread: function: a function to be called after run completion ''' threading.Thread.__init__(self) self.function = function self.update = False self.cancel_run = False def update_run(self,model,steps,options): '''Start a new run model: the model to use options: the run options ''' self.newmodel = copy.deepcopy(model) self.newsteps = steps self.newoptions = options self.update = True def run(self): '''The thread's run function''' import time while True: #Cancelling the thread's run for now if self.cancel_run: self.cancel_run = False self.update = False #Creating a new run if self.update: self.model = self.newmodel self.options = self.newoptions self.steps = self.newsteps self.update = False for step in range(0,self.steps): if self.update: break self.single_iteration(step) if not self.update: if not self.function==None: wx.CallAfter(self.function,self.output()) else: time.sleep(0.01) pass def cancel(self): '''Cancel this run''' self.update = True self.cancel_run = True def single_iteration(self,step): '''Perform a single iteration (to be implemented by inheriting class)''' pass def output(self): '''Return the model output (to be implemented by inheriting class)''' pass class DynamicThread(MyThread): '''Thread for dynamic model runs''' def single_iteration(self,step): '''Run a single time step''' self.model.run(1) def output(self): '''Return the model state''' return self.model.state class StaticThread(MyThread): '''Thread for static model runs''' def update_run(self,model,steps,options): '''Update the run, copying a new output state as well''' #MultiThreadModelRun.MyThread.update_run(self,model,steps,options) self.newmodel = copy.deepcopy(model) self.newsteps = steps self.newoptions = options self.update = True self.output_state = copy.deepcopy(self.newmodel.state) self.output_state.reset() def single_iteration(self,step): '''Find an equilibrium state for a single independent parameter value''' #Reset the model self.model.reset() #Set the independent value to the appropriate value self.model.state[self.options['independent_variable']] = [self.options['independent_values'][step]] self.model.parameters[self.options['independent_variable']] = self.options['independent_values'][step] self.model.run(self.options['convergence_time'],constant_variable = self.options['independent_variable']) if True: #self.model.state[self.options['independent_variable']][-1] == self.options['independent_values'][step]: for param in self.model.state.keys(): self.output_state[param].append(self.model.state[param][-1]) if self.model.state[self.options['independent_variable']][-1] < self.options['independent_values'][step]: print 'a' self.output_state[self.options['independent_variable']][-1] = self.options['independent_values'][step-1]+1e-6 # self.output_state[self.options['independent_variable']][-1] = self.options['independent_values'][step] def output(self): '''Return the output state''' return self.output_state def __init__(self,function=None): self.static_thread = self.StaticThread(function) self.static_thread.start() self.dynamic_thread = self.DynamicThread(function) self.dynamic_thread.start() def run(self,model,steps,dynamic=True,independent_variable='effort',independent_minimum = 0,independent_maximum = None,convergence_time=4): if dynamic: self.static_thread.cancel() self.dynamic_thread.update_run(model,steps,{}) else: self.dynamic_thread.cancel() self.static_thread.update_run(model,steps, { 'independent_variable': independent_variable, 'independent_values': linspace(independent_minimum,independent_maximum,steps), 'convergence_time':convergence_time}) def lobsterModel(control_type = 'catch'): '''A lobster model, loosely based on the Tasmanian Rock Lobster Fishery''' #------------------------------------------ #Parameter values customised for this model #------------------------------------------ r = {'value':1,'min':0,'max':2} K = {'value':7000000,'min':0,'max':10000000,'scale':1000,'units':'t'} catch_rate ={'value':1,'min':0.001,'max':5,'units':'kg/potlift'} catch = {'value':1500000,'min':0,'max':6000000,'scale':1000,'units':'t'} effort = {'value':1500000,'min':0,'max':5000000,'description':'Number of potlifts','scale':1e6,'scale_text':'millions'} fixed_cost ={'value':100000,'min':50000,'max':200000,'units':'$/year','scale':1000,'scale_text':'thousands'} marginal_cost= {'value':30,'min':5,'max':50,'units':'$/potlift'} movement_rate={'value':0,'min':0,'max':20,'units':'vessels/year'} beach_price = {'value':60,'min':0,'max':100,'units':'$/kg'} discount_rate = {'value':0.07,'min':0,'max':1,'units':''} #----------------------------------------- #Functions that control the model dynamics #----------------------------------------- #Discrete logistic growth growthClass = PDLogistic() growthClass.r.update(r) growthClass.K.update(K) #Catch component if control_type == 'catch': catchClass = CatchFixed() catchClass.catch.update(catch) elif control_type == 'effort': catchClass = EffortFixed() catchClass.effort.update(effort) catchClass.catch_rate.update(catch_rate) #Economics and fleet dynamics economicsClass = Economics() economicsClass.fixed_cost.update(fixed_cost) economicsClass.marginal_cost.update(marginal_cost) economicsClass.movement_rate.update(movement_rate) economicsClass.beach_price.update(beach_price) economicsClass.discount_rate.update(discount_rate) #----------------------------------------- #Set the state of the fishery #The attributes here must match what is #required by the functions PDLogistic, #CatchFixed/EffortFixed and Economics #----------------------------------------- initial_state = State( attributes = {'biomass': {'title': 'Biomass', 'units': 'tonnes','scale':1000}, 'catch': {'title': 'Catch', 'units': 'tonnes','scale':1000}, 'cpue': {'title': 'CPUE', 'units': 'kg/potlift','scale':1}, 'effort': {'title': 'Effort', 'units': 'millions of potlifts','scale':1e6}, 'fleet_size': {'title': 'Fleet Size','units': '# vessels','scale':1}, 'revenue': {'title': 'Revenue','units': '$ (millions)','scale':1e6}, 'cost': {'title': 'Cost','units': '$ (millions)','scale':1e6}, 'profit': {'title': 'Profit','units': '$ (millions)','scale':1e6}, 'discounted_profit': {'title': 'Discounted profit','units': '$ (millions)','scale':1e6}, }) initial_state.default_plot = ['biomass','catch'] # initial_state.default_plot = ['catch','revenue','cost','profit'] initial_state.attribute_order = ['biomass','catch','profit','revenue','cost','discounted_profit','cpue','effort','fleet_size'] #Set the initial fishery parameters initial_state.set(biomass=5000000,fleet_size=120) #----------------------------------------- #Create the fishery model #----------------------------------------- model = Model(functions = [growthClass,catchClass,economicsClass],initial_state = initial_state) return model
Python
#import matplotlib as mp #mp.use('GTK') #from matplotlib.figure import Figure #from matplotlib.pyplot import show import matplotlib.pyplot as plt figure = plt.figure() pos = [.1,.1,.8,.8] pos2 = list(pos) pos2[2]=.75 print pos print pos2 ax1 = figure.add_axes(pos, frameon = False,label ='a') ax2 = figure.add_axes(pos2, frameon = False,label = 'b') ax1.yaxis.tick_right() ax1.yaxis.set_label_position('right') ax2.yaxis.tick_right() ax2.yaxis.set_label_position('right') ax1.set_ylabel('fda') ax2.set_ylabel('$') ax1.plot([0,1],[1,2],'r:') ax2.plot([0,1],[10,1],'g-') plt.show()
Python
#!/usr/bin/env python """ Fisheries Economics Masterclass GUI Klaas Hartmann 2010 Copyright 2010, University of Tasmania, Australian Seafood CRC This program is released under the Open Software License ("OSL") v. 3.0. See OSL3.0.htm for details. """ import wx import wx.html import fisheries_model import colourblind import matplotlib #matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import \ FigureCanvasWxAgg as FigCanvas import numpy import copy import os import sys #String constants for some menus etc MG_QUOTA='Output Controlled' MG_EFFORT='Input Controlled' SIM_DYNAMIC='Dynamic' SIM_STATIC='Static (Equilibrium)' #Version history: #1.00 Initial release from Hobart Class 1 #1.01 Made fishery crash instantaneous. #1.02 Initial version on Google Code #1.03 Included licencing information VERSIONSTRING = '1.03' #Globals that specify the current simulation and management type #(to be subsumed at a later stage...) SIM_TYPE='' MG_TYPE='' class Frame(wx.Frame): '''The main (only?) GUI Frame''' def __init__(self,width,height): wx.Frame.__init__(self, None, size=wx.Size(width,height), title = 'Fisheries Explorer') #self.SetSize(wx.Size(width,height)) #Set the starting simulation and management types global SIM_TYPE global MG_TYPE MG_TYPE = MG_QUOTA SIM_TYPE = SIM_STATIC self.Maximize() #Initialise model components self._init_model() #Initialise model/graph update system self._init_update() #Initialise GUI components self._init_gui() def _init_update(self): '''Initialise model/graph update system''' #Will contain current parameters self.parameters= {} #Will contain last parameters for which the model run was completed self.computed_parameters = {} #Will contain last parameters for which a graph was produced self.plotted_parameters = {} #Whether current computation has been completed self.computed_complete = True #Timer for model reruns self.timer_model = wx.Timer(self) self.timer_model.Start(250) wx.EVT_TIMER(self,self.timer_model.GetId(),self.on_timer_model) #Hack to call layout after init self.timer_init_hack = wx.Timer(self) self.timer_init_hack.Start(250) wx.EVT_TIMER(self,self.timer_init_hack.GetId(),self.on_timer_init_hack) #The model execution thread self.model_thread = fisheries_model.MultiThreadModelRun(self.model_data_updater) def _init_model(self,type='catch'): '''Initialise model''' self.model = fisheries_model.lobsterModel(control_type = type) def _init_gui(self): '''Initialise GUI components''' #Setup sizers (in hierarchical order) self.sizer = wx.FlexGridSizer(rows=2,cols=1) #Create wx objects self.parameter_panel = ParameterPanel(self,self.model,sim_update_fx=self.on_simulation_change) self.plot_panel = PlotPanel(self) #Set up main sizer self.sizer.Add(self.parameter_panel,0,wx.EXPAND) self.sizer.Add(self.plot_panel,0,wx.EXPAND) self.sizer.AddGrowableCol(0,1) self.sizer.AddGrowableRow(1,1) #Set sizers self.SetSizer(self.sizer) #Set menu self.menubar = MenuBar(self,sim_update_fx=self.on_simulation_change,parameter_type_fx=self.parameter_panel.show_parameter_set,reset_model_fx=self.on_simulation_change) self.SetMenuBar(self.menubar) self.menubar.set_parameter_types(self.model.get_parameter_types()) #Bind events self.Bind(wx.EVT_SCROLL,self.on_slide_change) #self.Bind(wx.EVT_CLOSE, self.onCloseWindow) self.on_slide_change(None) self.on_timer_model(None) #Prevent the frame getting resized too small min_size = self.sizer.GetMinSize() self.SetMinSize(min_size) #Set the icon self.icon = wx.Icon(os.path.join('images','fishnet.ico'),wx.BITMAP_TYPE_ICO) self.SetIcon(self.icon) #It still doesn't close cleanly for some unknown reason.. block = False def onCloseWindow(self,event): self.timer_model.Stop() self.timer_model.Destroy() self.icon.Destroy() event.Skip() def on_timer_model(self,event): '''Rerun the model if parameters have changed''' #If parameters have changed we need to recalculate the model if self.parameters != self.computed_parameters: self.computed_complete=False self.model.set_parameters(self.parameter_panel.get_parameters()) self.model.reset() #Run the appropriate simulation if SIM_TYPE == SIM_STATIC: if MG_TYPE == MG_QUOTA: max= self.parameters['K']*self.parameters['r']/4*1.01 self.model_thread.run(self.model,20,dynamic=False,independent_variable='catch',independent_maximum=max) else: self.model_thread.run(self.model,20,dynamic=False,independent_variable='effort',independent_maximum=6e6) else: self.model_thread.run(self.model,20) self.computed_parameters = self.parameters init_hack_count = 0 def on_timer_init_hack(self,event): '''A hack to layout the plot panel after load. For some reason the legend is not displayed correctly.''' if self.init_hack_count > 0: self.timer_init_hack.Stop() self.init_hack_count += 1 self.plot_panel.update_visibility() self.plot_panel.OnSize() self.plot_panel.Layout() def on_simulation_change(self,simulation_type,control_type): '''Called if the simulation type (static/dynamic, quota/effort controlled) changes''' global SIM_TYPE global MG_TYPE SIM_TYPE = simulation_type MG_TYPE = control_type #Initialise the model with appropriate control type if MG_TYPE == MG_QUOTA: self._init_model('catch') else: self._init_model('effort') self.computed_parameters = None self.parameter_panel.set_model(self.model) self.plot_panel.update_visibility() self.plot_panel.Layout() self.on_timer_model(None) def on_slide_change(self,event): '''Get the latest set of parameters if the sliders have been moved''' #Store the latest set of parameters # if event.GetEventObject() in self.parameter_panel.GetChildren(): self.parameters = self.parameter_panel.get_parameters() def model_data_updater(self,state): self.computed_complete=True self.model.state = state self.plot_panel.update_state(self.model.state) min_size = self.sizer.GetMinSize() self.SetMinSize(min_size) class MenuBar(wx.MenuBar): def __init__(self,parent_frame,sim_update_fx=None,parameter_type_fx=None,reset_model_fx=None): wx.MenuBar.__init__(self) self.sim_update_fx = sim_update_fx self.parameter_type_fx=parameter_type_fx self.reset_model_fx = reset_model_fx self.parent_frame = parent_frame self.scenario_menu = wx.Menu() self.reset_model = self.scenario_menu.Append(-1,'Reset Model') self.scenario_menu.Append(-1,' ').Enable(False) self.scenario_menu.AppendRadioItem(-1,'Rock Lobster Fishery') self.scenario_menu.Append(-1,' ').Enable(False) self.static_simulation = self.scenario_menu.AppendRadioItem(-1,SIM_STATIC) self.dynamic_simulation = self.scenario_menu.AppendRadioItem(-1,SIM_DYNAMIC) self.scenario_menu.Append(-1,' ').Enable(False) self.input_control = self.scenario_menu.AppendRadioItem(-1,MG_EFFORT) self.output_control = self.scenario_menu.AppendRadioItem(-1,MG_QUOTA) #Bring checks in line with initial simulation state if SIM_TYPE == SIM_STATIC: self.static_simulation.Check() else: self.dynamic_simulation.Check() if MG_TYPE == MG_QUOTA: self.output_control.Check() else: self.input_control.Check() self.parameter_menu = wx.Menu() self.parameter_items = [] self.help_menu = wx.Menu() self.about = self.help_menu.Append(-1,'About') self.license = self.help_menu.Append(-1,'License') self.Append(self.scenario_menu,'Model') self.Append(self.parameter_menu,'Parameters') self.Append(self.help_menu,'Help') parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.input_control) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.output_control) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.static_simulation) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.dynamic_simulation) parent_frame.Bind(wx.EVT_MENU, self.on_about,self.about) parent_frame.Bind(wx.EVT_MENU, self.on_license,self.license) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.reset_model) def set_parameter_types(self,types): for item in self.parameter_items: self.parameter_menu.Delete(item) for type in ["All"]+types: self.parameter_items.append(self.parameter_menu.AppendRadioItem(-1,type)) self.parent_frame.Bind(wx.EVT_MENU, self.on_parameter_selection, self.parameter_items[-1]) if type == 'Management Controls': self.parameter_items[-1].Check() self.on_parameter_selection(None) def on_reset_model(self,event): '''Reset the model''' self.reset_model_fx() def on_parameter_selection(self,event): '''Called when a parameter set is selected''' for item in self.parameter_items: if item.IsChecked(): self.parameter_type_fx(item.GetText()) def on_simulation_change(self,event): if self.input_control.IsChecked(): control_type = MG_EFFORT else: control_type = MG_QUOTA if self.static_simulation.IsChecked(): simulation_type = SIM_STATIC else: simulation_type= SIM_DYNAMIC self.sim_update_fx(simulation_type = simulation_type, control_type = control_type) event.Skip() def on_about(self,event): '''About handler, shows modal AboutBox''' dlg = AboutBox(self.parent_frame,title='About Fisheries Explorer',filename='about.html') dlg.ShowModal() dlg.Destroy() def on_license(self,event): '''License handler, shows modal AboutBox''' dlg = AboutBox(self.parent_frame,title='Fisheries Explorer License',filename='OSL3.0.htm') dlg.ShowModal() dlg.Destroy() class ParameterPanel(wx.Panel): '''A panel for parameter input''' def __init__(self,parent,model = [],sim_update_fx=None): wx.Panel.__init__(self,parent) self.type_shown = 'All' self.model = model self.parameters = model.get_parameters() self._base_layout() self.set_model(model) self.sim_update_fx = sim_update_fx def set_model(self,model): '''Set the parameters displayed in the panel (expects a Parameter object)''' self.parameters = model.get_parameters() self.model = model self.parameter_layout() self.show_parameter_set() def _base_layout(self): #Empty lists for storing gui objects (to get parameter values etc) self.label_parameters = {} self.label_param_values = {} self.slider_parameters = {} self.sizer = wx.FlexGridSizer(rows=1,cols=2) self.sizer.AddGrowableCol(1,1) self.SetSizer(self.sizer) self.set_panel = wx.Panel(self) self.set_sizer = wx.FlexGridSizer(rows=3,cols=1) self.set_panel.SetSizer(self.set_sizer) self.control_panel = wx.Panel(self) self.control_sizer = wx.FlexGridSizer(rows=len(self.parameters),cols=3) self.control_sizer.AddGrowableCol(1,1) self.control_panel.SetSizer(self.control_sizer) self.sizer.Add(self.set_panel,0) self.sizer.Add(self.control_panel,0,flag=wx.EXPAND) if False: #Drop down box for choosing parameter types self.set_sizer.Add(wx.StaticText(self.set_panel,label='Parameter Set:')) self.parameter_choice = wx.Choice(self.set_panel,1) self.set_sizer.Add(self.parameter_choice) #Set selection items items = self.model.get_parameter_types() items.insert(0,'ALL') self.parameter_choice.SetItems(items) self.parameter_choice.SetSelection(0) if False: self.static_toggle = wx.RadioBox(self.set_panel,1,"Simulation Type",choices=[SIM_STATIC,SIM_DYNAMIC]) self.management_toggle = wx.RadioBox(self.set_panel,1,"Management Type",choices=[MG_EFFORT,MG_QUOTA]) self.set_sizer.Add(self.static_toggle) self.set_sizer.Add(self.management_toggle) self.Bind(wx.EVT_CHOICE,self.on_selection_change) self.Bind(wx.EVT_RADIOBOX,self.on_simulation_change) def parameter_layout(self): #Delete all existing objects if hasattr(self,'control_sizer'): self.control_sizer.Clear(True) #Create the caption, value and slider for each parameter count = 0 for param in self.parameters: p = self.parameters[param] self.label_parameters[param]=wx.StaticText(self.control_panel,label=p['title']+':') current_value = round((p['value']-p['min'])/float(p['max']-p['min'])*1000) self.slider_parameters[param]= wx.Slider(self.control_panel, -1, current_value, 0, 1000, wx.DefaultPosition, style= wx.SL_HORIZONTAL) self.label_param_values[param]=wx.StaticText(self.control_panel,label='') self.label_parameters[param].SetToolTipString(p['description']) self.slider_parameters[param].SetToolTipString(p['description']) self.control_sizer.Add(self.label_parameters[param],0,flag=wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT) self.control_sizer.Add(self.slider_parameters[param],0,flag=wx.EXPAND) self.control_sizer.Add(self.label_param_values[param],0,flag=wx.ALIGN_LEFT) count += 1 self.on_slide_change(None) self.Bind(wx.EVT_SCROLL,self.on_slide_change) def on_simulation_change(self,event): self.sim_update_fx(simulation_type = self.static_toggle.GetStringSelection(), control_type = self.management_toggle.GetStringSelection()) def on_selection_change(self,event): '''Update parameter list when a different parameter set is selected''' type = self.parameter_choice.GetItems()[self.parameter_choice.GetSelection()] self.show_parameter_set(type) def show_parameter_set(self,type=None): '''Show parameters of type''' #If type is unspecified we show the same parameter set if type != None: self.type_shown = type type = self.type_shown #Show the selected parameters for param in self.parameters: selected =((type == 'ALL' or type == 'All' or self.parameters[param]['type'] == type) and (SIM_TYPE == SIM_DYNAMIC or self.parameters[param]['type'] != 'Management Controls')) if SIM_TYPE == SIM_STATIC and param == 'discount_rate': selected = False self.label_param_values[param].Show(selected) self.label_parameters[param].Show(selected) self.slider_parameters[param].Show(selected) self.Fit() self.GetParent().Layout() def on_slide_change(self,event): '''Slider change event updates value label''' param_values = self.get_parameters() for param in (param_values): scale_text = '' if self.parameters[param]['scale_text'] != '': scale_text = ' (' + self.parameters[param]['scale_text'] + ')' self.label_param_values[param].SetLabel(str(param_values[param]/self.parameters[param]['scale'])+ ' ' + self.parameters[param]['units'] + scale_text) self.Layout() #Propagate the event so that the frame can process it if event != None: event.Skip() def get_parameters(self): '''Get a dict of the current parameter values''' out = {} for param in self.parameters: p = self.parameters[param] out[param] = float(self.slider_parameters[param].GetValue())/1000.0*(p['max']-p['min'])+p['min'] return out def set_parameters(self,parameter_values): '''Update parameters from a dict''' out = {} for param in parameter_values.keys(): if self.parameters.has_key(param): v = parameter_values[param] p = self.parameters[param] self.slider_parameters[param].SetValue(int((v-p['min'])/(p['max']-p['min'])*1000)) self.on_slide_change(None) class PlotPanel(wx.Panel): line_colours = colourblind.rgbScaled line_styles = [[127,1], #solid [5,5], #dashed [20,20,2,20], #dash-dot [2,2,2,2] #dotted ] def __init__(self,parent): wx.Panel.__init__(self,parent) self.last_redraw_size = [] self.fig = Figure() self.fig.set_facecolor([1,1,1]) self.control_panel = wx.Panel(self) self.canvas_panel = wx.Panel(self) self.canvas = FigCanvas(self.canvas_panel,wx.ID_ANY,self.fig) self.sizer = wx.FlexGridSizer(rows=1,cols=2,hgap=5,vgap=5) self.sizer.Add(self.canvas_panel,flag=wx.EXPAND) self.sizer.Add(self.control_panel,flag=wx.ALIGN_CENTER|wx.ALL) self.sizer.AddGrowableCol(0,1) self.sizer.AddGrowableRow(0,1) self.SetSizer(self.sizer) self.control_sizer = wx.FlexGridSizer(hgap=5,vgap=5) self.control_panel.SetSizer(self.control_sizer) self.control_panel.Bind(wx.EVT_CHECKBOX,self.redraw) # self.canvas.SetAutoLayout(True) self.canvas_panel.SetMinSize([600,300]) self.state = None self.bounds = {} self.xbound = 0 self.SetBackgroundColour(wx.WHITE) self.canvas_panel.SetBackgroundColour(wx.WHITE) self.control_panel.SetBackgroundColour(wx.WHITE) self.canvas_panel.Bind(wx.EVT_SIZE, self.OnSize) self.Fit() def OnSize(self,event=None,size=None): if event == None and size == None: size = self.canvas_panel.GetClientSize() elif event != None and size == None: size = event.GetSize() #If the size has actually changed we redraw (several events may #be intercepted here per resize) if size != self.last_redraw_size: self.last_redraw_size = size self.fig.set_figwidth(size[0]/(1.0*self.fig.get_dpi())) self.fig.set_figheight(size[1]/(1.0*self.fig.get_dpi())) self.canvas.SetClientSize(size) self.redraw(None, redraw=True) if event != None: event.Skip() def _setup_control_panel(self): self._update_line_styles() #Remove existing widgets self.control_sizer.Clear(True) parameters = self.state.attribute_order self.control_sizer.SetRows(len(parameters)) self.control_sizer.SetCols(3) #Column Labels if False: self.control_sizer.SetRows(len(parameters)+1) column_labels = ['Plot','Parameter','Style'] for col in range(len(column_labels)): self.control_sizer.Add(wx.StaticText(self.control_panel,-1,column_labels[col])) self.check_boxes = {} self.param_text = {} self.param_bitmap = {} self.pens = {} self.colours = {} self.linedc = {} self.linebitmap = {} # self.check_boxes = {} linedc = wx.MemoryDC() for param in parameters: rgbcolour = self.unit_colour[self.state.get_attribute_units(param)] self.colours[param] = wx.Colour(rgbcolour[0]*255,rgbcolour[1]*255,rgbcolour[2]*255) style = self.parameter_style[param] #Add the check box self.check_boxes[param] = wx.CheckBox(self.control_panel,-1,'') self.control_sizer.Add(self.check_boxes[param]) #Add the description self.param_text[param] = wx.StaticText(self.control_panel,-1,self.state.get_attribute_title(param)) self.control_sizer.Add(self.param_text[param]) self.param_text[param].SetForegroundColour(self.colours[param]) self.param_text[param].Refresh() #Add the linestyle self.linebitmap[param] = wx.EmptyBitmap(40,20) linedc.SelectObject(self.linebitmap[param]) linedc.Clear() self.pens[param] = wx.Pen(colour = self.colours[param], width = 1,style = wx.USER_DASH) self.pens[param].SetDashes(style) linedc.SetPen(self.pens[param]) linedc.DrawLine(0,10,40,10) self.param_bitmap[param] = wx.StaticBitmap(self.control_panel,-1,self.linebitmap[param]) self.control_sizer.Add(self.param_bitmap[param]) #Enable the default plot parameters for param in self.state.default_plot: self.check_boxes[param].SetValue(True) def _colour_control(self): ''' updates the colours of the control elements ''' selected = self.get_selected_parameters() for param in self.state.attributes: if param in selected: self.param_text[param].Enable() self.param_bitmap[param].Enable() else: self.param_text[param].Disable() #self.param_bitmap[param].Disable() def _update_line_styles(self): ''' Update the colour and style associated with each unit and parameter ''' self.unit_colour = {} self.parameter_style = {} #For tracking the number of parameters per unit unit_count = {} #Determine colours for units for unit in self.state.unit_order: self.unit_colour[unit] = self.line_colours[len(self.unit_colour)] unit_count[unit] = 0 #Determine line styles for parameters for param in self.state.attribute_order: unit = self.state.get_attribute_units(param) print param, unit self.parameter_style[param] = self.line_styles[unit_count[unit]] unit_count[unit] += 1 def _select_parameters(self,parameters = [],redraw=True): '''Set the parameters to be plotted''' self.parameters = parameters if redraw: self.redraw_fromscratch() def update_visibility(self): if SIM_TYPE == SIM_STATIC: enabled = False else: enabled = True self.check_boxes['discounted_profit'].Show(enabled) self.param_text['discounted_profit'].Show(enabled) self.param_bitmap['discounted_profit'].Show(enabled) def update_state(self,state,redraw=True): '''Update the state that is being plotted''' self.state = copy.deepcopy(state) if not hasattr(self,'last_parameters'): self.last_parameters = {} print self.state['discounted_profit'] import numpy self.npv = numpy.nansum(self.state['discounted_profit']) # discount_rate = 0.05 # for index in range(len(self.state['revenue'])): # if self.state['revenue'][index] != None and ~numpy.isnan(self.state['revenue'][index]): # self.npv += (self.state['revenue'][index]-self.state['cost'][index])*(1-discount_rate)**index if redraw: #Update the parameter selection controls if necessary if state.attributes != self.last_parameters: self._setup_control_panel() self.last_parameters = state.attributes self.redraw() def _update_bounds(self): '''Update the figure bounds''' def sig_round(number): '''Ceil a number to a nice round figure for limits''' if number == 0: return 0 sig = number/(10**numpy.floor(numpy.log10(number*2))) if sig < 2: factor_multiple = 2.0 elif sig < 5: factor_multiple = 2.0 else: factor_multiple = 1.0 factor = 10**(numpy.floor(numpy.log10(number*factor_multiple)))/factor_multiple rounded = numpy.ceil(number/factor)*factor print number, rounded return rounded self.xbound = 0 self.bounds = {} for unit in self._get_units(): self.bounds[unit]=[float('inf'), -float('inf')] for param in self.get_selected_parameters(): unit = self.state.get_attribute_units(param) yv = numpy.asarray(self.state[param])/self.state.attributes[param]['scale'] self.bounds[unit][0] = min(self.bounds[unit][0], numpy.nanmin(yv)) self.bounds[unit][1] = max(self.bounds[unit][1], numpy.nanmax(yv)) self.bounds[unit][0] = sig_round(self.bounds[unit][0]) self.bounds[unit][1] = sig_round(self.bounds[unit][1]) if SIM_TYPE == SIM_DYNAMIC: self.xbound = max(self.xbound,len(self.state[param])-1) if SIM_TYPE == SIM_STATIC: if MG_TYPE == MG_QUOTA: self.xbound = numpy.nanmax(numpy.asarray(self.state['catch'])/self.state.attributes['catch']['scale']) else: self.xbound = numpy.nanmax(numpy.asarray(self.state['effort'])/self.state.attributes['effort']['scale']) self.xbound = sig_round(self.xbound) def get_selected_parameters(self): '''Return the parameters that have been selected for plotting''' out = [] for param in self.state.attribute_order: if self.check_boxes[param].GetValue(): out.append(param) return out def _get_units(self): ''' Returns a list of units that will be plotted ''' units = {} for param in self.get_selected_parameters(): units[self.state.get_attribute_units(param)]=1 return units.keys() def _setup_axes(self): ''' Redraw the figure from scratch required if the number of axes etc. have changed ''' #Clear the figure self.fig.clf() #Add the new axes self.axes = {} self.plot_data = {} self.axes_xscale = {} max_width = 0.87 width_increment = 0.07 bottom_space = .13 pos=[.05, bottom_space, max_width-width_increment*(len(self._get_units())-1), 1-bottom_space-0.05] #Create the axes, one for each unit for unit in self._get_units(): first_figure = len(self.axes)==0 colour = self.unit_colour[unit] self.axes[unit] = self.fig.add_axes(pos,frameon=True,label=unit) self.axes[unit].yaxis.tick_right() self.axes[unit].yaxis.set_label_position('right') self.axes[unit].set_ylabel(unit) self.axes_xscale[unit] = pos[2]/(max_width-width_increment*(len(self._get_units())-1)) if not first_figure: self.axes[unit].patch.set_alpha(0) else: self.firstaxes = self.axes[unit] self.axes[unit].set_xlabel('Years') self._modify_axes(self.axes[unit],colour,not first_figure) pos[2] += width_increment #Create the plot lines, one for each parameter for param in self.get_selected_parameters(): unit = self.state.get_attribute_units(param) colour = self.unit_colour[unit] style = self.parameter_style[param] self.plot_data[param] = self.axes[unit].plot([0,0],[0,0],linewidth=2)[0] self.plot_data[param].set_color(colour) self.plot_data[param].set_dashes(style) #Text for npv self.npvtext = self.fig.text(.1,bottom_space,'NPV') def redraw(self,event=None,redraw=False): ''' Update the plots using data in the current state ''' if self.state == None: return if not hasattr(self,'last_selected_parameters'): self.last_selected_parameters = {} #If the selected parameters have changed we need new axes if self.last_selected_parameters != self.get_selected_parameters() or redraw: self.last_selected_parameters = self.get_selected_parameters() self._colour_control() self._setup_axes() self._update_bounds() #Update axes bounds for unit in self._get_units(): bounds = self.bounds[unit] self.axes[unit].set_ybound(lower = 0,upper = bounds[1]) self.axes[unit].set_xbound(lower = 0,upper=self.xbound*self.axes_xscale[unit]) #Update plot data for param in self.get_selected_parameters(): data = self.state[param] if SIM_TYPE == SIM_DYNAMIC: self.plot_data[param].set_xdata(range(len(data))) else: if MG_TYPE == MG_QUOTA: self.plot_data[param].set_xdata(numpy.asarray(self.state['catch'])/self.state.attributes['catch']['scale']) else: self.plot_data[param].set_xdata(numpy.asarray(self.state['effort'])/self.state.attributes['effort']['scale']) self.plot_data[param].set_ydata(numpy.asarray(data)/self.state.attributes[param]['scale']) if SIM_TYPE == SIM_DYNAMIC: self.firstaxes.set_xlabel('Years') else: if MG_TYPE == MG_QUOTA: xunit = 'catch' else: xunit = 'effort' self.firstaxes.set_xlabel('Management Control: ' + self.state.attributes[xunit]['title'] + ' (' + self.state.attributes[xunit]['units'] + ')') if SIM_TYPE == SIM_DYNAMIC and ~numpy.isnan(self.npv): self.npvtext.set_text('NPV: $' + str(int(round(self.npv/self.state.attributes['revenue']['scale']))) + ' million') else: self.npvtext.set_text('') self.canvas.draw() @staticmethod def _modify_axes(axes,color,remove = False): ''' Set the colour of the y axis to color and optionally remove the remaining borders of the graph ''' def modify_all(object,color=None,remove=False): for child in object.get_children(): modify_all(child,color,remove) if remove and hasattr(object,'set_visible'): object.set_visible(not remove) if color != None and hasattr(object,'set_color'): object.set_color(color) for child in axes.get_children(): if isinstance(child, matplotlib.spines.Spine): if child.spine_type == 'right': modify_all(child,color=color) elif remove == True: modify_all(child,remove=True) modify_all(axes.yaxis,color=color) if remove: modify_all(axes.xaxis,remove=True) class AboutBox(wx.Dialog): '''An about dialog box, which displays a html file''' replacements = {'_VERSION_': VERSIONSTRING} def __init__(self,parent,title,filename): ''' parent: parent window title: dialog box title filename: the html file to show ''' wx.Dialog.__init__(self,parent,-1,title,size=(500,550)) #Read the html source file fid = open(filename,'r') self.abouthtml = fid.read() fid.close() #Replace tokens for key in self.replacements.keys(): self.abouthtml = self.abouthtml.replace(key,self.replacements[key]) self.html = wx.html.HtmlWindow(self) self.html.SetPage(self.abouthtml) self.ok_button = wx.Button(self,wx.ID_OK,"Ok") self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.html,1,wx.EXPAND|wx.ALL,5) self.sizer.Add(self.ok_button,0,wx.ALIGN_CENTER|wx.ALL,5) self.SetSizer(self.sizer) self.Layout() x=1366 y=768 class App(wx.App): def OnInit(self): self.frame = Frame(x,y) self.SetTopWindow(self.frame) self.frame.Show() self.frame.Layout() return True if __name__ == '__main__': app = App(redirect=False) # app = App(redirect=False) app.MainLoop()
Python
#By running "python setup.py py2exe" this script generates a windows stand-alone #distribution of the Fisheries Explorer #Copyright 2010, University of Tasmania, Australian Seafood CRC #This program is released under the Open Software License ("OSL") v. 3.0. See OSL3.0.htm for details. from distutils.core import setup import py2exe import matplotlib import shutil # Remove the build folder shutil.rmtree("build", ignore_errors=True) # do the same for dist folder shutil.rmtree("dist", ignore_errors=True) data_files = matplotlib.get_py2exe_datafiles() data_files += ['OSL3.0.htm','about.html',('images',["images/fishnet.ico","images/seafoodcrc.png",'images/fishnet.png','images/about.png','images/fish.png'])] dll_excludes = ['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll', 'tk84.dll', 'MSVCP90.dll', 'mswsock.dll', 'powrprof.dll'] excludes = ['_gtkagg' ] setup( windows = [ { "script": "fisheries_gui.py", "icon_resources": [(1, "images\\fishnet.ico")], #"other_resources": [(24,1,manifest)] } ], options = {"py2exe": { 'excludes': excludes, 'includes': ['matplotlib.backends.backend_tkagg','unittest','inspect'], "dll_excludes": dll_excludes, # "compressed": 2, # "optimize": 2, # "bundle_files": 2, # "xref": False, # "skip_archive": False, # "ascii": False, # "custom_boot_script": '' } }, data_files=data_files )
Python
#!/usr/bin/env python """ Fisheries Economics Masterclass GUI Klaas Hartmann 2010 Copyright 2010, University of Tasmania, Australian Seafood CRC This program is released under the Open Software License ("OSL") v. 3.0. See OSL3.0.htm for details. """ import wx import wx.html import fisheries_model import colourblind import matplotlib #matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import \ FigureCanvasWxAgg as FigCanvas import numpy import copy import os import sys #String constants for some menus etc MG_QUOTA='Output Controlled' MG_EFFORT='Input Controlled' SIM_DYNAMIC='Dynamic' SIM_STATIC='Static (Equilibrium)' #Version history: #1.00 Initial release from Hobart Class 1 #1.01 Made fishery crash instantaneous. #1.02 Initial version on Google Code #1.03 Included licencing information VERSIONSTRING = '1.03' #Globals that specify the current simulation and management type #(to be subsumed at a later stage...) SIM_TYPE='' MG_TYPE='' class Frame(wx.Frame): '''The main (only?) GUI Frame''' def __init__(self,width,height): wx.Frame.__init__(self, None, size=wx.Size(width,height), title = 'Fisheries Explorer') #self.SetSize(wx.Size(width,height)) #Set the starting simulation and management types global SIM_TYPE global MG_TYPE MG_TYPE = MG_QUOTA SIM_TYPE = SIM_STATIC self.Maximize() #Initialise model components self._init_model() #Initialise model/graph update system self._init_update() #Initialise GUI components self._init_gui() def _init_update(self): '''Initialise model/graph update system''' #Will contain current parameters self.parameters= {} #Will contain last parameters for which the model run was completed self.computed_parameters = {} #Will contain last parameters for which a graph was produced self.plotted_parameters = {} #Whether current computation has been completed self.computed_complete = True #Timer for model reruns self.timer_model = wx.Timer(self) self.timer_model.Start(250) wx.EVT_TIMER(self,self.timer_model.GetId(),self.on_timer_model) #Hack to call layout after init self.timer_init_hack = wx.Timer(self) self.timer_init_hack.Start(250) wx.EVT_TIMER(self,self.timer_init_hack.GetId(),self.on_timer_init_hack) #The model execution thread self.model_thread = fisheries_model.MultiThreadModelRun(self.model_data_updater) def _init_model(self,type='catch'): '''Initialise model''' self.model = fisheries_model.lobsterModel(control_type = type) def _init_gui(self): '''Initialise GUI components''' #Setup sizers (in hierarchical order) self.sizer = wx.FlexGridSizer(rows=2,cols=1) #Create wx objects self.parameter_panel = ParameterPanel(self,self.model,sim_update_fx=self.on_simulation_change) self.plot_panel = PlotPanel(self) #Set up main sizer self.sizer.Add(self.parameter_panel,0,wx.EXPAND) self.sizer.Add(self.plot_panel,0,wx.EXPAND) self.sizer.AddGrowableCol(0,1) self.sizer.AddGrowableRow(1,1) #Set sizers self.SetSizer(self.sizer) #Set menu self.menubar = MenuBar(self,sim_update_fx=self.on_simulation_change,parameter_type_fx=self.parameter_panel.show_parameter_set,reset_model_fx=self.on_simulation_change) self.SetMenuBar(self.menubar) self.menubar.set_parameter_types(self.model.get_parameter_types()) #Bind events self.Bind(wx.EVT_SCROLL,self.on_slide_change) #self.Bind(wx.EVT_CLOSE, self.onCloseWindow) self.on_slide_change(None) self.on_timer_model(None) #Prevent the frame getting resized too small min_size = self.sizer.GetMinSize() self.SetMinSize(min_size) #Set the icon self.icon = wx.Icon(os.path.join('images','fishnet.ico'),wx.BITMAP_TYPE_ICO) self.SetIcon(self.icon) #It still doesn't close cleanly for some unknown reason.. block = False def onCloseWindow(self,event): self.timer_model.Stop() self.timer_model.Destroy() self.icon.Destroy() event.Skip() def on_timer_model(self,event): '''Rerun the model if parameters have changed''' #If parameters have changed we need to recalculate the model if self.parameters != self.computed_parameters: self.computed_complete=False self.model.set_parameters(self.parameter_panel.get_parameters()) self.model.reset() #Run the appropriate simulation if SIM_TYPE == SIM_STATIC: if MG_TYPE == MG_QUOTA: max= self.parameters['K']*self.parameters['r']/4*1.01 self.model_thread.run(self.model,20,dynamic=False,independent_variable='catch',independent_maximum=max) else: self.model_thread.run(self.model,20,dynamic=False,independent_variable='effort',independent_maximum=6e6) else: self.model_thread.run(self.model,20) self.computed_parameters = self.parameters init_hack_count = 0 def on_timer_init_hack(self,event): '''A hack to layout the plot panel after load. For some reason the legend is not displayed correctly.''' if self.init_hack_count > 0: self.timer_init_hack.Stop() self.init_hack_count += 1 self.plot_panel.update_visibility() self.plot_panel.OnSize() self.plot_panel.Layout() def on_simulation_change(self,simulation_type,control_type): '''Called if the simulation type (static/dynamic, quota/effort controlled) changes''' global SIM_TYPE global MG_TYPE SIM_TYPE = simulation_type MG_TYPE = control_type #Initialise the model with appropriate control type if MG_TYPE == MG_QUOTA: self._init_model('catch') else: self._init_model('effort') self.computed_parameters = None self.parameter_panel.set_model(self.model) self.plot_panel.update_visibility() self.plot_panel.Layout() self.on_timer_model(None) def on_slide_change(self,event): '''Get the latest set of parameters if the sliders have been moved''' #Store the latest set of parameters # if event.GetEventObject() in self.parameter_panel.GetChildren(): self.parameters = self.parameter_panel.get_parameters() def model_data_updater(self,state): self.computed_complete=True self.model.state = state self.plot_panel.update_state(self.model.state) min_size = self.sizer.GetMinSize() self.SetMinSize(min_size) class MenuBar(wx.MenuBar): def __init__(self,parent_frame,sim_update_fx=None,parameter_type_fx=None,reset_model_fx=None): wx.MenuBar.__init__(self) self.sim_update_fx = sim_update_fx self.parameter_type_fx=parameter_type_fx self.reset_model_fx = reset_model_fx self.parent_frame = parent_frame self.scenario_menu = wx.Menu() self.reset_model = self.scenario_menu.Append(-1,'Reset Model') self.scenario_menu.Append(-1,' ').Enable(False) self.scenario_menu.AppendRadioItem(-1,'Rock Lobster Fishery') self.scenario_menu.Append(-1,' ').Enable(False) self.static_simulation = self.scenario_menu.AppendRadioItem(-1,SIM_STATIC) self.dynamic_simulation = self.scenario_menu.AppendRadioItem(-1,SIM_DYNAMIC) self.scenario_menu.Append(-1,' ').Enable(False) self.input_control = self.scenario_menu.AppendRadioItem(-1,MG_EFFORT) self.output_control = self.scenario_menu.AppendRadioItem(-1,MG_QUOTA) #Bring checks in line with initial simulation state if SIM_TYPE == SIM_STATIC: self.static_simulation.Check() else: self.dynamic_simulation.Check() if MG_TYPE == MG_QUOTA: self.output_control.Check() else: self.input_control.Check() self.parameter_menu = wx.Menu() self.parameter_items = [] self.help_menu = wx.Menu() self.about = self.help_menu.Append(-1,'About') self.license = self.help_menu.Append(-1,'License') self.Append(self.scenario_menu,'Model') self.Append(self.parameter_menu,'Parameters') self.Append(self.help_menu,'Help') parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.input_control) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.output_control) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.static_simulation) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.dynamic_simulation) parent_frame.Bind(wx.EVT_MENU, self.on_about,self.about) parent_frame.Bind(wx.EVT_MENU, self.on_license,self.license) parent_frame.Bind(wx.EVT_MENU, self.on_simulation_change, self.reset_model) def set_parameter_types(self,types): for item in self.parameter_items: self.parameter_menu.Delete(item) for type in ["All"]+types: self.parameter_items.append(self.parameter_menu.AppendRadioItem(-1,type)) self.parent_frame.Bind(wx.EVT_MENU, self.on_parameter_selection, self.parameter_items[-1]) if type == 'Management Controls': self.parameter_items[-1].Check() self.on_parameter_selection(None) def on_reset_model(self,event): '''Reset the model''' self.reset_model_fx() def on_parameter_selection(self,event): '''Called when a parameter set is selected''' for item in self.parameter_items: if item.IsChecked(): self.parameter_type_fx(item.GetText()) def on_simulation_change(self,event): if self.input_control.IsChecked(): control_type = MG_EFFORT else: control_type = MG_QUOTA if self.static_simulation.IsChecked(): simulation_type = SIM_STATIC else: simulation_type= SIM_DYNAMIC self.sim_update_fx(simulation_type = simulation_type, control_type = control_type) event.Skip() def on_about(self,event): '''About handler, shows modal AboutBox''' dlg = AboutBox(self.parent_frame,title='About Fisheries Explorer',filename='about.html') dlg.ShowModal() dlg.Destroy() def on_license(self,event): '''License handler, shows modal AboutBox''' dlg = AboutBox(self.parent_frame,title='Fisheries Explorer License',filename='OSL3.0.htm') dlg.ShowModal() dlg.Destroy() class ParameterPanel(wx.Panel): '''A panel for parameter input''' def __init__(self,parent,model = [],sim_update_fx=None): wx.Panel.__init__(self,parent) self.type_shown = 'All' self.model = model self.parameters = model.get_parameters() self._base_layout() self.set_model(model) self.sim_update_fx = sim_update_fx def set_model(self,model): '''Set the parameters displayed in the panel (expects a Parameter object)''' self.parameters = model.get_parameters() self.model = model self.parameter_layout() self.show_parameter_set() def _base_layout(self): #Empty lists for storing gui objects (to get parameter values etc) self.label_parameters = {} self.label_param_values = {} self.slider_parameters = {} self.sizer = wx.FlexGridSizer(rows=1,cols=2) self.sizer.AddGrowableCol(1,1) self.SetSizer(self.sizer) self.set_panel = wx.Panel(self) self.set_sizer = wx.FlexGridSizer(rows=3,cols=1) self.set_panel.SetSizer(self.set_sizer) self.control_panel = wx.Panel(self) self.control_sizer = wx.FlexGridSizer(rows=len(self.parameters),cols=3) self.control_sizer.AddGrowableCol(1,1) self.control_panel.SetSizer(self.control_sizer) self.sizer.Add(self.set_panel,0) self.sizer.Add(self.control_panel,0,flag=wx.EXPAND) if False: #Drop down box for choosing parameter types self.set_sizer.Add(wx.StaticText(self.set_panel,label='Parameter Set:')) self.parameter_choice = wx.Choice(self.set_panel,1) self.set_sizer.Add(self.parameter_choice) #Set selection items items = self.model.get_parameter_types() items.insert(0,'ALL') self.parameter_choice.SetItems(items) self.parameter_choice.SetSelection(0) if False: self.static_toggle = wx.RadioBox(self.set_panel,1,"Simulation Type",choices=[SIM_STATIC,SIM_DYNAMIC]) self.management_toggle = wx.RadioBox(self.set_panel,1,"Management Type",choices=[MG_EFFORT,MG_QUOTA]) self.set_sizer.Add(self.static_toggle) self.set_sizer.Add(self.management_toggle) self.Bind(wx.EVT_CHOICE,self.on_selection_change) self.Bind(wx.EVT_RADIOBOX,self.on_simulation_change) def parameter_layout(self): #Delete all existing objects if hasattr(self,'control_sizer'): self.control_sizer.Clear(True) #Create the caption, value and slider for each parameter count = 0 for param in self.parameters: p = self.parameters[param] self.label_parameters[param]=wx.StaticText(self.control_panel,label=p['title']+':') current_value = round((p['value']-p['min'])/float(p['max']-p['min'])*1000) self.slider_parameters[param]= wx.Slider(self.control_panel, -1, current_value, 0, 1000, wx.DefaultPosition, style= wx.SL_HORIZONTAL) self.label_param_values[param]=wx.StaticText(self.control_panel,label='') self.label_parameters[param].SetToolTipString(p['description']) self.slider_parameters[param].SetToolTipString(p['description']) self.control_sizer.Add(self.label_parameters[param],0,flag=wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT) self.control_sizer.Add(self.slider_parameters[param],0,flag=wx.EXPAND) self.control_sizer.Add(self.label_param_values[param],0,flag=wx.ALIGN_LEFT) count += 1 self.on_slide_change(None) self.Bind(wx.EVT_SCROLL,self.on_slide_change) def on_simulation_change(self,event): self.sim_update_fx(simulation_type = self.static_toggle.GetStringSelection(), control_type = self.management_toggle.GetStringSelection()) def on_selection_change(self,event): '''Update parameter list when a different parameter set is selected''' type = self.parameter_choice.GetItems()[self.parameter_choice.GetSelection()] self.show_parameter_set(type) def show_parameter_set(self,type=None): '''Show parameters of type''' #If type is unspecified we show the same parameter set if type != None: self.type_shown = type type = self.type_shown #Show the selected parameters for param in self.parameters: selected =((type == 'ALL' or type == 'All' or self.parameters[param]['type'] == type) and (SIM_TYPE == SIM_DYNAMIC or self.parameters[param]['type'] != 'Management Controls')) if SIM_TYPE == SIM_STATIC and param == 'discount_rate': selected = False self.label_param_values[param].Show(selected) self.label_parameters[param].Show(selected) self.slider_parameters[param].Show(selected) self.Fit() self.GetParent().Layout() def on_slide_change(self,event): '''Slider change event updates value label''' param_values = self.get_parameters() for param in (param_values): scale_text = '' if self.parameters[param]['scale_text'] != '': scale_text = ' (' + self.parameters[param]['scale_text'] + ')' self.label_param_values[param].SetLabel(str(param_values[param]/self.parameters[param]['scale'])+ ' ' + self.parameters[param]['units'] + scale_text) self.Layout() #Propagate the event so that the frame can process it if event != None: event.Skip() def get_parameters(self): '''Get a dict of the current parameter values''' out = {} for param in self.parameters: p = self.parameters[param] out[param] = float(self.slider_parameters[param].GetValue())/1000.0*(p['max']-p['min'])+p['min'] return out def set_parameters(self,parameter_values): '''Update parameters from a dict''' out = {} for param in parameter_values.keys(): if self.parameters.has_key(param): v = parameter_values[param] p = self.parameters[param] self.slider_parameters[param].SetValue(int((v-p['min'])/(p['max']-p['min'])*1000)) self.on_slide_change(None) class PlotPanel(wx.Panel): line_colours = colourblind.rgbScaled line_styles = [[127,1], #solid [5,5], #dashed [20,20,2,20], #dash-dot [2,2,2,2] #dotted ] def __init__(self,parent): wx.Panel.__init__(self,parent) self.last_redraw_size = [] self.fig = Figure() self.fig.set_facecolor([1,1,1]) self.control_panel = wx.Panel(self) self.canvas_panel = wx.Panel(self) self.canvas = FigCanvas(self.canvas_panel,wx.ID_ANY,self.fig) self.sizer = wx.FlexGridSizer(rows=1,cols=2,hgap=5,vgap=5) self.sizer.Add(self.canvas_panel,flag=wx.EXPAND) self.sizer.Add(self.control_panel,flag=wx.ALIGN_CENTER|wx.ALL) self.sizer.AddGrowableCol(0,1) self.sizer.AddGrowableRow(0,1) self.SetSizer(self.sizer) self.control_sizer = wx.FlexGridSizer(hgap=5,vgap=5) self.control_panel.SetSizer(self.control_sizer) self.control_panel.Bind(wx.EVT_CHECKBOX,self.redraw) # self.canvas.SetAutoLayout(True) self.canvas_panel.SetMinSize([600,300]) self.state = None self.bounds = {} self.xbound = 0 self.SetBackgroundColour(wx.WHITE) self.canvas_panel.SetBackgroundColour(wx.WHITE) self.control_panel.SetBackgroundColour(wx.WHITE) self.canvas_panel.Bind(wx.EVT_SIZE, self.OnSize) self.Fit() def OnSize(self,event=None,size=None): if event == None and size == None: size = self.canvas_panel.GetClientSize() elif event != None and size == None: size = event.GetSize() #If the size has actually changed we redraw (several events may #be intercepted here per resize) if size != self.last_redraw_size: self.last_redraw_size = size self.fig.set_figwidth(size[0]/(1.0*self.fig.get_dpi())) self.fig.set_figheight(size[1]/(1.0*self.fig.get_dpi())) self.canvas.SetClientSize(size) self.redraw(None, redraw=True) if event != None: event.Skip() def _setup_control_panel(self): self._update_line_styles() #Remove existing widgets self.control_sizer.Clear(True) parameters = self.state.attribute_order self.control_sizer.SetRows(len(parameters)) self.control_sizer.SetCols(3) #Column Labels if False: self.control_sizer.SetRows(len(parameters)+1) column_labels = ['Plot','Parameter','Style'] for col in range(len(column_labels)): self.control_sizer.Add(wx.StaticText(self.control_panel,-1,column_labels[col])) self.check_boxes = {} self.param_text = {} self.param_bitmap = {} self.pens = {} self.colours = {} self.linedc = {} self.linebitmap = {} # self.check_boxes = {} linedc = wx.MemoryDC() for param in parameters: rgbcolour = self.unit_colour[self.state.get_attribute_units(param)] self.colours[param] = wx.Colour(rgbcolour[0]*255,rgbcolour[1]*255,rgbcolour[2]*255) style = self.parameter_style[param] #Add the check box self.check_boxes[param] = wx.CheckBox(self.control_panel,-1,'') self.control_sizer.Add(self.check_boxes[param]) #Add the description self.param_text[param] = wx.StaticText(self.control_panel,-1,self.state.get_attribute_title(param)) self.control_sizer.Add(self.param_text[param]) self.param_text[param].SetForegroundColour(self.colours[param]) self.param_text[param].Refresh() #Add the linestyle self.linebitmap[param] = wx.EmptyBitmap(40,20) linedc.SelectObject(self.linebitmap[param]) linedc.Clear() self.pens[param] = wx.Pen(colour = self.colours[param], width = 1,style = wx.USER_DASH) self.pens[param].SetDashes(style) linedc.SetPen(self.pens[param]) linedc.DrawLine(0,10,40,10) self.param_bitmap[param] = wx.StaticBitmap(self.control_panel,-1,self.linebitmap[param]) self.control_sizer.Add(self.param_bitmap[param]) #Enable the default plot parameters for param in self.state.default_plot: self.check_boxes[param].SetValue(True) def _colour_control(self): ''' updates the colours of the control elements ''' selected = self.get_selected_parameters() for param in self.state.attributes: if param in selected: self.param_text[param].Enable() self.param_bitmap[param].Enable() else: self.param_text[param].Disable() #self.param_bitmap[param].Disable() def _update_line_styles(self): ''' Update the colour and style associated with each unit and parameter ''' self.unit_colour = {} self.parameter_style = {} #For tracking the number of parameters per unit unit_count = {} #Determine colours for units for unit in self.state.unit_order: self.unit_colour[unit] = self.line_colours[len(self.unit_colour)] unit_count[unit] = 0 #Determine line styles for parameters for param in self.state.attribute_order: unit = self.state.get_attribute_units(param) print param, unit self.parameter_style[param] = self.line_styles[unit_count[unit]] unit_count[unit] += 1 def _select_parameters(self,parameters = [],redraw=True): '''Set the parameters to be plotted''' self.parameters = parameters if redraw: self.redraw_fromscratch() def update_visibility(self): if SIM_TYPE == SIM_STATIC: enabled = False else: enabled = True self.check_boxes['discounted_profit'].Show(enabled) self.param_text['discounted_profit'].Show(enabled) self.param_bitmap['discounted_profit'].Show(enabled) def update_state(self,state,redraw=True): '''Update the state that is being plotted''' self.state = copy.deepcopy(state) if not hasattr(self,'last_parameters'): self.last_parameters = {} print self.state['discounted_profit'] import numpy self.npv = numpy.nansum(self.state['discounted_profit']) # discount_rate = 0.05 # for index in range(len(self.state['revenue'])): # if self.state['revenue'][index] != None and ~numpy.isnan(self.state['revenue'][index]): # self.npv += (self.state['revenue'][index]-self.state['cost'][index])*(1-discount_rate)**index if redraw: #Update the parameter selection controls if necessary if state.attributes != self.last_parameters: self._setup_control_panel() self.last_parameters = state.attributes self.redraw() def _update_bounds(self): '''Update the figure bounds''' def sig_round(number): '''Ceil a number to a nice round figure for limits''' if number == 0: return 0 sig = number/(10**numpy.floor(numpy.log10(number*2))) if sig < 2: factor_multiple = 2.0 elif sig < 5: factor_multiple = 2.0 else: factor_multiple = 1.0 factor = 10**(numpy.floor(numpy.log10(number*factor_multiple)))/factor_multiple rounded = numpy.ceil(number/factor)*factor print number, rounded return rounded self.xbound = 0 self.bounds = {} for unit in self._get_units(): self.bounds[unit]=[float('inf'), -float('inf')] for param in self.get_selected_parameters(): unit = self.state.get_attribute_units(param) yv = numpy.asarray(self.state[param])/self.state.attributes[param]['scale'] self.bounds[unit][0] = min(self.bounds[unit][0], numpy.nanmin(yv)) self.bounds[unit][1] = max(self.bounds[unit][1], numpy.nanmax(yv)) self.bounds[unit][0] = sig_round(self.bounds[unit][0]) self.bounds[unit][1] = sig_round(self.bounds[unit][1]) if SIM_TYPE == SIM_DYNAMIC: self.xbound = max(self.xbound,len(self.state[param])-1) if SIM_TYPE == SIM_STATIC: if MG_TYPE == MG_QUOTA: self.xbound = numpy.nanmax(numpy.asarray(self.state['catch'])/self.state.attributes['catch']['scale']) else: self.xbound = numpy.nanmax(numpy.asarray(self.state['effort'])/self.state.attributes['effort']['scale']) self.xbound = sig_round(self.xbound) def get_selected_parameters(self): '''Return the parameters that have been selected for plotting''' out = [] for param in self.state.attribute_order: if self.check_boxes[param].GetValue(): out.append(param) return out def _get_units(self): ''' Returns a list of units that will be plotted ''' units = {} for param in self.get_selected_parameters(): units[self.state.get_attribute_units(param)]=1 return units.keys() def _setup_axes(self): ''' Redraw the figure from scratch required if the number of axes etc. have changed ''' #Clear the figure self.fig.clf() #Add the new axes self.axes = {} self.plot_data = {} self.axes_xscale = {} max_width = 0.87 width_increment = 0.07 bottom_space = .13 pos=[.05, bottom_space, max_width-width_increment*(len(self._get_units())-1), 1-bottom_space-0.05] #Create the axes, one for each unit for unit in self._get_units(): first_figure = len(self.axes)==0 colour = self.unit_colour[unit] self.axes[unit] = self.fig.add_axes(pos,frameon=True,label=unit) self.axes[unit].yaxis.tick_right() self.axes[unit].yaxis.set_label_position('right') self.axes[unit].set_ylabel(unit) self.axes_xscale[unit] = pos[2]/(max_width-width_increment*(len(self._get_units())-1)) if not first_figure: self.axes[unit].patch.set_alpha(0) else: self.firstaxes = self.axes[unit] self.axes[unit].set_xlabel('Years') self._modify_axes(self.axes[unit],colour,not first_figure) pos[2] += width_increment #Create the plot lines, one for each parameter for param in self.get_selected_parameters(): unit = self.state.get_attribute_units(param) colour = self.unit_colour[unit] style = self.parameter_style[param] self.plot_data[param] = self.axes[unit].plot([0,0],[0,0],linewidth=2)[0] self.plot_data[param].set_color(colour) self.plot_data[param].set_dashes(style) #Text for npv self.npvtext = self.fig.text(.1,bottom_space,'NPV') def redraw(self,event=None,redraw=False): ''' Update the plots using data in the current state ''' if self.state == None: return if not hasattr(self,'last_selected_parameters'): self.last_selected_parameters = {} #If the selected parameters have changed we need new axes if self.last_selected_parameters != self.get_selected_parameters() or redraw: self.last_selected_parameters = self.get_selected_parameters() self._colour_control() self._setup_axes() self._update_bounds() #Update axes bounds for unit in self._get_units(): bounds = self.bounds[unit] self.axes[unit].set_ybound(lower = 0,upper = bounds[1]) self.axes[unit].set_xbound(lower = 0,upper=self.xbound*self.axes_xscale[unit]) #Update plot data for param in self.get_selected_parameters(): data = self.state[param] if SIM_TYPE == SIM_DYNAMIC: self.plot_data[param].set_xdata(range(len(data))) else: if MG_TYPE == MG_QUOTA: self.plot_data[param].set_xdata(numpy.asarray(self.state['catch'])/self.state.attributes['catch']['scale']) else: self.plot_data[param].set_xdata(numpy.asarray(self.state['effort'])/self.state.attributes['effort']['scale']) self.plot_data[param].set_ydata(numpy.asarray(data)/self.state.attributes[param]['scale']) if SIM_TYPE == SIM_DYNAMIC: self.firstaxes.set_xlabel('Years') else: if MG_TYPE == MG_QUOTA: xunit = 'catch' else: xunit = 'effort' self.firstaxes.set_xlabel('Management Control: ' + self.state.attributes[xunit]['title'] + ' (' + self.state.attributes[xunit]['units'] + ')') if SIM_TYPE == SIM_DYNAMIC and ~numpy.isnan(self.npv): self.npvtext.set_text('NPV: $' + str(int(round(self.npv/self.state.attributes['revenue']['scale']))) + ' million') else: self.npvtext.set_text('') self.canvas.draw() @staticmethod def _modify_axes(axes,color,remove = False): ''' Set the colour of the y axis to color and optionally remove the remaining borders of the graph ''' def modify_all(object,color=None,remove=False): for child in object.get_children(): modify_all(child,color,remove) if remove and hasattr(object,'set_visible'): object.set_visible(not remove) if color != None and hasattr(object,'set_color'): object.set_color(color) for child in axes.get_children(): if isinstance(child, matplotlib.spines.Spine): if child.spine_type == 'right': modify_all(child,color=color) elif remove == True: modify_all(child,remove=True) modify_all(axes.yaxis,color=color) if remove: modify_all(axes.xaxis,remove=True) class AboutBox(wx.Dialog): '''An about dialog box, which displays a html file''' replacements = {'_VERSION_': VERSIONSTRING} def __init__(self,parent,title,filename): ''' parent: parent window title: dialog box title filename: the html file to show ''' wx.Dialog.__init__(self,parent,-1,title,size=(500,550)) #Read the html source file fid = open(filename,'r') self.abouthtml = fid.read() fid.close() #Replace tokens for key in self.replacements.keys(): self.abouthtml = self.abouthtml.replace(key,self.replacements[key]) self.html = wx.html.HtmlWindow(self) self.html.SetPage(self.abouthtml) self.ok_button = wx.Button(self,wx.ID_OK,"Ok") self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.html,1,wx.EXPAND|wx.ALL,5) self.sizer.Add(self.ok_button,0,wx.ALIGN_CENTER|wx.ALL,5) self.SetSizer(self.sizer) self.Layout() x=1366 y=768 class App(wx.App): def OnInit(self): self.frame = Frame(x,y) self.SetTopWindow(self.frame) self.frame.Show() self.frame.Layout() return True if __name__ == '__main__': app = App(redirect=False) # app = App(redirect=False) app.MainLoop()
Python
#!/usr/bin/env python ''' Fisheries Economics Masterclass model Copyright 2010, University of Tasmania, Australian Seafood CRC This program is released under the Open Software License ("OSL") v. 3.0. See OSL3.0.htm for details. ''' import threading import wx from pylab import * import copy class Parameter(dict): """ Model parameter class A simple dict with some default values """ def __init__(self,value=0,min=0,max=1,units='',title='',description='',type='Miscellaneous',scale=1,scale_text=''): """Initialise the parameter""" self['value'] = value self['min'] = min self['max'] = max self['units'] = units self['title'] = title self['description'] = description self['type'] = type self['scale'] = scale self['scale_text']=scale_text class Component: """ Model component class All model classes should inherit this """ def get_parameters(self): """ Returns the parameters required by this component The format is a dictionary, keys are parameter name, value is a list of minimum value, maximum value, default value, """ return {} def execute(self,state,parameters): """Executes this component and returns the modified state""" return state class PDLogistic(Component): """Population Dynamics Logistic growth component""" def __init__(self): self.r = Parameter(title='Population growth rate', description='The maximum growth rate of the population', type='Population dynamics') self.K = Parameter(title='Maximum population size', description='The size of a unfished (virgin) population', type='Population dynamics') def get_parameters(self): return {'r': self.r,'K': self.K} #Execute a logistic step def execute(self,state,parameters,equilibrium=False): if equilibrium: r = parameters['r'] K = parameters['K'] if parameters.has_key('catch'): C = parameters['catch'] # [r-1 + (1-2r+r2+4Cr/K)^.5]/(2r/K) term = (r)**2-4*C*r/K #term = (1-4*parameters['catch']/parameters['r']/parameters['K']) if term < 0: state['biomass'][-1] = 0 else: #state['biomass'][-1] = parameters['K']/2*(1+term**0.5)#+parameters['catch'] #Catch is added back on as the catch step removes it state['biomass'][-1] = (r+term**.5)/(2*r/K) state['biomass'][-1] += parameters['catch'] #Catch is added back on as the catch step removes it else: catch = state['biomass'][-1]* parameters['catch_rate']*parameters['effort']/parameters['K'] state['biomass'][-1] = parameters['K']-parameters['catch_rate']*parameters['effort']/parameters['r'] state['biomass'][-1] += catch #state['biomass'][-1] = K*(1-r) else: b = state['biomass'][-1] state['biomass'][-1] = b+b*parameters['r']*(1-b/parameters['K']) return state #Catch component removes catch determines CPUE class CatchFixed(Component): """Fixed catch component with simplistic CPUE/effort calculation""" catch_rate = Parameter(title='Max catch rate', description='The biomass caught per unit of effort', type='Fleet dynamics') catch = Parameter(title='TAC', description='Total allowable catch', type='Management Controls' ) def get_parameters(self): return {'catch_rate': self.catch_rate, 'catch': self.catch} def execute(self,state,parameters,equilibrium=False): preCatchBiomass = state.get('biomass') previousBiomass = state['biomass'][-2] state.set(cpue=previousBiomass/parameters['K']*parameters['catch_rate']) state.set(biomass=preCatchBiomass-parameters['catch']) state.set(catch=parameters['catch']) if state.get('biomass') < 0: state.set(biomass=0,catch= preCatchBiomass) if state.get('cpue') <= 0: state.set(effort=0) else: state.set(effort=state.get('catch')/state.get('cpue')) return state #Constant effort class EffortFixed(Component): """Fixed catch component with simplistic CPUE/effort calculation""" catch_rate = Parameter(title='Max catch rate', description='The biomass caught per unit of effort', type='Fleet dynamics') effort = Parameter( title='Effort', description='Fishing effort', type='Management Controls' ) def get_parameters(self): return {'catch_rate': self.catch_rate, 'effort': self.effort} def execute(self,state,parameters,equilibrium=False): previousBiomass = state['biomass'][-2] preCatchBiomass = state['biomass'][-1] state.set(cpue=previousBiomass/parameters['K']*parameters['catch_rate']) state.set(catch=parameters['effort']*state.get('cpue')) state.set(biomass=preCatchBiomass-state.get('catch')) if state.get('biomass') < 0: state.set(biomass=0,catch= preCatchBiomass) state.set(effort=parameters['effort']) return state class Economics(Component): fixed_cost = Parameter( title='Operator fixed cost', description='An individual operator\s fixed annual cost', type='Economics') marginal_cost= Parameter( title='Operator marginal cost', description='An individual operator\s marginal cost per unit effort', type='Economics') movement_rate= Parameter( title='Fleet resize rate', description='The maximum rate at which vessels can enter or exit the fishery', type='Fleet dynamics') beach_price = Parameter( title='Beach price', description='The price per kg of landed fish', type='Economics') discount_rate = Parameter( title='Discount Rate', description='The discount rate', type='Economics') def get_parameters(self): return {'fixed_cost': self.fixed_cost, 'marginal_cost': self.marginal_cost, 'movement_rate': self.movement_rate, 'beach_price': self.beach_price, 'discount_rate': self.discount_rate} @staticmethod def _calculate_revenue(state,parameters): return state.get('catch')*parameters['beach_price'] @staticmethod def _calculate_cost(state,parameters): return (state.get('fleet_size')*parameters['fixed_cost']+\ state.get('effort')*parameters['marginal_cost']) @staticmethod def _calculate_profit(state,parameters): return Economics._calculate_revenue(state,parameters)-Economics._calculate_cost(state,parameters) def execute(self,state,parameters,equilibrium=False): #Adjust the fleet size original_fleet_size = state.get('fleet_size') while abs(self._calculate_profit(state,parameters))>parameters['fixed_cost'] and \ ((equilibrium and parameters['movement_rate'] > 0) or abs(original_fleet_size - state.get('fleet_size')) < parameters['movement_rate']): if self._calculate_profit(state,parameters) > 0: state.set(fleet_size = state.get('fleet_size')+1) else: state.set(fleet_size = state.get('fleet_size')-1) #Set the cost, revenue and profit state.set(cost = self._calculate_cost(state, parameters)) state.set(revenue = self._calculate_revenue(state,parameters)) profit = state.get('revenue')-state.get('cost') if abs(profit)<1000000: profit = 0 state.set(profit = profit) state.set(discounted_profit = profit*(1-parameters['discount_rate'])**(len(state['cost'])-2)) return state class State(dict): """Model state A dictionary where each key corresponds to an attribute of a fishery state (eg. biomass) all keys are the same length and can be extended trivially """ def __init__(self, attributes): """ Constructor attribute_list is a dictionary for the attributes of the fishery see example fishery models for details """ for key in attributes: self[key] = [nan] self.attributes = attributes self.attribute_order = self.attributes.keys() #The attributes to plot first up by default self.default_plot = self.attributes.keys() self.unit_order = [] units = {} for att in self.attributes: unit = self.attributes[att]['units'] if not units.has_key(unit): units[unit]=1 self.unit_order.append(unit) def extend(self): """Extend all the lists by one, using the previous value for the new value""" for att in self: self[att].append(self[att][-1]) return def set(self,**kwargs): """Set the current (last item) of one or more of the lists""" for key in kwargs: self[key][-1]=kwargs[key] def get(self,item): """Get the current (last item) of one of the lists""" return self[item][-1] def get_attribute_title(self,attribute): return self.attributes[attribute]['title'] def get_attribute_units(self,attribute): return self.attributes[attribute]['units'] def reset(self): """ Resets the state to the initial timestep """ for att in self: self[att]=self[att][0:1] return class Model(): """Model Definition By combining a set of model functions this class creates a complete model definition""" def __init__(self,functions=[],parameters={},initial_state = None,convergence_time=3): """ functions: a list of functions in the order that they are to be run parameters: a dict of parameters as required by the functions (can be set later) initial_state: initial state of the fishery convergence_time: number of steps required to convergence of static version """ if initial_state == None: self.state = State() else: self.state = initial_state self.functions = functions self.parameters = parameters self.convergence_time = convergence_time def get_parameters(self): """ returns a list of parameters as required by the model functions """ #Get all parameters pOut = {} for function in self.functions: pOut.update(function.get_parameters()) #Replace values with current if applicable for param in pOut: if self.parameters.has_key(param): pOut[param].value = self.parameters[param] return pOut def set_parameters(self,parameters): """ set the parameters to a given value for this and subsequent time steps """ self.parameters = parameters def get_parameter_types(self): """ return a list of parameter types """ types = {} p = self.get_parameters() for par in p: types[p[par]['type']] = 1 return types.keys() def set_state(self,state): """ set the state of the model """ self.state = state def reset(self): """ Resets the model state to the initial timestep """ self.state.reset() def run(self,steps = 1,constant_variable=None): """ run the model for one time step """ for step in range(0,steps): self.state.extend() for function in self.functions: self.state=function.execute(self.state,self.parameters,equilibrium=constant_variable!=None) class MultiThreadModelRun: class MyThread(threading.Thread): def __init__(self,function): '''Initialise the thread: function: a function to be called after run completion ''' threading.Thread.__init__(self) self.function = function self.update = False self.cancel_run = False def update_run(self,model,steps,options): '''Start a new run model: the model to use options: the run options ''' self.newmodel = copy.deepcopy(model) self.newsteps = steps self.newoptions = options self.update = True def run(self): '''The thread's run function''' import time while True: #Cancelling the thread's run for now if self.cancel_run: self.cancel_run = False self.update = False #Creating a new run if self.update: self.model = self.newmodel self.options = self.newoptions self.steps = self.newsteps self.update = False for step in range(0,self.steps): if self.update: break self.single_iteration(step) if not self.update: if not self.function==None: wx.CallAfter(self.function,self.output()) else: time.sleep(0.01) pass def cancel(self): '''Cancel this run''' self.update = True self.cancel_run = True def single_iteration(self,step): '''Perform a single iteration (to be implemented by inheriting class)''' pass def output(self): '''Return the model output (to be implemented by inheriting class)''' pass class DynamicThread(MyThread): '''Thread for dynamic model runs''' def single_iteration(self,step): '''Run a single time step''' self.model.run(1) def output(self): '''Return the model state''' return self.model.state class StaticThread(MyThread): '''Thread for static model runs''' def update_run(self,model,steps,options): '''Update the run, copying a new output state as well''' #MultiThreadModelRun.MyThread.update_run(self,model,steps,options) self.newmodel = copy.deepcopy(model) self.newsteps = steps self.newoptions = options self.update = True self.output_state = copy.deepcopy(self.newmodel.state) self.output_state.reset() def single_iteration(self,step): '''Find an equilibrium state for a single independent parameter value''' #Reset the model self.model.reset() #Set the independent value to the appropriate value self.model.state[self.options['independent_variable']] = [self.options['independent_values'][step]] self.model.parameters[self.options['independent_variable']] = self.options['independent_values'][step] self.model.run(self.options['convergence_time'],constant_variable = self.options['independent_variable']) if True: #self.model.state[self.options['independent_variable']][-1] == self.options['independent_values'][step]: for param in self.model.state.keys(): self.output_state[param].append(self.model.state[param][-1]) if self.model.state[self.options['independent_variable']][-1] < self.options['independent_values'][step]: print 'a' self.output_state[self.options['independent_variable']][-1] = self.options['independent_values'][step-1]+1e-6 # self.output_state[self.options['independent_variable']][-1] = self.options['independent_values'][step] def output(self): '''Return the output state''' return self.output_state def __init__(self,function=None): self.static_thread = self.StaticThread(function) self.static_thread.start() self.dynamic_thread = self.DynamicThread(function) self.dynamic_thread.start() def run(self,model,steps,dynamic=True,independent_variable='effort',independent_minimum = 0,independent_maximum = None,convergence_time=4): if dynamic: self.static_thread.cancel() self.dynamic_thread.update_run(model,steps,{}) else: self.dynamic_thread.cancel() self.static_thread.update_run(model,steps, { 'independent_variable': independent_variable, 'independent_values': linspace(independent_minimum,independent_maximum,steps), 'convergence_time':convergence_time}) def lobsterModel(control_type = 'catch'): '''A lobster model, loosely based on the Tasmanian Rock Lobster Fishery''' #------------------------------------------ #Parameter values customised for this model #------------------------------------------ r = {'value':1,'min':0,'max':2} K = {'value':7000000,'min':0,'max':10000000,'scale':1000,'units':'t'} catch_rate ={'value':1,'min':0.001,'max':5,'units':'kg/potlift'} catch = {'value':1500000,'min':0,'max':6000000,'scale':1000,'units':'t'} effort = {'value':1500000,'min':0,'max':5000000,'description':'Number of potlifts','scale':1e6,'scale_text':'millions'} fixed_cost ={'value':100000,'min':50000,'max':200000,'units':'$/year','scale':1000,'scale_text':'thousands'} marginal_cost= {'value':30,'min':5,'max':50,'units':'$/potlift'} movement_rate={'value':0,'min':0,'max':20,'units':'vessels/year'} beach_price = {'value':60,'min':0,'max':100,'units':'$/kg'} discount_rate = {'value':0.07,'min':0,'max':1,'units':''} #----------------------------------------- #Functions that control the model dynamics #----------------------------------------- #Discrete logistic growth growthClass = PDLogistic() growthClass.r.update(r) growthClass.K.update(K) #Catch component if control_type == 'catch': catchClass = CatchFixed() catchClass.catch.update(catch) elif control_type == 'effort': catchClass = EffortFixed() catchClass.effort.update(effort) catchClass.catch_rate.update(catch_rate) #Economics and fleet dynamics economicsClass = Economics() economicsClass.fixed_cost.update(fixed_cost) economicsClass.marginal_cost.update(marginal_cost) economicsClass.movement_rate.update(movement_rate) economicsClass.beach_price.update(beach_price) economicsClass.discount_rate.update(discount_rate) #----------------------------------------- #Set the state of the fishery #The attributes here must match what is #required by the functions PDLogistic, #CatchFixed/EffortFixed and Economics #----------------------------------------- initial_state = State( attributes = {'biomass': {'title': 'Biomass', 'units': 'tonnes','scale':1000}, 'catch': {'title': 'Catch', 'units': 'tonnes','scale':1000}, 'cpue': {'title': 'CPUE', 'units': 'kg/potlift','scale':1}, 'effort': {'title': 'Effort', 'units': 'millions of potlifts','scale':1e6}, 'fleet_size': {'title': 'Fleet Size','units': '# vessels','scale':1}, 'revenue': {'title': 'Revenue','units': '$ (millions)','scale':1e6}, 'cost': {'title': 'Cost','units': '$ (millions)','scale':1e6}, 'profit': {'title': 'Profit','units': '$ (millions)','scale':1e6}, 'discounted_profit': {'title': 'Discounted profit','units': '$ (millions)','scale':1e6}, }) initial_state.default_plot = ['biomass','catch'] # initial_state.default_plot = ['catch','revenue','cost','profit'] initial_state.attribute_order = ['biomass','catch','profit','revenue','cost','discounted_profit','cpue','effort','fleet_size'] #Set the initial fishery parameters initial_state.set(biomass=5000000,fleet_size=120) #----------------------------------------- #Create the fishery model #----------------------------------------- model = Model(functions = [growthClass,catchClass,economicsClass],initial_state = initial_state) return model
Python
import numpy as np # Colours and colourmaps that are readable by most colourblind people # Copyright 2010, University of Tasmania, Australian Seafood CRC # This program is released under the Open Software License ("OSL") v. 3.0. See OSL3.0.htm for details. #A set of safe plotting colours from http://jfly.iam.u-tokyo.ac.jp/color/ rgb = np.array([[0,0,0],[230,159,0],[86,180,233],[0,158,115],[240,228,66],[0,114,178],[213,94,0],[204,121,167]]) rgbScaled = rgb/255.0 #Colormaps from #A. Light & P.J. Bartlein, "The End of the Rainbow? Color Schemes for #Improved Data Graphics," Eos,Vol. 85, No. 40, 5 October 2004. #http://geography.uoregon.edu/datagraphics/EOS/Light&Bartlein_EOS2004.pdf def makeMap(inMap,name): import numpy import matplotlib inMap = numpy.array(inMap)/255.0 return matplotlib.colors.LinearSegmentedColormap.from_list(name,inMap) blueMap = makeMap([[243,246,248],[224,232,240],[171,209,236],[115,180,224],[35,157,213],[0,142,205],[0,122,192]],'cbBlue') blueGrayMap = makeMap([[0,170,227],[53,196,238],[133,212,234],[190,230,242],[217,224,230],[146,161,170],[109,122,129],[65,79,81]],'cbBlueGray') brownBlueMap = makeMap([[144,100,44],[187,120,54],[225,146,65],[248,184,139],[244,218,200],[241,244,245],[207,226,240],[160,190,225],[109,153,206],[70,99,174],[24,79,162]],'cbBrownBlue') redBlueMap = makeMap([[175,53,71],[216,82,88],[239,133,122],[245,177,139],[249,216,168],[242,238,197],[216,236,241],[154,217,238],[68,199,239],[0,170,226],[0,116,188]],'cbRedBlue')
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the "File Uploader" for Python """ import os from fckutil import * from fckcommands import * # default command's implementation from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorQuickUpload( FCKeditorConnectorBase, UploadFileCommandMixin, BaseHttpMixin, BaseHtmlMixin): def doResponse(self): "Main function. Process the request, set headers and return a string as response." # Check if this connector is disabled if not(Config.Enabled): return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"") command = 'QuickUpload' # The file type (from the QueryString, by default 'File'). resourceType = self.request.get('Type','File') currentFolder = "/" # Check for invalid paths if currentFolder is None: return self.sendUploadResults(102, '', '', "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendUploadResults( 1, '', '', 'Invalid type specified' ) # Setup paths self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFoldercreateServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here return self.uploadFile(resourceType, currentFolder) # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorQuickUpload() data = conn.doResponse() for header in conn.headers: if not header is None: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ from time import gmtime, strftime import string def escape(text, replace=string.replace): """ Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') return text def convertToXmlAttribute(value): if (value is None): value = "" return escape(value) class BaseHttpMixin(object): def setHttpHeaders(self, content_type='text/xml'): "Purpose: to prepare the headers for the xml to return" # Prevent the browser from caching the result. # Date in the past self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT') # always modified self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())) # HTTP/1.1 self.setHeader('Cache-Control','no-store, no-cache, must-revalidate') self.setHeader('Cache-Control','post-check=0, pre-check=0') # HTTP/1.0 self.setHeader('Pragma','no-cache') # Set the response format. self.setHeader( 'Content-Type', content_type + '; charset=utf-8' ) return class BaseXmlMixin(object): def createXmlHeader(self, command, resourceType, currentFolder, url): "Purpose: returns the xml header" self.setHttpHeaders() # Create the XML document header s = """<?xml version="1.0" encoding="utf-8" ?>""" # Create the main connector node s += """<Connector command="%s" resourceType="%s">""" % ( command, resourceType ) # Add the current folder node s += """<CurrentFolder path="%s" url="%s" />""" % ( convertToXmlAttribute(currentFolder), convertToXmlAttribute(url), ) return s def createXmlFooter(self): "Purpose: returns the xml footer" return """</Connector>""" def sendError(self, number, text): "Purpose: in the event of an error, return an xml based error" self.setHttpHeaders() return ("""<?xml version="1.0" encoding="utf-8" ?>""" + """<Connector>""" + self.sendErrorNode (number, text) + """</Connector>""" ) def sendErrorNode(self, number, text): if number != 1: return """<Error number="%s" />""" % (number) else: return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text)) class BaseHtmlMixin(object): def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ): self.setHttpHeaders("text/html") "This is the function that sends the results of the uploading process" "Minified version of the document.domain automatic fix script (#1919)." "The original script can be found at _dev/domain_fix_template.js" return """<script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s"); </script>""" % { 'errorNumber': errorNo, 'fileUrl': fileUrl.replace ('"', '\\"'), 'fileName': fileName.replace ( '"', '\\"' ) , 'customMsg': customMsg.replace ( '"', '\\"' ), }
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Utility functions for the File Manager Connector for Python """ import string, re import os import config as Config # Generic manipulation functions def removeExtension(fileName): index = fileName.rindex(".") newFileName = fileName[0:index] return newFileName def getExtension(fileName): index = fileName.rindex(".") + 1 fileExtension = fileName[index:] return fileExtension def removeFromStart(string, char): return string.lstrip(char) def removeFromEnd(string, char): return string.rstrip(char) # Path functions def combinePaths( basePath, folder ): return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' ) def getFileName(filename): " Purpose: helper function to extrapolate the filename " for splitChar in ["/", "\\"]: array = filename.split(splitChar) if (len(array) > 1): filename = array[-1] return filename def sanitizeFolderName( newFolderName ): "Do a cleanup of the folder name to avoid possible problems" # Remove . \ / | : ? * " < > and control characters return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]', '_', newFolderName ) def sanitizeFileName( newFileName ): "Do a cleanup of the file name to avoid possible problems" # Replace dots in the name with underscores (only one dot can be there... security issue). if ( Config.ForceSingleExtension ): # remove dots newFileName = re.sub ( '\\.(?![^.]*$)', '_', newFileName ) ; newFileName = newFileName.replace('\\','/') # convert windows to unix path newFileName = os.path.basename (newFileName) # strip directories # Remove \ / | : ? * return re.sub ( '\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]/', '_', newFileName ) def getCurrentFolder(currentFolder): if not currentFolder: currentFolder = '/' # Check the current folder syntax (must begin and end with a slash). if (currentFolder[-1] <> "/"): currentFolder += "/" if (currentFolder[0] <> "/"): currentFolder = "/" + currentFolder # Ensure the folder path has no double-slashes while '//' in currentFolder: currentFolder = currentFolder.replace('//','/') # Check for invalid folder paths (..) if '..' in currentFolder or '\\' in currentFolder: return None # Check for invalid folder paths (..) if re.search( '(/\\.)|(//)|([\\\\:\\*\\?\\""\\<\\>\\|]|[\x00-\x1F]|[\x7f-\x9f])', currentFolder ): return None return currentFolder def mapServerPath( environ, url): " Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to " # This isn't correct but for the moment there's no other solution # If this script is under a virtual directory or symlink it will detect the problem and stop return combinePaths( getRootPath(environ), url ) def mapServerFolder(resourceTypePath, folderPath): return combinePaths ( resourceTypePath , folderPath ) def getRootPath(environ): "Purpose: returns the root path on the server" # WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python # Use Config.UserFilesAbsolutePath instead if environ.has_key('DOCUMENT_ROOT'): return environ['DOCUMENT_ROOT'] else: realPath = os.path.realpath( './' ) selfPath = environ['SCRIPT_FILENAME'] selfPath = selfPath [ : selfPath.rfind( '/' ) ] selfPath = selfPath.replace( '/', os.path.sep) position = realPath.find(selfPath) # This can check only that this script isn't run from a virtual dir # But it avoids the problems that arise if it isn't checked raise realPath if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''): raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".') return realPath[ : position ]
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the "File Uploader" for Python """ import os from fckutil import * from fckcommands import * # default command's implementation from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorQuickUpload( FCKeditorConnectorBase, UploadFileCommandMixin, BaseHttpMixin, BaseHtmlMixin): def doResponse(self): "Main function. Process the request, set headers and return a string as response." # Check if this connector is disabled if not(Config.Enabled): return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"") command = 'QuickUpload' # The file type (from the QueryString, by default 'File'). resourceType = self.request.get('Type','File') currentFolder = "/" # Check for invalid paths if currentFolder is None: return self.sendUploadResults(102, '', '', "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendUploadResults( 1, '', '', 'Invalid type specified' ) # Setup paths self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFoldercreateServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here return self.uploadFile(resourceType, currentFolder) # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorQuickUpload() data = conn.doResponse() for header in conn.headers: if not header is None: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Base Connector for Python (CGI and WSGI). See config.py for configuration settings """ import cgi, os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins import config as Config class FCKeditorConnectorBase( object ): "The base connector class. Subclass it to extend functionality (see Zope example)" def __init__(self, environ=None): "Constructor: Here you should parse request fields, initialize variables, etc." self.request = FCKeditorRequest(environ) # Parse request self.headers = [] # Clean Headers if environ: self.environ = environ else: self.environ = os.environ # local functions def setHeader(self, key, value): self.headers.append ((key, value)) return class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, environ): if environ: # WSGI self.request = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=1) self.environ = environ else: # plain old cgi self.environ = os.environ self.request = cgi.FieldStorage() if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ: if self.environ['REQUEST_METHOD'].upper()=='POST': # we are in a POST, but GET query_string exists # cgi parses by default POST data, so parse GET QUERY_STRING too self.get_request = cgi.FieldStorage(fp=None, environ={ 'REQUEST_METHOD':'GET', 'QUERY_STRING':self.environ['QUERY_STRING'], }, ) else: self.get_request={} def has_key(self, key): return self.request.has_key(key) or self.get_request.has_key(key) def get(self, key, default=None): if key in self.request.keys(): field = self.request[key] elif key in self.get_request.keys(): field = self.get_request[key] else: return default if hasattr(field,"filename") and field.filename: #file upload, do not convert return value return field else: return field.value
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector/QuickUpload for Python (WSGI wrapper). See config.py for configuration settings """ from connector import FCKeditorConnector from upload import FCKeditorQuickUpload import cgitb from cStringIO import StringIO # Running from WSGI capable server (recomended) def App(environ, start_response): "WSGI entry point. Run the connector" if environ['SCRIPT_NAME'].endswith("connector.py"): conn = FCKeditorConnector(environ) elif environ['SCRIPT_NAME'].endswith("upload.py"): conn = FCKeditorQuickUpload(environ) else: start_response ("200 Ok", [('Content-Type','text/html')]) yield "Unknown page requested: " yield environ['SCRIPT_NAME'] return try: # run the connector data = conn.doResponse() # Start WSGI response: start_response ("200 Ok", conn.headers) # Send response text yield data except: start_response("500 Internal Server Error",[("Content-type","text/html")]) file = StringIO() cgitb.Hook(file = file).handle() yield file.getvalue()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Utility functions for the File Manager Connector for Python """ import string, re import os import config as Config # Generic manipulation functions def removeExtension(fileName): index = fileName.rindex(".") newFileName = fileName[0:index] return newFileName def getExtension(fileName): index = fileName.rindex(".") + 1 fileExtension = fileName[index:] return fileExtension def removeFromStart(string, char): return string.lstrip(char) def removeFromEnd(string, char): return string.rstrip(char) # Path functions def combinePaths( basePath, folder ): return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' ) def getFileName(filename): " Purpose: helper function to extrapolate the filename " for splitChar in ["/", "\\"]: array = filename.split(splitChar) if (len(array) > 1): filename = array[-1] return filename def sanitizeFolderName( newFolderName ): "Do a cleanup of the folder name to avoid possible problems" # Remove . \ / | : ? * " < > and control characters return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]', '_', newFolderName ) def sanitizeFileName( newFileName ): "Do a cleanup of the file name to avoid possible problems" # Replace dots in the name with underscores (only one dot can be there... security issue). if ( Config.ForceSingleExtension ): # remove dots newFileName = re.sub ( '\\.(?![^.]*$)', '_', newFileName ) ; newFileName = newFileName.replace('\\','/') # convert windows to unix path newFileName = os.path.basename (newFileName) # strip directories # Remove \ / | : ? * return re.sub ( '\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]/', '_', newFileName ) def getCurrentFolder(currentFolder): if not currentFolder: currentFolder = '/' # Check the current folder syntax (must begin and end with a slash). if (currentFolder[-1] <> "/"): currentFolder += "/" if (currentFolder[0] <> "/"): currentFolder = "/" + currentFolder # Ensure the folder path has no double-slashes while '//' in currentFolder: currentFolder = currentFolder.replace('//','/') # Check for invalid folder paths (..) if '..' in currentFolder or '\\' in currentFolder: return None # Check for invalid folder paths (..) if re.search( '(/\\.)|(//)|([\\\\:\\*\\?\\""\\<\\>\\|]|[\x00-\x1F]|[\x7f-\x9f])', currentFolder ): return None return currentFolder def mapServerPath( environ, url): " Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to " # This isn't correct but for the moment there's no other solution # If this script is under a virtual directory or symlink it will detect the problem and stop return combinePaths( getRootPath(environ), url ) def mapServerFolder(resourceTypePath, folderPath): return combinePaths ( resourceTypePath , folderPath ) def getRootPath(environ): "Purpose: returns the root path on the server" # WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python # Use Config.UserFilesAbsolutePath instead if environ.has_key('DOCUMENT_ROOT'): return environ['DOCUMENT_ROOT'] else: realPath = os.path.realpath( './' ) selfPath = environ['SCRIPT_FILENAME'] selfPath = selfPath [ : selfPath.rfind( '/' ) ] selfPath = selfPath.replace( '/', os.path.sep) position = realPath.find(selfPath) # This can check only that this script isn't run from a virtual dir # But it avoids the problems that arise if it isn't checked raise realPath if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''): raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".') return realPath[ : position ]
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). See config.py for configuration settings """ import os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorConnector( FCKeditorConnectorBase, GetFoldersCommandMixin, GetFoldersAndFilesCommandMixin, CreateFolderCommandMixin, UploadFileCommandMixin, BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ): "The Standard connector class." def doResponse(self): "Main function. Process the request, set headers and return a string as response." s = "" # Check if this connector is disabled if not(Config.Enabled): return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.") # Make sure we have valid inputs for key in ("Command","Type","CurrentFolder"): if not self.request.has_key (key): return # Get command, resource type and current folder command = self.request.get("Command") resourceType = self.request.get("Type") currentFolder = getCurrentFolder(self.request.get("CurrentFolder")) # Check for invalid paths if currentFolder is None: if (command == "FileUpload"): return self.sendUploadResults( errorNo = 102, customMsg = "" ) else: return self.sendError(102, "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendError( 1, 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendError( 1, 'Invalid type specified' ) # Setup paths if command == "QuickUpload": self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] else: self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType] self.webUserFilesFolder = Config.FileTypesPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here if (command == "FileUpload"): return self.uploadFile(resourceType, currentFolder) # Create Url url = combinePaths( self.webUserFilesFolder, currentFolder ) # Begin XML s += self.createXmlHeader(command, resourceType, currentFolder, url) # Execute the command selector = {"GetFolders": self.getFolders, "GetFoldersAndFiles": self.getFoldersAndFiles, "CreateFolder": self.createFolder, } s += selector[command](resourceType, currentFolder) s += self.createXmlFooter() return s # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorConnector() data = conn.doResponse() for header in conn.headers: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python and Zope. This code was not tested at all. It just was ported from pre 2.5 release, so for further reference see \editor\filemanager\browser\default\connectors\py\connector.py in previous releases. """ from fckutil import * from connector import * import config as Config class FCKeditorConnectorZope(FCKeditorConnector): """ Zope versiof FCKeditorConnector """ # Allow access (Zope) __allow_access_to_unprotected_subobjects__ = 1 def __init__(self, context=None): """ Constructor """ FCKeditorConnector.__init__(self, environ=None) # call superclass constructor # Instance Attributes self.context = context self.request = FCKeditorRequest(context) def getZopeRootContext(self): if self.zopeRootContext is None: self.zopeRootContext = self.context.getPhysicalRoot() return self.zopeRootContext def getZopeUploadContext(self): if self.zopeUploadContext is None: folderNames = self.userFilesFolder.split("/") c = self.getZopeRootContext() for folderName in folderNames: if (folderName <> ""): c = c[folderName] self.zopeUploadContext = c return self.zopeUploadContext def setHeader(self, key, value): self.context.REQUEST.RESPONSE.setHeader(key, value) def getFolders(self, resourceType, currentFolder): # Open the folders node s = "" s += """<Folders>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["Folder"]): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(name) ) # Close the folders node s += """</Folders>""" return s def getZopeFoldersAndFiles(self, resourceType, currentFolder): folders = self.getZopeFolders(resourceType, currentFolder) files = self.getZopeFiles(resourceType, currentFolder) s = folders + files return s def getZopeFiles(self, resourceType, currentFolder): # Open the files node s = "" s += """<Files>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["File","Image"]): s += """<File name="%s" size="%s" />""" % ( convertToXmlAttribute(name), ((o.get_size() / 1024) + 1) ) # Close the files node s += """</Files>""" return s def findZopeFolder(self, resourceType, folderName): # returns the context of the resource / folder zopeFolder = self.getZopeUploadContext() folderName = self.removeFromStart(folderName, "/") folderName = self.removeFromEnd(folderName, "/") if (resourceType <> ""): try: zopeFolder = zopeFolder[resourceType] except: zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType) zopeFolder = zopeFolder[resourceType] if (folderName <> ""): folderNames = folderName.split("/") for folderName in folderNames: zopeFolder = zopeFolder[folderName] return zopeFolder def createFolder(self, resourceType, currentFolder): # Find out where we are zopeFolder = self.findZopeFolder(resourceType, currentFolder) errorNo = 0 errorMsg = "" if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder) else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def uploadFile(self, resourceType, currentFolder, count=None): zopeFolder = self.findZopeFolder(resourceType, currentFolder) file = self.request.get("NewFile", None) fileName = self.getFileName(file.filename) fileNameOnly = self.removeExtension(fileName) fileExtension = self.getExtension(fileName).lower() if (count): nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension) else: nid = fileName title = nid try: zopeFolder.manage_addProduct['OFSP'].manage_addFile( id=nid, title=title, file=file.read() ) except: if (count): count += 1 else: count = 1 return self.zopeFileUpload(resourceType, currentFolder, count) return self.sendUploadResults( 0 ) class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, context=None): r = context.REQUEST self.request = r def has_key(self, key): return self.request.has_key(key) def get(self, key, default=None): return self.request.get(key, default) """ Running from zope, you will need to modify this connector. If you have uploaded the FCKeditor into Zope (like me), you need to move this connector out of Zope, and replace the "connector" with an alias as below. The key to it is to pass the Zope context in, as we then have a like to the Zope context. ## Script (Python) "connector.py" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=*args, **kws ##title=ALIAS ## import Products.zope as connector return connector.FCKeditorConnectorZope(context=context).doResponse() """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ import os try: # Windows needs stdio set for binary mode for file upload to work. import msvcrt msvcrt.setmode (0, os.O_BINARY) # stdin = 0 msvcrt.setmode (1, os.O_BINARY) # stdout = 1 except ImportError: pass from fckutil import * from fckoutput import * import config as Config class GetFoldersCommandMixin (object): def getFolders(self, resourceType, currentFolder): """ Purpose: command to recieve a list of folders """ # Map the virtual path to our local server serverPath = mapServerFolder(self.userFilesFolder,currentFolder) s = """<Folders>""" # Open the folders node for someObject in os.listdir(serverPath): someObjectPath = mapServerFolder(serverPath, someObject) if os.path.isdir(someObjectPath): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(someObject) ) s += """</Folders>""" # Close the folders node return s class GetFoldersAndFilesCommandMixin (object): def getFoldersAndFiles(self, resourceType, currentFolder): """ Purpose: command to recieve a list of folders and files """ # Map the virtual path to our local server serverPath = mapServerFolder(self.userFilesFolder,currentFolder) # Open the folders / files node folders = """<Folders>""" files = """<Files>""" for someObject in os.listdir(serverPath): someObjectPath = mapServerFolder(serverPath, someObject) if os.path.isdir(someObjectPath): folders += """<Folder name="%s" />""" % ( convertToXmlAttribute(someObject) ) elif os.path.isfile(someObjectPath): size = os.path.getsize(someObjectPath) if size > 0: size = round(size/1024) if size < 1: size = 1 files += """<File name="%s" size="%d" />""" % ( convertToXmlAttribute(someObject), size ) # Close the folders / files node folders += """</Folders>""" files += """</Files>""" return folders + files class CreateFolderCommandMixin (object): def createFolder(self, resourceType, currentFolder): """ Purpose: command to create a new folder """ errorNo = 0; errorMsg =''; if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) newFolder = sanitizeFolderName (newFolder) try: newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder)) self.createServerFolder(newFolderPath) except Exception, e: errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!! if hasattr(e,'errno'): if e.errno==17: #file already exists errorNo=0 elif e.errno==13: # permission denied errorNo = 103 elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name errorNo = 102 else: errorNo = 110 else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def createServerFolder(self, folderPath): "Purpose: physically creates a folder on the server" # No need to check if the parent exists, just create all hierachy try: permissions = Config.ChmodOnFolderCreate if not permissions: os.makedirs(folderPath) except AttributeError: #ChmodOnFolderCreate undefined permissions = 0755 if permissions: oldumask = os.umask(0) os.makedirs(folderPath,mode=0755) os.umask( oldumask ) class UploadFileCommandMixin (object): def uploadFile(self, resourceType, currentFolder): """ Purpose: command to upload files to server (same as FileUpload) """ errorNo = 0 if self.request.has_key("NewFile"): # newFile has all the contents we need newFile = self.request.get("NewFile", "") # Get the file name newFileName = newFile.filename newFileName = sanitizeFileName( newFileName ) newFileNameOnly = removeExtension(newFileName) newFileExtension = getExtension(newFileName).lower() allowedExtensions = Config.AllowedExtensions[resourceType] deniedExtensions = Config.DeniedExtensions[resourceType] if (allowedExtensions): # Check for allowed isAllowed = False if (newFileExtension in allowedExtensions): isAllowed = True elif (deniedExtensions): # Check for denied isAllowed = True if (newFileExtension in deniedExtensions): isAllowed = False else: # No extension limitations isAllowed = True if (isAllowed): # Upload to operating system # Map the virtual path to the local server path currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder) i = 0 while (True): newFilePath = os.path.join (currentFolderPath,newFileName) if os.path.exists(newFilePath): i += 1 newFileName = "%s(%d).%s" % ( newFileNameOnly, i, newFileExtension ) errorNo= 201 # file renamed else: # Read file contents and write to the desired path (similar to php's move_uploaded_file) fout = file(newFilePath, 'wb') while (True): chunk = newFile.file.read(100000) if not chunk: break fout.write (chunk) fout.close() if os.path.exists ( newFilePath ): doChmod = False try: doChmod = Config.ChmodOnUpload permissions = Config.ChmodOnUpload except AttributeError: #ChmodOnUpload undefined doChmod = True permissions = 0755 if ( doChmod ): oldumask = os.umask(0) os.chmod( newFilePath, permissions ) os.umask( oldumask ) newFileUrl = combinePaths(self.webUserFilesFolder, currentFolder) + newFileName return self.sendUploadResults( errorNo , newFileUrl, newFileName ) else: return self.sendUploadResults( errorNo = 202, customMsg = "" ) else: return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ from time import gmtime, strftime import string def escape(text, replace=string.replace): """ Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') return text def convertToXmlAttribute(value): if (value is None): value = "" return escape(value) class BaseHttpMixin(object): def setHttpHeaders(self, content_type='text/xml'): "Purpose: to prepare the headers for the xml to return" # Prevent the browser from caching the result. # Date in the past self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT') # always modified self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())) # HTTP/1.1 self.setHeader('Cache-Control','no-store, no-cache, must-revalidate') self.setHeader('Cache-Control','post-check=0, pre-check=0') # HTTP/1.0 self.setHeader('Pragma','no-cache') # Set the response format. self.setHeader( 'Content-Type', content_type + '; charset=utf-8' ) return class BaseXmlMixin(object): def createXmlHeader(self, command, resourceType, currentFolder, url): "Purpose: returns the xml header" self.setHttpHeaders() # Create the XML document header s = """<?xml version="1.0" encoding="utf-8" ?>""" # Create the main connector node s += """<Connector command="%s" resourceType="%s">""" % ( command, resourceType ) # Add the current folder node s += """<CurrentFolder path="%s" url="%s" />""" % ( convertToXmlAttribute(currentFolder), convertToXmlAttribute(url), ) return s def createXmlFooter(self): "Purpose: returns the xml footer" return """</Connector>""" def sendError(self, number, text): "Purpose: in the event of an error, return an xml based error" self.setHttpHeaders() return ("""<?xml version="1.0" encoding="utf-8" ?>""" + """<Connector>""" + self.sendErrorNode (number, text) + """</Connector>""" ) def sendErrorNode(self, number, text): if number != 1: return """<Error number="%s" />""" % (number) else: return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text)) class BaseHtmlMixin(object): def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ): self.setHttpHeaders("text/html") "This is the function that sends the results of the uploading process" "Minified version of the document.domain automatic fix script (#1919)." "The original script can be found at _dev/domain_fix_template.js" return """<script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s"); </script>""" % { 'errorNumber': errorNo, 'fileUrl': fileUrl.replace ('"', '\\"'), 'fileName': fileName.replace ( '"', '\\"' ) , 'customMsg': customMsg.replace ( '"', '\\"' ), }
Python
#!/usr/bin/env python """ * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Configuration file for the File Manager Connector for Python """ # INSTALLATION NOTE: You must set up your server environment accordingly to run # python scripts. This connector requires Python 2.4 or greater. # # Supported operation modes: # * WSGI (recommended): You'll need apache + mod_python + modpython_gateway # or any web server capable of the WSGI python standard # * Plain Old CGI: Any server capable of running standard python scripts # (although mod_python is recommended for performance) # This was the previous connector version operation mode # # If you're using Apache web server, replace the htaccess.txt to to .htaccess, # and set the proper options and paths. # For WSGI and mod_python, you may need to download modpython_gateway from: # http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this # directory. # SECURITY: You must explicitly enable this "connector". (Set it to "True"). # WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only # authenticated users can access this file or use some kind of session checking. Enabled = False # Path to user files relative to the document root. UserFilesPath = '/userfiles/' # Fill the following value it you prefer to specify the absolute path for the # user files directory. Useful if you are using a virtual directory, symbolic # link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'UserFilesPath' must point to the same directory. # WARNING: GetRootPath may not work in virtual or mod_python configurations, and # may not be thread safe. Use this configuration parameter instead. UserFilesAbsolutePath = '' # Due to security issues with Apache modules, it is recommended to leave the # following setting enabled. ForceSingleExtension = True # What the user can do with this connector ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ] # Allowed Resource Types ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media'] # After file is uploaded, sometimes it is required to change its permissions # so that it was possible to access it at the later time. # If possible, it is recommended to set more restrictive permissions, like 0755. # Set to 0 to disable this feature. # Note: not needed on Windows-based servers. ChmodOnUpload = 0755 # See comments above. # Used when creating folders that does not exist. ChmodOnFolderCreate = 0755 # Do not touch this 3 lines, see "Configuration settings for each Resource Type" AllowedExtensions = {}; DeniedExtensions = {}; FileTypesPath = {}; FileTypesAbsolutePath = {}; QuickUploadPath = {}; QuickUploadAbsolutePath = {}; # Configuration settings for each Resource Type # # - AllowedExtensions: the possible extensions that can be allowed. # If it is empty then any file type can be uploaded. # - DeniedExtensions: The extensions that won't be allowed. # If it is empty then no restrictions are done here. # # For a file to be uploaded it has to fulfill both the AllowedExtensions # and DeniedExtensions (that's it: not being denied) conditions. # # - FileTypesPath: the virtual folder relative to the document root where # these resources will be located. # Attention: It must start and end with a slash: '/' # # - FileTypesAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'FileTypesPath' must point to the same directory. # Attention: It must end with a slash: '/' # # # - QuickUploadPath: the virtual folder relative to the document root where # these resources will be uploaded using the Upload tab in the resources # dialogs. # Attention: It must start and end with a slash: '/' # # - QuickUploadAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'QuickUploadPath' must point to the same directory. # Attention: It must end with a slash: '/' AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip'] DeniedExtensions['File'] = [] FileTypesPath['File'] = UserFilesPath + 'file/' FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or '' QuickUploadPath['File'] = FileTypesPath['File'] QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File'] AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png'] DeniedExtensions['Image'] = [] FileTypesPath['Image'] = UserFilesPath + 'image/' FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or '' QuickUploadPath['Image'] = FileTypesPath['Image'] QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image'] AllowedExtensions['Flash'] = ['swf','flv'] DeniedExtensions['Flash'] = [] FileTypesPath['Flash'] = UserFilesPath + 'flash/' FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or '' QuickUploadPath['Flash'] = FileTypesPath['Flash'] QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash'] AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv'] DeniedExtensions['Media'] = [] FileTypesPath['Media'] = UserFilesPath + 'media/' FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or '' QuickUploadPath['Media'] = FileTypesPath['Media'] QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python and Zope. This code was not tested at all. It just was ported from pre 2.5 release, so for further reference see \editor\filemanager\browser\default\connectors\py\connector.py in previous releases. """ from fckutil import * from connector import * import config as Config class FCKeditorConnectorZope(FCKeditorConnector): """ Zope versiof FCKeditorConnector """ # Allow access (Zope) __allow_access_to_unprotected_subobjects__ = 1 def __init__(self, context=None): """ Constructor """ FCKeditorConnector.__init__(self, environ=None) # call superclass constructor # Instance Attributes self.context = context self.request = FCKeditorRequest(context) def getZopeRootContext(self): if self.zopeRootContext is None: self.zopeRootContext = self.context.getPhysicalRoot() return self.zopeRootContext def getZopeUploadContext(self): if self.zopeUploadContext is None: folderNames = self.userFilesFolder.split("/") c = self.getZopeRootContext() for folderName in folderNames: if (folderName <> ""): c = c[folderName] self.zopeUploadContext = c return self.zopeUploadContext def setHeader(self, key, value): self.context.REQUEST.RESPONSE.setHeader(key, value) def getFolders(self, resourceType, currentFolder): # Open the folders node s = "" s += """<Folders>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["Folder"]): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(name) ) # Close the folders node s += """</Folders>""" return s def getZopeFoldersAndFiles(self, resourceType, currentFolder): folders = self.getZopeFolders(resourceType, currentFolder) files = self.getZopeFiles(resourceType, currentFolder) s = folders + files return s def getZopeFiles(self, resourceType, currentFolder): # Open the files node s = "" s += """<Files>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["File","Image"]): s += """<File name="%s" size="%s" />""" % ( convertToXmlAttribute(name), ((o.get_size() / 1024) + 1) ) # Close the files node s += """</Files>""" return s def findZopeFolder(self, resourceType, folderName): # returns the context of the resource / folder zopeFolder = self.getZopeUploadContext() folderName = self.removeFromStart(folderName, "/") folderName = self.removeFromEnd(folderName, "/") if (resourceType <> ""): try: zopeFolder = zopeFolder[resourceType] except: zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType) zopeFolder = zopeFolder[resourceType] if (folderName <> ""): folderNames = folderName.split("/") for folderName in folderNames: zopeFolder = zopeFolder[folderName] return zopeFolder def createFolder(self, resourceType, currentFolder): # Find out where we are zopeFolder = self.findZopeFolder(resourceType, currentFolder) errorNo = 0 errorMsg = "" if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder) else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def uploadFile(self, resourceType, currentFolder, count=None): zopeFolder = self.findZopeFolder(resourceType, currentFolder) file = self.request.get("NewFile", None) fileName = self.getFileName(file.filename) fileNameOnly = self.removeExtension(fileName) fileExtension = self.getExtension(fileName).lower() if (count): nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension) else: nid = fileName title = nid try: zopeFolder.manage_addProduct['OFSP'].manage_addFile( id=nid, title=title, file=file.read() ) except: if (count): count += 1 else: count = 1 return self.zopeFileUpload(resourceType, currentFolder, count) return self.sendUploadResults( 0 ) class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, context=None): r = context.REQUEST self.request = r def has_key(self, key): return self.request.has_key(key) def get(self, key, default=None): return self.request.get(key, default) """ Running from zope, you will need to modify this connector. If you have uploaded the FCKeditor into Zope (like me), you need to move this connector out of Zope, and replace the "connector" with an alias as below. The key to it is to pass the Zope context in, as we then have a like to the Zope context. ## Script (Python) "connector.py" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=*args, **kws ##title=ALIAS ## import Products.zope as connector return connector.FCKeditorConnectorZope(context=context).doResponse() """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Base Connector for Python (CGI and WSGI). See config.py for configuration settings """ import cgi, os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins import config as Config class FCKeditorConnectorBase( object ): "The base connector class. Subclass it to extend functionality (see Zope example)" def __init__(self, environ=None): "Constructor: Here you should parse request fields, initialize variables, etc." self.request = FCKeditorRequest(environ) # Parse request self.headers = [] # Clean Headers if environ: self.environ = environ else: self.environ = os.environ # local functions def setHeader(self, key, value): self.headers.append ((key, value)) return class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, environ): if environ: # WSGI self.request = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=1) self.environ = environ else: # plain old cgi self.environ = os.environ self.request = cgi.FieldStorage() if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ: if self.environ['REQUEST_METHOD'].upper()=='POST': # we are in a POST, but GET query_string exists # cgi parses by default POST data, so parse GET QUERY_STRING too self.get_request = cgi.FieldStorage(fp=None, environ={ 'REQUEST_METHOD':'GET', 'QUERY_STRING':self.environ['QUERY_STRING'], }, ) else: self.get_request={} def has_key(self, key): return self.request.has_key(key) or self.get_request.has_key(key) def get(self, key, default=None): if key in self.request.keys(): field = self.request[key] elif key in self.get_request.keys(): field = self.get_request[key] else: return default if hasattr(field,"filename") and field.filename: #file upload, do not convert return value return field else: return field.value
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ import os try: # Windows needs stdio set for binary mode for file upload to work. import msvcrt msvcrt.setmode (0, os.O_BINARY) # stdin = 0 msvcrt.setmode (1, os.O_BINARY) # stdout = 1 except ImportError: pass from fckutil import * from fckoutput import * import config as Config class GetFoldersCommandMixin (object): def getFolders(self, resourceType, currentFolder): """ Purpose: command to recieve a list of folders """ # Map the virtual path to our local server serverPath = mapServerFolder(self.userFilesFolder,currentFolder) s = """<Folders>""" # Open the folders node for someObject in os.listdir(serverPath): someObjectPath = mapServerFolder(serverPath, someObject) if os.path.isdir(someObjectPath): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(someObject) ) s += """</Folders>""" # Close the folders node return s class GetFoldersAndFilesCommandMixin (object): def getFoldersAndFiles(self, resourceType, currentFolder): """ Purpose: command to recieve a list of folders and files """ # Map the virtual path to our local server serverPath = mapServerFolder(self.userFilesFolder,currentFolder) # Open the folders / files node folders = """<Folders>""" files = """<Files>""" for someObject in os.listdir(serverPath): someObjectPath = mapServerFolder(serverPath, someObject) if os.path.isdir(someObjectPath): folders += """<Folder name="%s" />""" % ( convertToXmlAttribute(someObject) ) elif os.path.isfile(someObjectPath): size = os.path.getsize(someObjectPath) if size > 0: size = round(size/1024) if size < 1: size = 1 files += """<File name="%s" size="%d" />""" % ( convertToXmlAttribute(someObject), size ) # Close the folders / files node folders += """</Folders>""" files += """</Files>""" return folders + files class CreateFolderCommandMixin (object): def createFolder(self, resourceType, currentFolder): """ Purpose: command to create a new folder """ errorNo = 0; errorMsg =''; if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) newFolder = sanitizeFolderName (newFolder) try: newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder)) self.createServerFolder(newFolderPath) except Exception, e: errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!! if hasattr(e,'errno'): if e.errno==17: #file already exists errorNo=0 elif e.errno==13: # permission denied errorNo = 103 elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name errorNo = 102 else: errorNo = 110 else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def createServerFolder(self, folderPath): "Purpose: physically creates a folder on the server" # No need to check if the parent exists, just create all hierachy try: permissions = Config.ChmodOnFolderCreate if not permissions: os.makedirs(folderPath) except AttributeError: #ChmodOnFolderCreate undefined permissions = 0755 if permissions: oldumask = os.umask(0) os.makedirs(folderPath,mode=0755) os.umask( oldumask ) class UploadFileCommandMixin (object): def uploadFile(self, resourceType, currentFolder): """ Purpose: command to upload files to server (same as FileUpload) """ errorNo = 0 if self.request.has_key("NewFile"): # newFile has all the contents we need newFile = self.request.get("NewFile", "") # Get the file name newFileName = newFile.filename newFileName = sanitizeFileName( newFileName ) newFileNameOnly = removeExtension(newFileName) newFileExtension = getExtension(newFileName).lower() allowedExtensions = Config.AllowedExtensions[resourceType] deniedExtensions = Config.DeniedExtensions[resourceType] if (allowedExtensions): # Check for allowed isAllowed = False if (newFileExtension in allowedExtensions): isAllowed = True elif (deniedExtensions): # Check for denied isAllowed = True if (newFileExtension in deniedExtensions): isAllowed = False else: # No extension limitations isAllowed = True if (isAllowed): # Upload to operating system # Map the virtual path to the local server path currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder) i = 0 while (True): newFilePath = os.path.join (currentFolderPath,newFileName) if os.path.exists(newFilePath): i += 1 newFileName = "%s(%d).%s" % ( newFileNameOnly, i, newFileExtension ) errorNo= 201 # file renamed else: # Read file contents and write to the desired path (similar to php's move_uploaded_file) fout = file(newFilePath, 'wb') while (True): chunk = newFile.file.read(100000) if not chunk: break fout.write (chunk) fout.close() if os.path.exists ( newFilePath ): doChmod = False try: doChmod = Config.ChmodOnUpload permissions = Config.ChmodOnUpload except AttributeError: #ChmodOnUpload undefined doChmod = True permissions = 0755 if ( doChmod ): oldumask = os.umask(0) os.chmod( newFilePath, permissions ) os.umask( oldumask ) newFileUrl = combinePaths(self.webUserFilesFolder, currentFolder) + newFileName return self.sendUploadResults( errorNo , newFileUrl, newFileName ) else: return self.sendUploadResults( errorNo = 202, customMsg = "" ) else: return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector/QuickUpload for Python (WSGI wrapper). See config.py for configuration settings """ from connector import FCKeditorConnector from upload import FCKeditorQuickUpload import cgitb from cStringIO import StringIO # Running from WSGI capable server (recomended) def App(environ, start_response): "WSGI entry point. Run the connector" if environ['SCRIPT_NAME'].endswith("connector.py"): conn = FCKeditorConnector(environ) elif environ['SCRIPT_NAME'].endswith("upload.py"): conn = FCKeditorQuickUpload(environ) else: start_response ("200 Ok", [('Content-Type','text/html')]) yield "Unknown page requested: " yield environ['SCRIPT_NAME'] return try: # run the connector data = conn.doResponse() # Start WSGI response: start_response ("200 Ok", conn.headers) # Send response text yield data except: start_response("500 Internal Server Error",[("Content-type","text/html")]) file = StringIO() cgitb.Hook(file = file).handle() yield file.getvalue()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). See config.py for configuration settings """ import os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorConnector( FCKeditorConnectorBase, GetFoldersCommandMixin, GetFoldersAndFilesCommandMixin, CreateFolderCommandMixin, UploadFileCommandMixin, BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ): "The Standard connector class." def doResponse(self): "Main function. Process the request, set headers and return a string as response." s = "" # Check if this connector is disabled if not(Config.Enabled): return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.") # Make sure we have valid inputs for key in ("Command","Type","CurrentFolder"): if not self.request.has_key (key): return # Get command, resource type and current folder command = self.request.get("Command") resourceType = self.request.get("Type") currentFolder = getCurrentFolder(self.request.get("CurrentFolder")) # Check for invalid paths if currentFolder is None: if (command == "FileUpload"): return self.sendUploadResults( errorNo = 102, customMsg = "" ) else: return self.sendError(102, "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendError( 1, 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendError( 1, 'Invalid type specified' ) # Setup paths if command == "QuickUpload": self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] else: self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType] self.webUserFilesFolder = Config.FileTypesPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here if (command == "FileUpload"): return self.uploadFile(resourceType, currentFolder) # Create Url url = combinePaths( self.webUserFilesFolder, currentFolder ) # Begin XML s += self.createXmlHeader(command, resourceType, currentFolder, url) # Execute the command selector = {"GetFolders": self.getFolders, "GetFoldersAndFiles": self.getFoldersAndFiles, "CreateFolder": self.createFolder, } s += selector[command](resourceType, currentFolder) s += self.createXmlFooter() return s # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorConnector() data = conn.doResponse() for header in conn.headers: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Configuration file for the File Manager Connector for Python """ # INSTALLATION NOTE: You must set up your server environment accordingly to run # python scripts. This connector requires Python 2.4 or greater. # # Supported operation modes: # * WSGI (recommended): You'll need apache + mod_python + modpython_gateway # or any web server capable of the WSGI python standard # * Plain Old CGI: Any server capable of running standard python scripts # (although mod_python is recommended for performance) # This was the previous connector version operation mode # # If you're using Apache web server, replace the htaccess.txt to to .htaccess, # and set the proper options and paths. # For WSGI and mod_python, you may need to download modpython_gateway from: # http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this # directory. # SECURITY: You must explicitly enable this "connector". (Set it to "True"). # WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only # authenticated users can access this file or use some kind of session checking. Enabled = False # Path to user files relative to the document root. UserFilesPath = '/userfiles/' # Fill the following value it you prefer to specify the absolute path for the # user files directory. Useful if you are using a virtual directory, symbolic # link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'UserFilesPath' must point to the same directory. # WARNING: GetRootPath may not work in virtual or mod_python configurations, and # may not be thread safe. Use this configuration parameter instead. UserFilesAbsolutePath = '' # Due to security issues with Apache modules, it is recommended to leave the # following setting enabled. ForceSingleExtension = True # What the user can do with this connector ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ] # Allowed Resource Types ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media'] # After file is uploaded, sometimes it is required to change its permissions # so that it was possible to access it at the later time. # If possible, it is recommended to set more restrictive permissions, like 0755. # Set to 0 to disable this feature. # Note: not needed on Windows-based servers. ChmodOnUpload = 0755 # See comments above. # Used when creating folders that does not exist. ChmodOnFolderCreate = 0755 # Do not touch this 3 lines, see "Configuration settings for each Resource Type" AllowedExtensions = {}; DeniedExtensions = {}; FileTypesPath = {}; FileTypesAbsolutePath = {}; QuickUploadPath = {}; QuickUploadAbsolutePath = {}; # Configuration settings for each Resource Type # # - AllowedExtensions: the possible extensions that can be allowed. # If it is empty then any file type can be uploaded. # - DeniedExtensions: The extensions that won't be allowed. # If it is empty then no restrictions are done here. # # For a file to be uploaded it has to fulfill both the AllowedExtensions # and DeniedExtensions (that's it: not being denied) conditions. # # - FileTypesPath: the virtual folder relative to the document root where # these resources will be located. # Attention: It must start and end with a slash: '/' # # - FileTypesAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'FileTypesPath' must point to the same directory. # Attention: It must end with a slash: '/' # # # - QuickUploadPath: the virtual folder relative to the document root where # these resources will be uploaded using the Upload tab in the resources # dialogs. # Attention: It must start and end with a slash: '/' # # - QuickUploadAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'QuickUploadPath' must point to the same directory. # Attention: It must end with a slash: '/' AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip'] DeniedExtensions['File'] = [] FileTypesPath['File'] = UserFilesPath + 'file/' FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or '' QuickUploadPath['File'] = FileTypesPath['File'] QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File'] AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png'] DeniedExtensions['Image'] = [] FileTypesPath['Image'] = UserFilesPath + 'image/' FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or '' QuickUploadPath['Image'] = FileTypesPath['Image'] QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image'] AllowedExtensions['Flash'] = ['swf','flv'] DeniedExtensions['Flash'] = [] FileTypesPath['Flash'] = UserFilesPath + 'flash/' FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or '' QuickUploadPath['Flash'] = FileTypesPath['Flash'] QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash'] AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv'] DeniedExtensions['Media'] = [] FileTypesPath['Media'] = UserFilesPath + 'media/' FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or '' QuickUploadPath['Media'] = FileTypesPath['Media'] QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This page lists the data posted by a form. """ import cgi import os # Tell the browser to render html print "Content-Type: text/html" print "" try: # Create a cgi object form = cgi.FieldStorage() except Exception, e: print e # Document header print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>FCKeditor - Samples - Posted Data</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="robots" content="noindex, nofollow"> <link href="../sample.css" rel="stylesheet" type="text/css" /> </head> <body> """ # This is the real work print """ <h1>FCKeditor - Samples - Posted Data</h1> This page lists all data posted by the form. <hr> <table border="1" cellspacing="0" id="outputSample"> <colgroup><col width="80"><col></colgroup> <thead> <tr> <th>Field Name</th> <th>Value</th> </tr> </thead> """ for key in form.keys(): try: value = form[key].value print """ <tr> <th>%s</th> <td><pre>%s</pre></td> </tr> """ % (cgi.escape(key), cgi.escape(value)) except Exception, e: print e print "</table>" # For testing your environments #print "<hr>" #for key in os.environ.keys(): # print "%s: %s<br>" % (key, os.environ.get(key, "")) #print "<hr>" # Document footer print """ </body> </html> """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Sample page. """ import cgi import os # Ensure that the fckeditor.py is included in your classpath import fckeditor # Tell the browser to render html print "Content-Type: text/html" print "" # Document header print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>FCKeditor - Sample</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="robots" content="noindex, nofollow"> <link href="../sample.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>FCKeditor - Python - Sample 1</h1> This sample displays a normal HTML form with an FCKeditor with full features enabled. <hr> <form action="sampleposteddata.py" method="post" target="_blank"> """ # This is the real work try: sBasePath = os.environ.get("SCRIPT_NAME") sBasePath = sBasePath[0:sBasePath.find("_samples")] oFCKeditor = fckeditor.FCKeditor('FCKeditor1') oFCKeditor.BasePath = sBasePath oFCKeditor.Value = """<p>This is some <strong>sample text</strong>. You are using <a href="http://www.fckeditor.net/">FCKeditor</a>.</p>""" print oFCKeditor.Create() except Exception, e: print e print """ <br> <input type="submit" value="Submit"> </form> """ # For testing your environments #print "<hr>" #for key in os.environ.keys(): # print "%s: %s<br>" % (key, os.environ.get(key, "")) #print "<hr>" # Document footer print """ </body> </html> """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This page lists the data posted by a form. """ import cgi import os # Tell the browser to render html print "Content-Type: text/html" print "" try: # Create a cgi object form = cgi.FieldStorage() except Exception, e: print e # Document header print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>FCKeditor - Samples - Posted Data</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="robots" content="noindex, nofollow"> <link href="../sample.css" rel="stylesheet" type="text/css" /> </head> <body> """ # This is the real work print """ <h1>FCKeditor - Samples - Posted Data</h1> This page lists all data posted by the form. <hr> <table border="1" cellspacing="0" id="outputSample"> <colgroup><col width="80"><col></colgroup> <thead> <tr> <th>Field Name</th> <th>Value</th> </tr> </thead> """ for key in form.keys(): try: value = form[key].value print """ <tr> <th>%s</th> <td><pre>%s</pre></td> </tr> """ % (cgi.escape(key), cgi.escape(value)) except Exception, e: print e print "</table>" # For testing your environments #print "<hr>" #for key in os.environ.keys(): # print "%s: %s<br>" % (key, os.environ.get(key, "")) #print "<hr>" # Document footer print """ </body> </html> """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Sample page. """ import cgi import os # Ensure that the fckeditor.py is included in your classpath import fckeditor # Tell the browser to render html print "Content-Type: text/html" print "" # Document header print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>FCKeditor - Sample</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="robots" content="noindex, nofollow"> <link href="../sample.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>FCKeditor - Python - Sample 1</h1> This sample displays a normal HTML form with an FCKeditor with full features enabled. <hr> <form action="sampleposteddata.py" method="post" target="_blank"> """ # This is the real work try: sBasePath = os.environ.get("SCRIPT_NAME") sBasePath = sBasePath[0:sBasePath.find("_samples")] oFCKeditor = fckeditor.FCKeditor('FCKeditor1') oFCKeditor.BasePath = sBasePath oFCKeditor.Value = """<p>This is some <strong>sample text</strong>. You are using <a href="http://www.fckeditor.net/">FCKeditor</a>.</p>""" print oFCKeditor.Create() except Exception, e: print e print """ <br> <input type="submit" value="Submit"> </form> """ # For testing your environments #print "<hr>" #for key in os.environ.keys(): # print "%s: %s<br>" % (key, os.environ.get(key, "")) #print "<hr>" # Document footer print """ </body> </html> """
Python
""" FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the integration file for Python. """ import cgi import os import re import string def escape(text, replace=string.replace): """Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') text = replace(text, "'", '&#39;') return text # The FCKeditor class class FCKeditor(object): def __init__(self, instanceName): self.InstanceName = instanceName self.BasePath = '/fckeditor/' self.Width = '100%' self.Height = '200' self.ToolbarSet = 'Default' self.Value = ''; self.Config = {} def Create(self): return self.CreateHtml() def CreateHtml(self): HtmlValue = escape(self.Value) Html = "" if (self.IsCompatible()): File = "fckeditor.html" Link = "%seditor/%s?InstanceName=%s" % ( self.BasePath, File, self.InstanceName ) if (self.ToolbarSet is not None): Link += "&amp;Toolbar=%s" % self.ToolbarSet # Render the linked hidden field Html += "<input type=\"hidden\" id=\"%s\" name=\"%s\" value=\"%s\" style=\"display:none\" />" % ( self.InstanceName, self.InstanceName, HtmlValue ) # Render the configurations hidden field Html += "<input type=\"hidden\" id=\"%s___Config\" value=\"%s\" style=\"display:none\" />" % ( self.InstanceName, self.GetConfigFieldString() ) # Render the editor iframe Html += "<iframe id=\"%s\__Frame\" src=\"%s\" width=\"%s\" height=\"%s\" frameborder=\"0\" scrolling=\"no\"></iframe>" % ( self.InstanceName, Link, self.Width, self.Height ) else: if (self.Width.find("%%") < 0): WidthCSS = "%spx" % self.Width else: WidthCSS = self.Width if (self.Height.find("%%") < 0): HeightCSS = "%spx" % self.Height else: HeightCSS = self.Height Html += "<textarea name=\"%s\" rows=\"4\" cols=\"40\" style=\"width: %s; height: %s;\" wrap=\"virtual\">%s</textarea>" % ( self.InstanceName, WidthCSS, HeightCSS, HtmlValue ) return Html def IsCompatible(self): if (os.environ.has_key("HTTP_USER_AGENT")): sAgent = os.environ.get("HTTP_USER_AGENT", "") else: sAgent = "" if (sAgent.find("MSIE") >= 0) and (sAgent.find("mac") < 0) and (sAgent.find("Opera") < 0): i = sAgent.find("MSIE") iVersion = float(sAgent[i+5:i+5+3]) if (iVersion >= 5.5): return True return False elif (sAgent.find("Gecko/") >= 0): i = sAgent.find("Gecko/") iVersion = int(sAgent[i+6:i+6+8]) if (iVersion >= 20030210): return True return False elif (sAgent.find("Opera/") >= 0): i = sAgent.find("Opera/") iVersion = float(sAgent[i+6:i+6+4]) if (iVersion >= 9.5): return True return False elif (sAgent.find("AppleWebKit/") >= 0): p = re.compile('AppleWebKit\/(\d+)', re.IGNORECASE) m = p.search(sAgent) if (m.group(1) >= 522): return True return False else: return False def GetConfigFieldString(self): sParams = "" bFirst = True for sKey in self.Config.keys(): sValue = self.Config[sKey] if (not bFirst): sParams += "&amp;" else: bFirst = False if (sValue): k = escape(sKey) v = escape(sValue) if (sValue == "true"): sParams += "%s=true" % k elif (sValue == "false"): sParams += "%s=false" % k else: sParams += "%s=%s" % (k, v) return sParams
Python
""" Selector classes implementing various selection algorithms """ import sys from random import choice, randint, shuffle, random class Selector(object): """ Abstract base selection object contains standard methods """ def select(self, organisms=None, n=None): """ @param list organisms a list of organisms from which individuals are selected @param int n number of individuals in the population to select @param list candidates the selected candidates for reproduction """ raise Exception("select method is not implemented.") class TournamentSelector(Selector): """ """ def select(self, organisms, n): tournament_size = 5 candidates = [] for i in xrange(n): # Choose x random organisms tournament_candidates = [choice(organisms) for i in xrange(tournament_size)] best_candidate = tournament_candidates[0] # Compare candidates to find the best of the group. for candidate in tournament_candidates[1:]: if candidate.fitness() < best_candidate.fitness(): best_candidate = candidate candidates.append(best_candidate) return candidates class RouletteSelector(Selector): """ Based on the algorithm presented by Holland (1975) and Goldberg (1989b) """ def select(self, organisms, n): # Evaluate the fitness of each organism organism_count = len(organisms) shuffle(organisms) fitnesses = [organism.fitness() for organism in organisms] f_total = sum(fitnesses) # Invert fitness so smallest fitnesses have the most weight. f_inv = [f_total / f for f in fitnesses] f_inv_total = sum(f_inv) # Calculate selection probability of inverted fitnesses. p = [f_inv_i / f_inv_total for f_inv_i in f_inv] # Calculate the cumulative selection probability. p_total = 0 q = [] for p_i in p: p_total += p_i q.append(p_total) # Select candidates for reproduction organism_range = xrange(1, organism_count) candidates = [] for c in xrange(n): # Select r in (0, 1] r = 0 while r == 0: r = random() if r < q[0]: i = 0 else: for i in organism_range: if q[i - 1] < r <= q[i]: break candidates.append(organisms[i]) print "Return candidates", len(candidates) return candidates class NewRouletteSelector(Selector): """ Based on the algorithm presented by Holland (1975) and Goldberg (1989b) """ def select(self, organisms, n): # Evaluate the fitness of each organism organism_count = len(organisms) #shuffle(organisms) fitnesses = [organism.fitness() for organism in organisms] f_total = sum(fitnesses) # Calculate selection probability of inverted fitnesses. p = [f / f_total for f in fitnesses] # Invert fitness so smallest fitnesses have the most weight. p.reverse() #print p #sys.exit() # Calculate the cumulative selection probability. p_total = 0 q = [] for p_i in p: p_total += p_i q.append(p_total) # Select candidates for reproduction organism_range = xrange(1, organism_count) candidates = [] for c in xrange(n): # Select r in (0, 1] r = 0 while r == 0: r = random() if r < q[0]: i = 0 else: for i in organism_range: if q[i - 1] < r <= q[i]: break candidates.append(organisms[i]) print "Return candidates", len(candidates) return candidates class SpeaSelector(Selector): """ Interfaces with the PISA-based multiobjective optimization algorithm SPEA2. See: http://www.tik.ee.ethz.ch/sop/pisa/ """ def __init__(self, *args, **kwargs): """ Sets up the local archive of all organisms ever passed to the selector. """ self.archive = {} self.max_id = 0 super(SpeaSelector, self).__init__(*args, **kwargs) def get_max_id(self): max = self.max_id self.max_id += 1 return max def select(self, organisms, n): pass
Python
"""Variator mockup used to test PISA functionality.""" import random import time import pisa try: ################################################################# # evolve_beats.py # # Configuration steps, command line arguments, basic file i/o. # Passes prefix and period. ################################################################# MAX_GENERATIONS = 10 pisa_prefix = "PISA_" poll_period = 1 ################################################################# # population __init__() # # PISA file names and common parameters. Uses PISA files to # configure state and initial population. ################################################################# for key, value in pisa.files.items(): pisa.files[key] = "%s%s" % (pisa_prefix, value) # Write 0 to the state file pisa.write_file(pisa.files['state'], 0) # Read common parameters parameters = pisa.read_configuration_file(pisa.files['configuration']) print "Loaded parameters: %s\n" % parameters # Generate initial population population = {} for i in xrange(parameters['alpha']): population[i] = [float(random.randint(0, 100))] # Evaluate individual next_id = parameters['alpha'] print "Generated population: %s\n" % population # Write initial population into init pop file pisa.write_file(pisa.files['initial_population'], population, parameters['dim']) # Write 1 to the state file pisa.write_file(pisa.files['state'], 1) ################################################################# # evolve_beats # # Handles looping of generations. Everything within loop can be # handled by the population. ################################################################# # For each remaining generation print "Start\n" generation = 0 while generation < MAX_GENERATIONS: ############################################################# # population gen() # # Checks state file, returns False if selector terminates. ############################################################# # If state is 4, break. If state is 2, process selector output. # Otherwise, read state file every n seconds where n is the poll time state = pisa.read_state_file(pisa.files['state']) if state == 4: print "Selector has terminated\n" break elif state != 2: # Sleep for n seconds, then continue. print "Waiting for selector\n" time.sleep(poll_period) continue ############################################################# # The load sample and archive sections could be in the # selector but how does the selector know where the mating # happens or where to look for the data files? How does it # know what it's looking at or what to do with it? ############################################################# # Load sample from sample file print "Read sample file\n" sample = pisa.read_data_file(pisa.files['sample']) # Load archive from archive file archive = pisa.read_data_file(pisa.files['archive']) # Clean up local population based on archive contents ids = population.keys() for id in ids: if id not in archive: del(population[id]) # Pair up and mate parents from sample with mutation offspring = {} for i in xrange(parameters['lambda']): offspring[next_id] = [random.randint(0, 100)] next_id += 1 # Calculate fitness values for the offspring # Write offspring to offspring file pisa.write_file(pisa.files['offspring'], offspring, parameters['dim']) population.update(offspring) # Write 3 to the state file pisa.write_file(pisa.files['state'], 3) # This marks the end of the gen() method. generation += 1 ################################################################# # The final write to the state file will need to be handled # in a separate population method like close(), or finish(). # Alternately, the population's __del__ method can be used. ################################################################# if state != 4: # Write 6 to state file pisa.write_file(pisa.files['state'], 6) print "Final sample:" for id in sample: print "%i: %s" % (id, population[id]) except pisa.CorruptedDataException, e: print "Error: %s" % e
Python
#!/usr/bin/env python """ pisa_beats.py Evolves a pattern of beats based on a collection of user-defined fitness trajectories. The genetic algorithm is based on the pygene library. @author John Huddleston """ import os import sys import pickle os.environ['DJANGO_SETTINGS_MODULE'] = "fitbeat_project.settings" from random import choice, random from optparse import OptionParser from pattern import PatternGene, MultiObjectivePatternOrganism, MultiObjectiveDictPopulation from fitbeat_project.fitbeats.models import * from selector import RouletteSelector, TournamentSelector, NewRouletteSelector from crossover import OnePointCrossover def main(pattern_id=None): if pattern_id: return_best = True else: return_best = False usage = "usage: %prog [-p] [[options] pattern_id]" parser = OptionParser(usage) parser.add_option("-f", "--prefix", dest="pisa_prefix", type="string", default="PISA_", help="the prefix to use for all PISA configuration files.") parser.add_option("-t", "--poll", dest="pisa_period", type="float", default=1.0, help="the amount of time the variator should wait between\ polling the PISA state file.") parser.add_option("-s", "--stats", dest="statfile", type="string", default="stats.txt", help="a filename for the statistical output") parser.add_option("-o", "--output", dest="songfile", type="string", default=None, help="a filename for the song output") parser.add_option("-d", dest="database_dump", action="store_true", default=False, help="dump best pattern to database") parser.add_option("-l", dest="limit_mutation", action="store_true", default=False, help="limit mutation based on fitness value and mutator impact") parser.add_option("-q", dest="quiet", action="store_true", default=False, help="suppress debug output") parser.add_option("-p", dest="list_patterns", action="store_true", default=False, help="list available patterns and their ids") (options, args) = parser.parse_args() if options.list_patterns: patterns = Pattern.objects.all() print "Id | Dimensions | Name" print "----------------------" for p in patterns: try: print "%i | (%i x %i) | %s | %s" % (p.id, p.length, p.instrument_length, p, p.fitnesstrajectory_set.all()) except: pass sys.exit() elif pattern_id is None and len(args) != 1: parser.error("""You must supply a pattern id as an argument or use the -p flag to list the available patterns.""") else: try: pattern_id = pattern_id or int(args[0]) except ValueError: parser.error("You must supply an integer value for the pattern id.") try: pattern = Pattern.objects.get(pk=pattern_id) except Pattern.DoesNotExist: print "Error: could not load pattern %s" % pattern_id sys.exit(1) selector = eval(pattern.selector.get_short_name()) crossover = eval(pattern.crossover.get_short_name()) mutators = ["%sMutator" % m.name for m in pattern.mutators.all()] trajectory_set = pattern.fitnesstrajectory_set.all() for trajectory in trajectory_set: trajectory.calculate_trajectory() parameters = dict([(parameter.name, parameter.value) for parameter in pattern.parameters.all()]) # Prepare gene PatternGene.mutProb = parameters['gene_mutation_probability'] # Prepare organism MultiObjectivePatternOrganism.mutProb = parameters['organism_mutation_probability'] MultiObjectivePatternOrganism.crossoverRate = parameters['organism_crossover_rate'] MultiObjectivePatternOrganism.instrument_length = pattern.instrument_length MultiObjectivePatternOrganism.instruments = pattern.instruments.all() MultiObjectivePatternOrganism.length = pattern.length MultiObjectivePatternOrganism.crossover = crossover() MultiObjectivePatternOrganism.mutators = mutators MultiObjectivePatternOrganism.limit_mutation = options.limit_mutation MultiObjectivePatternOrganism.trajectory_set = trajectory_set MultiObjectivePatternOrganism.gene = PatternGene # Prepare population dimensions = len(trajectory_set) childCount = int(parameters['population_new_children']) selector=selector() initial_population_size = int(parameters['population_initial_size']) ph = MultiObjectiveDictPopulation(options.pisa_prefix, options.pisa_period, dimensions, childCount, selector, init=initial_population_size, species=MultiObjectivePatternOrganism) max_generations = int(parameters['population_max_generations']) if not options.quiet: print "Pattern Length: %i" % pattern.length print "Instruments:" for i in pattern.instruments.all(): print "\t%s" % i print "Generations: %i" % max_generations print "Selector: %s" % pattern.selector.name print "Crossover: %s" % pattern.crossover.name print "Mutators:\n\t%s" % "\n\t".join(mutators) print "Fitness Trajectories:" for t in trajectory_set: print "\t%s" % t print "Parameters:" for key, value in parameters.iteritems(): print "\t%s: %s" % (key, value) stats = {} webstats = None lastBest = None lastBestCount = 0 i = 0 stopfile = "/home/huddlej/fitbeats/stopfile.txt" for i in xrange(max_generations): # Check for file-based exit command. if options.database_dump: try: fhandle = open(stopfile, "r") stop = pickle.load(fhandle) if stop: break except: pass try: b = ph.best() if not options.quiet: print "generation %i:\n%s best=%s)" % (i, repr(b), b.fitness()) stats[i] = {'generation': i, 'bestfitness': b.fitness(), 'best_pattern': b, 'is_done': False} webstats = stats[i] # Store for web, TODO: make this better fhandle = open(options.statfile, "w") pickle.dump(webstats, fhandle) fhandle.close() if b.fitness() <= 0: break # Start the next generation. ph.gen() except KeyboardInterrupt: break if options.database_dump: p = PatternInstance(pattern=pattern, fitness=b.fitness(), value=b.xmlDumps()) p.save() if webstats: webstats['is_done'] = True fhandle = open(options.statfile, "w") pickle.dump(webstats, fhandle) fhandle.close() if not options.quiet: for p in ph.sample: print ph[p] # Store new statistics data #fileHandle = open(options.statfile, 'w') #pickle.dump(stats, fileHandle) #fileHandle.close() if options.songfile: testxml = open(options.songfile, "w") b.xmlDump(testxml) testxml.close() if not options.quiet: print "Wrote %s" % options.songfile else: if not options.quiet: print "No file written." if __name__ == '__main__': main()
Python
#!/usr/bin/env python """ evolve_beats.py Evolves a pattern of beats based on a collection of user-defined fitness trajectories. The genetic algorithm is based on the pygene library. @author John Huddleston """ import os import sys import pickle os.environ['DJANGO_SETTINGS_MODULE'] = "fitbeat_project.settings" from random import choice, random from optparse import OptionParser from pattern import PatternGene, PatternOrganism, PatternPopulation from fitbeat_project.fitbeats.models import * from selector import RouletteSelector, TournamentSelector, NewRouletteSelector from crossover import OnePointCrossover def main(pattern_id=None): if pattern_id: return_best = True else: return_best = False usage = "usage: %prog [-p] [[options] pattern_id]" parser = OptionParser(usage) parser.add_option("-f", "--prefix", dest="pisa_prefix", type="string", default="PISA_", help="the prefix to use for all PISA configuration files.") parser.add_option("-s", "--stats", dest="statfile", type="string", default="stats.txt", help="a filename for the statistical output") parser.add_option("-o", "--output", dest="songfile", type="string", default=None, help="a filename for the song output") parser.add_option("-d", dest="database_dump", action="store_true", default=False, help="dump best pattern to database") parser.add_option("-l", dest="limit_mutation", action="store_true", default=False, help="limit mutation based on fitness value and mutator impact") parser.add_option("-q", dest="quiet", action="store_true", default=False, help="suppress debug output") parser.add_option("-p", dest="list_patterns", action="store_true", default=False, help="list available patterns and their ids") (options, args) = parser.parse_args() if options.list_patterns: patterns = Pattern.objects.all() print "Id | Dimensions | Name" print "----------------------" for p in patterns: try: print "%i | (%i x %i) | %s" % (p.id, p.length, p.instrument_length, p) except: pass sys.exit() elif pattern_id is None and len(args) != 1: parser.error("""You must supply a pattern id as an argument or use the -p flag to list the available patterns.""") else: try: pattern_id = pattern_id or int(args[0]) except ValueError: parser.error("You must supply an integer value for the pattern id.") # Set option variables limit_mutation = options.limit_mutation database_dump = options.database_dump quiet = options.quiet statfile = options.statfile songfile = options.songfile pisa_prefix = options.pisa_prefix try: pattern = Pattern.objects.get(pk=pattern_id) except Pattern.DoesNotExist: print "Error: could not load pattern %s" % pattern_id sys.exit(1) length = pattern.length instrument_length = pattern.instrument_length selector = eval(pattern.selector.get_short_name()) crossover = eval(pattern.crossover.get_short_name()) mutators = ["%sMutator" % m.name for m in pattern.mutators.all()] trajectory_set = pattern.fitnesstrajectory_set.all() for trajectory in trajectory_set: trajectory.calculate_trajectory() parameters = pattern.parameters.all() parameter_dict = {} for parameter in parameters: parameter_dict[parameter.name] = parameter.value parameters = parameter_dict # Prepare gene PatternGene.mutProb = parameters['gene_mutation_probability'] # Prepare organism PatternOrganism.mutProb = parameters['organism_mutation_probability'] PatternOrganism.crossoverRate = parameters['organism_crossover_rate'] PatternOrganism.instrument_length = instrument_length PatternOrganism.instruments = pattern.instruments.all() PatternOrganism.length = length PatternOrganism.crossover = crossover() PatternOrganism.mutators = mutators PatternOrganism.limit_mutation = limit_mutation PatternOrganism.trajectory_set = trajectory_set PatternOrganism.gene = PatternGene # Prepare population PatternPopulation.selector=selector() ph = PatternPopulation(init=int(parameters['population_initial_size']), species=PatternOrganism) ph.childCount = int(parameters['population_new_children']) max_generations = int(parameters['population_max_generations']) if not quiet: print "Pattern Length: %i, Instruments: %i" % (length, instrument_length) print "Generations: %i" % max_generations print "Selector: %s" % pattern.selector.name print "Crossover: %s" % pattern.crossover.name print "Mutators:\n\t%s" % "\n\t".join(mutators) print "Fitness Trajectories:" print trajectory_set #print "Parameters:" #print parameters stats = {} webstats = None lastBest = 1000 lastBestCount = 0 i = 0 statfile = "/home/huddlej/fitbeats/testData.txt" stopfile = "/home/huddlej/fitbeats/stopfile.txt" while i < max_generations: # Check for file-based exit command. if database_dump: try: fhandle = open(stopfile, "r") stop = pickle.load(fhandle) if stop: break except: pass try: b = ph.best() diversity = ph.diversity() #b = ph.worst() if not quiet: print "generation %i:\n%s best=%f, average=%f, diversity=%f)" % (i, repr(b), b.fitness(), ph.fitness(), diversity) stats[i] = {'generation': i, 'bestfitness': b.fitness(), 'popfitness': ph.fitness(), 'diversity': diversity, 'best_pattern': b, 'is_done': False} webstats = stats[i] # Store for web, TODO: make this better fhandle = open(statfile, "w") pickle.dump(webstats, fhandle) fhandle.close() if b.fitness() <= 0: break if lastBest > b.fitness(): lastBest = b.fitness() lastBestCount = 1 else: lastBestCount += 1 #if lastBestCount > 10: # break ph.gen() i += 1 except KeyboardInterrupt: break if database_dump: p = PatternInstance(pattern=pattern, fitness=b.fitness(), value=b.xmlDumps()) p.save() if webstats: webstats['is_done'] = True fhandle = open(statfile, "w") pickle.dump(webstats, fhandle) fhandle.close() if not quiet: print "Stopped:\n%f" % lastBest #print "Average diversity: %f" % ph.diversity() # Store new statistics data #fileHandle = open(statfile, 'w') #pickle.dump(stats, fileHandle) #fileHandle.close() if songfile: testxml = open(songfile, "w") b.xmlDump(testxml) testxml.close() if not quiet: print "Wrote %s" % songfile else: if not quiet: print "No file written." if __name__ == '__main__': main()
Python
#!/usr/bin/env python """ evolve_beats.py Evolves a pattern of beats based on a collection of user-defined fitness trajectories. The genetic algorithm is based on the pygene library. @author John Huddleston """ import os import sys import pickle os.environ['DJANGO_SETTINGS_MODULE'] = "fitbeat_project.settings" from random import choice, random from optparse import OptionParser from pattern import PatternGene, PatternOrganism, PatternPopulation from fitbeat_project.fitbeats.models import * from selector import RouletteSelector, TournamentSelector, NewRouletteSelector from crossover import OnePointCrossover def main(pattern_id=None): if pattern_id: return_best = True else: return_best = False usage = "usage: %prog [-p] [[options] pattern_id]" parser = OptionParser(usage) parser.add_option("-f", "--prefix", dest="pisa_prefix", type="string", default="PISA_", help="the prefix to use for all PISA configuration files.") parser.add_option("-s", "--stats", dest="statfile", type="string", default="stats.txt", help="a filename for the statistical output") parser.add_option("-o", "--output", dest="songfile", type="string", default=None, help="a filename for the song output") parser.add_option("-d", dest="database_dump", action="store_true", default=False, help="dump best pattern to database") parser.add_option("-l", dest="limit_mutation", action="store_true", default=False, help="limit mutation based on fitness value and mutator impact") parser.add_option("-q", dest="quiet", action="store_true", default=False, help="suppress debug output") parser.add_option("-p", dest="list_patterns", action="store_true", default=False, help="list available patterns and their ids") (options, args) = parser.parse_args() if options.list_patterns: patterns = Pattern.objects.all() print "Id | Dimensions | Name" print "----------------------" for p in patterns: try: print "%i | (%i x %i) | %s" % (p.id, p.length, p.instrument_length, p) except: pass sys.exit() elif pattern_id is None and len(args) != 1: parser.error("""You must supply a pattern id as an argument or use the -p flag to list the available patterns.""") else: try: pattern_id = pattern_id or int(args[0]) except ValueError: parser.error("You must supply an integer value for the pattern id.") # Set option variables limit_mutation = options.limit_mutation database_dump = options.database_dump quiet = options.quiet statfile = options.statfile songfile = options.songfile pisa_prefix = options.pisa_prefix try: pattern = Pattern.objects.get(pk=pattern_id) except Pattern.DoesNotExist: print "Error: could not load pattern %s" % pattern_id sys.exit(1) length = pattern.length instrument_length = pattern.instrument_length selector = eval(pattern.selector.get_short_name()) crossover = eval(pattern.crossover.get_short_name()) mutators = ["%sMutator" % m.name for m in pattern.mutators.all()] trajectory_set = pattern.fitnesstrajectory_set.all() for trajectory in trajectory_set: trajectory.calculate_trajectory() parameters = pattern.parameters.all() parameter_dict = {} for parameter in parameters: parameter_dict[parameter.name] = parameter.value parameters = parameter_dict # Prepare gene PatternGene.mutProb = parameters['gene_mutation_probability'] # Prepare organism PatternOrganism.mutProb = parameters['organism_mutation_probability'] PatternOrganism.crossoverRate = parameters['organism_crossover_rate'] PatternOrganism.instrument_length = instrument_length PatternOrganism.instruments = pattern.instruments.all() PatternOrganism.length = length PatternOrganism.crossover = crossover() PatternOrganism.mutators = mutators PatternOrganism.limit_mutation = limit_mutation PatternOrganism.trajectory_set = trajectory_set PatternOrganism.gene = PatternGene # Prepare population PatternPopulation.selector=selector() ph = PatternPopulation(init=int(parameters['population_initial_size']), species=PatternOrganism) ph.childCount = int(parameters['population_new_children']) max_generations = int(parameters['population_max_generations']) if not quiet: print "Pattern Length: %i, Instruments: %i" % (length, instrument_length) print "Generations: %i" % max_generations print "Selector: %s" % pattern.selector.name print "Crossover: %s" % pattern.crossover.name print "Mutators:\n\t%s" % "\n\t".join(mutators) print "Fitness Trajectories:" print trajectory_set #print "Parameters:" #print parameters stats = {} webstats = None lastBest = 1000 lastBestCount = 0 i = 0 statfile = "/home/huddlej/fitbeats/testData.txt" stopfile = "/home/huddlej/fitbeats/stopfile.txt" while i < max_generations: # Check for file-based exit command. if database_dump: try: fhandle = open(stopfile, "r") stop = pickle.load(fhandle) if stop: break except: pass try: b = ph.best() diversity = ph.diversity() #b = ph.worst() if not quiet: print "generation %i:\n%s best=%f, average=%f, diversity=%f)" % (i, repr(b), b.fitness(), ph.fitness(), diversity) stats[i] = {'generation': i, 'bestfitness': b.fitness(), 'popfitness': ph.fitness(), 'diversity': diversity, 'best_pattern': b, 'is_done': False} webstats = stats[i] # Store for web, TODO: make this better fhandle = open(statfile, "w") pickle.dump(webstats, fhandle) fhandle.close() if b.fitness() <= 0: break if lastBest > b.fitness(): lastBest = b.fitness() lastBestCount = 1 else: lastBestCount += 1 #if lastBestCount > 10: # break ph.gen() i += 1 except KeyboardInterrupt: break if database_dump: p = PatternInstance(pattern=pattern, fitness=b.fitness(), value=b.xmlDumps()) p.save() if webstats: webstats['is_done'] = True fhandle = open(statfile, "w") pickle.dump(webstats, fhandle) fhandle.close() if not quiet: print "Stopped:\n%f" % lastBest #print "Average diversity: %f" % ph.diversity() # Store new statistics data #fileHandle = open(statfile, 'w') #pickle.dump(stats, fileHandle) #fileHandle.close() if songfile: testxml = open(songfile, "w") b.xmlDump(testxml) testxml.close() if not quiet: print "Wrote %s" % songfile else: if not quiet: print "No file written." if __name__ == '__main__': main()
Python
""" pattern.py Represents all elements population of organisms: * Gene * Organism * Population """ import Numeric import copy import time from random import random, choice from pygene.gene import IntGene from pygene.organism import Organism from pygene.population import Population from fitness import * from mutator import * from hydrogen import savePatternToXml from fitbeat_project.fitbeats.functions import similarity import pisa class PatternGene(IntGene): mutProb = 0.02 randMin = 0 randMax = 1 def __repr__(self): return str(self.value) def __cmp__(this, other): if isinstance(other, int): return cmp(this.value, other) else: return cmp(this.value, other.value) class PatternOrganism(Organism): mutProb = 0.02 crossoverRate = 0.9 def __init__(self, **kw): self.genes = Numeric.array([[self.gene() for i in xrange(self.length)] for j in xrange(self.instrument_length)], 'O') def __repr__(self): return self.__str__() def __str__(self): output = "" for i in xrange(Numeric.shape(self.genes)[0] - 1, -1, -1): output += "%s %s\n" % (str(self.instruments[i]).ljust(20), " ".join(map(str, self.genes[i].tolist()))) return output def __len__(self): return self.length def __getitem__(self, key): if not isinstance(key, int) and not isinstance(key, slice): raise TypeError("Type is: %s" % type(key)) length = Numeric.shape(self.genes)[1] if isinstance(key, int) and key >= length: raise IndexError("""Request key %i is greater than the length of the object: %i""" % (key, length)) elif isinstance(key, slice) and key.start >= length: raise IndexError("""Request key %i is greater than the length of the object: %i""" % (key.start, length)) return self.genes[:, key] def __setitem__(self, key, value): if not isinstance(key, int) and not isinstance(key, slice): raise TypeError("Type is: %s" % type(key)) length = Numeric.shape(self.genes)[1] if isinstance(key, int) and key >= length: raise IndexError("""Request key %i is greater than the length of the object: %i""" % (key, length)) elif isinstance(key, slice) and key.start >= length: raise IndexError("""Request key %i is greater than the length of the object: %i""" % (key.start, length)) self.genes[:, key] = value def fitness(self): # Only evaluate this individual's fitness once try: if self._fitness: return self._fitness except: pass trajectory_set = self.trajectory_set n = len(trajectory_set) fitness = 0 if n == 0: return fitness # Calculate fitness for each trajectory for trajectory in trajectory_set: fitness_function = eval(trajectory.function.name) fitness += fitness_function(self, trajectory) self._fitness = float(fitness) / n return self._fitness def mate(self, partner): """ Mate this organism with another using the organism's crossover method. """ if not self.crossover: raise Exception('No crossover operator specified.') #print "crossover..." if random() < self.crossoverRate: return self.crossover.mate(self, partner) else: return (self, partner) def copy(self): """ Perform copy as parent would but make sure fitness value is cleared. """ #copy = self.__class__(**genes) self_copy = copy.deepcopy(self) self_copy._fitness = None return self_copy def mutate(self): """ Implement the mutation phase, invoking stochastic mutation method on the entire organism. """ mutant = self.copy() fitness = self.fitness() # If random value meets mutation probability, then mutate! if len(self.mutators) > 0 and random() < self.mutProb: # choose a random mutator while True: mutator = eval(choice(self.mutators)) operator = mutator(mutant) #mutator, args = mutatorSet #operator = mutator(mutant, **args) # TODO: Replace hard-coded values with variable parameters if self.limit_mutation: if fitness < 30 and operator.mutationImpact == "LARGE": continue elif fitness < 10 and operator.mutationImpact == "MEDIUM": continue else: break else: break mutant = operator.mutate() return mutant def xmlDump(self, fileobject): savePatternToXml(self, fileobject, False) def xmlDumps(self): song = savePatternToXml(self, None, True) return song.toxml() class MultiObjectivePatternOrganism(PatternOrganism): """ Pattern Organism that treats fitness as a vector of objective values for the sake of multiobjective optimization. """ def fitness(self): # Evaluate the fitness once. if not hasattr(self, '_fitness') or self._fitness is None: self._fitness = [] if len(self.trajectory_set) > 0: # Evaluate each trajectory. for trajectory in self.trajectory_set: fitness_function = eval(trajectory.function.name) self._fitness.append(fitness_function(self, trajectory)) return self._fitness def mutate(self): """Mutates the individual without regarding fitness.""" mutant = self.copy() if len(self.mutators) > 0 and random() < self.mutProb: # TODO: Mutators should handle mutation with a static method. # Choose a random mutator. mutator = eval(choice(self.mutators)) operator = mutator(mutant) mutant = operator.mutate() return mutant class PatternPopulation(Population): """ Contains and manages a population of 2 dimensional patterns (arrays). """ def diversity(self, n=10): """ Calculate the diversity of the top n organisms in the population. """ similarities = [] for i in xrange(n - 1): g1 = [y.value for x in self.organisms[i].genes.tolist() for y in x] for j in xrange(i+1, n): g2 = [y.value for x in self.organisms[j].genes.tolist() for y in x] s = similarity(g1, g2) similarities.append(s) total = sum(similarities) length = len(similarities) diversity = total / length return diversity def gen(self, nfittest=None, nchildren=None): """ Executes a generation of the population. """ # Add new random organisms, if required if self.numNewOrganisms: for i in xrange(self.numNewOrganisms): self.add(self.__class__()) # Select n individuals to be parents parents = self.selector.select(self.organisms, self.childCount) children = [] for i in xrange(self.childCount): # Choose first parent parent1 = parent2 = choice(parents) # Choose second parent not equal to first parent maxwait = 400 i = 0 while parent1.genes.tolist() == parent2.genes.tolist(): if i > maxwait: # Try another random set of parents if the first one didn't work. parent1 = parent2 = choice(parents) parent2 = choice(parents) i += 1 # Reproduce child1, child2 = parent1 + parent2 # Mutate children child1 = child1.mutate() child2 = child2.mutate() children.extend([child1, child2]) children.extend(parents) children.sort() # Set parents and children as the new population self.organisms = children def worst(self): return max(self) class DictPopulation(Population): def __init__(self, childCount, selector, *items, **kwargs): self.max_id = 0 self.organisms = {} self.childCount = childCount self.selector = selector if kwargs.has_key('species'): species = self.species = kwargs['species'] else: species = self.species if kwargs.has_key('init'): init = self.initPopulation = kwargs['init'] else: init = self.initPopulation if not items: for i in xrange(init): self.add(species()) def __getitem__(self, index): return self.organisms[index] def add(self, *args): for arg in args: if isinstance(arg, Organism): self.organisms[self.max_id] = arg self.max_id += 1 else: self.add(arg) def fitness(self): """ returns the average fitness value for the population """ raise Exception("Average fitness cannot be meaningfully calculated for organisms with multiobjective fitness vectors.") def best(self): return max(self.organisms.values()) def worst(self): return min(self.organisms.values()) def diversity(self, n=10): """ Calculate the diversity of the top n organisms in the population. """ similarities = [] for i in xrange(n - 1): g1 = [y.value for x in self.organisms[i].genes.tolist() for y in x] for j in xrange(i+1, n): g2 = [y.value for x in self.organisms[j].genes.tolist() for y in x] s = similarity(g1, g2) similarities.append(s) total = sum(similarities) length = len(similarities) diversity = total / length return diversity class MultiObjectiveDictPopulation(DictPopulation): def __init__(self, pisa_prefix, pisa_period, dimensions, *items, **kwargs): self.pisa_prefix = pisa_prefix self.pisa_period = pisa_period self.pisa_files = {} for key, value in pisa.files.items(): self.pisa_files[key] = "%s%s" % (pisa_prefix, value) # Write 0 to the state file. pisa.write_file(self.pisa_files['state'], pisa.STATE_0) # Read common parameters. self.pisa_parameters = pisa.read_configuration_file(self.pisa_files['configuration']) print "Loaded parameters: %s\n" % self.pisa_parameters # Write preset parameters to configuration file. self.pisa_parameters['dim'] = dimensions pisa.write_configuration_file(self.pisa_files['configuration'], self.pisa_parameters) # Generate the initial population. kwargs['init'] = self.pisa_parameters['alpha'] super(MultiObjectiveDictPopulation, self).__init__(*items, **kwargs) # Write initial population into init pop file fitnesses = [[key] + org.fitness() for key, org in self.organisms.items()] pisa.write_file(self.pisa_files['initial_population'], fitnesses, self.pisa_parameters['dim']) # Write 1 to the state file pisa.write_file(self.pisa_files['state'], pisa.STATE_1) def __del__(self): if hasattr(self, 'state') and self.state != pisa.STATE_4: # Write 6 to state file pisa.write_file(self.pisa_files['state'], pisa.STATE_6) def gen(self, nfittest=None, nchildren=None): """Executes a generation of the population.""" # If state is 4, return False. If state is 2, process selector output. # Otherwise, read state file every n seconds where n is the poll time. while True: self.state = pisa.read_state_file(self.pisa_files['state']) if self.state == pisa.STATE_4: #print "Selector has terminated\n" return False elif self.state == pisa.STATE_2: break else: # Sleep for n seconds, then continue. #print "Waiting for selector\n" time.sleep(self.pisa_period) continue # Load sample from sample file. #print "Read sample file\n" sample = pisa.read_data_file(self.pisa_files['sample']) # Load archive from archive file. archive = pisa.read_data_file(self.pisa_files['archive']) # Clean up local population based on archive contents. ids = self.organisms.keys() for id in ids: if id not in archive: del(self.organisms[id]) # Pair up and mate parents from sample with mutation. offspring = {} for i in xrange(self.pisa_parameters['lambda']): # Choose the first parent. parent_index_1 = parent_index_2 = choice(sample) # Choose the second parent not equal to first parent. while parent_index_1 == parent_index_2: parent_index_2 = choice(sample) # Reproduce and mutate. children = self.organisms[parent_index_1] + self.organisms[parent_index_2] child = choice(children) child = child.mutate() # Calculate fitness and add child. offspring[self.max_id] = child.fitness() self.add(child) # Write offspring to offspring file pisa.write_file(self.pisa_files['offspring'], offspring, self.pisa_parameters['dim']) # Write 3 to the state file pisa.write_file(self.pisa_files['state'], pisa.STATE_3) # Save the sample. self.sample = sample
Python
# Django settings for fitbeat_project project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('John Huddleston', 'huddlej@gmail.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = '/home/huddlej/fitbeats/fitbeat_project/research.db' DATABASE_USER = '' DATABASE_PASSWORD = '' DATABASE_HOST = '' DATABASE_PORT = '' # Local time zone for this installation. All choices can be found here: # http://www.postgresql.org/docs/current/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE TIME_ZONE = 'America/Los_Angeles' # Language code for this installation. All choices can be found here: # http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes # http://blogs.law.harvard.edu/tech/stories/storyReader$15 LANGUAGE_CODE = 'en-us' SITE_ID = 1 # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. # Example: "http://media.lawrence.com" MEDIA_URL = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = '5&02cw1#gn)gl0o%a*t(p$7yl17ny-^an$v22dr%_pq%d%$rb)' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', #'fitbeat_project.django-cas.middleware.CASMiddleware', 'django.middleware.doc.XViewMiddleware', 'fitbeat_project.middleware.threadlocals.ThreadLocals', ) #AUTHENTICATION_BACKENDS = ( #'fitbeat_project.django-cas.backend.CASBackend', #) #CAS_SERVICE_URL = 'https://websso.wwu.edu/cas/' #CAS_POPULATE_USER = 'fitbeat_project.utils.caslogin' ROOT_URLCONF = 'fitbeat_project.urls' TEMPLATE_DIRS = ( "/home/huddlej/fitbeats/fitbeat_project/fitbeats/templates", "/home/huddlej/fitbeats/fitbeat_project/templates", ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'fitbeat_project.fitbeats', # 'fitbeat_project.django-cas', )
Python
from django.conf import settings def caslogin(user): print "Hello!" print "User: ", user def get_applications(clean=True): if clean: return [".".join(app.split(".")[1:]) for app in settings.INSTALLED_APPS if not app.startswith('django')] else: return [app for app in settings.INSTALLED_APPS if not app.startswith('django')]
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^login/$', 'fitbeat_project.fitbeats.views.user_login'), (r'^logout/$', 'fitbeat_project.fitbeats.views.user_logout'), (r'^admin/', include('django.contrib.admin.urls')), (r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/huddlej/fitbeats/media'}), (r'^', include('fitbeat_project.fitbeats.urls')), )
Python
# threadlocals middleware try: from threading import local except ImportError: from django.utils._threading_local import local _thread_locals = local() def get_current_user(): return getattr(_thread_locals, 'user', None) class ThreadLocals(object): """Middleware that gets various objects from the request object and saves them in thread local storage.""" def process_request(self, request): _thread_locals.user = getattr(request, 'user', None)
Python
import sys sys.path.append('../') from django.db import models from django.db.models import permalink from django.contrib.auth.models import User from django.template.defaultfilters import slugify from functions import bezier TRAJECTORY_TYPES = ( ('coordinate', 'Coordinate'), ('boolean', 'Boolean'), ('integer', 'Integer'), ('float', 'Float'), ) class Parameter(models.Model): name = models.CharField(maxlength=100, editable=False) value = models.FloatField() def __str__(self): return "%s: %f" % (self.name, self.value) class Admin: search_fields = ['name'] class Crossover(models.Model): # TODO: Crossover could implement __call__ and use __import__ to execute # the right method. name = models.CharField(maxlength=100) def __str__(self): return self.name def __repr__(self): return "".join((self.name.replace(" ", ""), self.__class__.__name__)) def get_short_name(self): return repr(self) class Admin: pass class Selector(models.Model): name = models.CharField(maxlength=100) parameters = models.ManyToManyField(Parameter, blank=True) def __str__(self): return self.name def get_short_name(self): return "%s%s" % (self.name.replace(" ", ""), self.__class__.__name__) class Admin: pass class Mutator(models.Model): name = models.CharField(maxlength=100) mutate_all_rows = models.BooleanField(help_text="""Whether this mutator should mutate all instrument rows or just a randomly selected row.""") def __str__(self): return "%s%s" % (self.name, self.mutate_all_rows and " (all rows)" or "") def get_short_name(self): return "%s%s%s" % (self.name.replace(" ", ""), self.mutate_all_rows and "AllRows" or "", self.__class__) class Admin: pass class Meta: ordering = ('name', 'mutate_all_rows') class Instrument(models.Model): CATEGORY_CHOICES = ( ('L', 'Low'), ('M', 'Mid'), ('H', 'High'), ) name = models.CharField(maxlength=200) category = models.CharField(maxlength=50, choices=CATEGORY_CHOICES) sequence_number = models.IntegerField() def __str__(self): return "%i: %s (%s)" % (self.sequence_number, self.name, self.category) class Admin: pass class Meta: ordering = ('sequence_number',) class Pattern(models.Model): DEFAULT_VALUES = { 'gene': { 'mutation_probability': 0.02, }, 'organism': { 'mutation_probability': 0.02, 'crossover_rate': 0.6, }, 'population': { 'max_generations': 50, 'initial_size': 1000, 'new_children': 200, } } length = models.IntegerField(help_text="The number of beats in this pattern.") instruments = models.ManyToManyField(Instrument) selector = models.ForeignKey(Selector, help_text="Determines how fit patterns will be selected.") crossover = models.ForeignKey(Crossover, help_text="Determines how individuals will reproduce.") mutators = models.ManyToManyField(Mutator, help_text="Introduces random diversity to the population.") parameters = models.ManyToManyField(Parameter, editable=False) author = models.ForeignKey(User, editable=False) def save(self): # Create parameters for new patterns if self.id and self.parameters.count() == 0: for key in self.DEFAULT_VALUES.keys(): for name in self.DEFAULT_VALUES[key].keys(): p = Parameter(name="%s_%s" % (key, name), value=self.DEFAULT_VALUES[key][name]) p.save() self.parameters.add(p) super(Pattern, self).save() def get_absolute_url(self): return ('fitbeats.views.edit_pattern', [str(self.id)]) get_absolute_url = permalink(get_absolute_url) def __str__(self): return "Pattern %i (%ix%i, %s, %s)" % (self.id, self.length, self.instrument_length, self.selector, self.crossover) def _instrument_length(self): if self.id: return self.instruments.count() else: return 0 instrument_length = property(_instrument_length) def get_max_generations(self): return 50 class Admin: list_display = ['id', 'author', 'length', 'instrument_length', 'selector', 'crossover'] class FitnessFunction(models.Model): name = models.CharField(maxlength=100) display_name = models.CharField(maxlength=100) trajectory_type = models.CharField(maxlength=10, choices=TRAJECTORY_TYPES) def __str__(self): return self.display_name or self.name class Admin: pass class Meta: verbose_name = "Fitness rule" verbose_name_plural = "Fitness rules" class FitnessTrajectory(models.Model): pattern = models.ForeignKey(Pattern, editable=False) function = models.ForeignKey(FitnessFunction, verbose_name="Rhythmic rule") trajectory_type = models.CharField(maxlength=10, choices=TRAJECTORY_TYPES, editable=False) def __str__(self): return "%s (%s)" % (self.function, self.trajectory_type) def _trajectory_set(self): if self.trajectory_type == "coordinate": return self.fitnesstrajectorycoordinate_set.order_by('sequence_number') elif self.trajectory_type == "boolean": return self.fitnesstrajectoryboolean_set.order_by('instrument') elif self.trajectory_type == "integer": return self.fitnesstrajectoryinteger_set.order_by('instrument') elif self.trajectory_type == "float": return self.fitnesstrajectoryfloat_set.order_by('instrument') else: return None trajectory_set = property(_trajectory_set) def get_absolute_url(self): return ('fitbeats.views.edit_trajectory', [str(self.pattern.id), str(self.id)]) get_absolute_url = permalink(get_absolute_url) def calculate_trajectory(self): patternLength = self.pattern.length if self.trajectory_type == "coordinate": values = [(v.x, v.y) for v in self.trajectory_set] t = 0.0 self.values = [] # calculate the initial value self.values.append(bezier(values[0], values[1], values[2], values[3], t)) dt = 1.0 / (patternLength - 1) for i in xrange(1, patternLength): t += dt self.values.append(bezier(values[0], values[1], values[2], values[3], t)) elif self.trajectory_type == "boolean": ft_set = self.trajectory_set.order_by('instrument') self.values = [i for i in xrange(ft_set.count()) if ft_set[i].value] else: ft_set = self.trajectory_set.order_by('instrument') self.values = [(i, ft_set[i].value) for i in xrange(ft_set.count())] class Meta: verbose_name_plural = "Fitness trajectories" class Admin: pass class FitnessTrajectoryCoordinate(models.Model): trajectory = models.ForeignKey(FitnessTrajectory, editable=False, null=True) sequence_number = models.IntegerField() value = models.CharField(maxlength=10, verbose_name="coordinate") x = models.FloatField(editable=False) y = models.FloatField(editable=False) def save(self): if self.value.find(",") > 0: values = self.value.split(",") self.x = float(values[0].strip()) self.y = float(values[1].strip()) else: self.x, self.y = 0.0, 0.0 super(FitnessTrajectoryCoordinate, self).save() def __str__(self): return "(%f, %f)" % (self.x, self.y) """ def _value(self): return (self.x, self.y) value = property(_value) """ class Admin: pass class FitnessTrajectoryInteger(models.Model): trajectory = models.ForeignKey(FitnessTrajectory, editable=False, null=True) instrument = models.ForeignKey(Instrument) value = models.IntegerField() def __str__(self): return str(self.value) class Admin: pass class FitnessTrajectoryBoolean(models.Model): trajectory = models.ForeignKey(FitnessTrajectory, editable=False, null=True) instrument = models.ForeignKey(Instrument) value = models.BooleanField() def __str__(self): return "%s - %s" % (self.trajectory, str(self.value)) class Admin: pass class FitnessTrajectoryFloat(models.Model): trajectory = models.ForeignKey(FitnessTrajectory, editable=False, null=True) instrument = models.ForeignKey(Instrument) value = models.FloatField() def __str__(self): return str(self.value) class Admin: pass class PatternInstance(models.Model): pattern = models.ForeignKey(Pattern, editable=False) fitness = models.FloatField() value = models.TextField() class Admin: pass """ class PatternInstanceComplete: length = models.IntegerField(help_text="The number of beats in this pattern.") instrument_length = models.IntegerField(editable=False) instruments = models.TextField(help_text="Instruments used for this pattern.") selector = models.CharField(maxlength=100) crossover = models.CharField(maxlength=100) mutators = models.CharField(maxlength=250) parameters = models.TextField() value = models.XMLField(schema_path="") author = models.ForeignKey(User) class Piece(models.Model): name = models.CharField(maxlength=150) patterns = models.ManyToManyField(Pattern) author = models.ForeignKey(User) """
Python
# Forms from django import newforms as forms class PatternForm(forms.Form): length = forms.IntegerField(maxlength=100)
Python
from django.conf.urls.defaults import * from django.views.generic.list_detail import object_list import fitbeats from fitbeats.models import Pattern base_generic_dict = {'paginate_by': 20} pattern_info_dict = dict(base_generic_dict, queryset=Pattern.objects.all(), template_object_name='pattern', extra_context={'title': "View Patterns", 'heading': "View Patterns",}) urlpatterns = patterns('', url(r'^patterns/$', object_list, pattern_info_dict, name='view_patterns'), url(r'^patterns/add/$', 'fitbeats.views.add_pattern', name='add_pattern'), (r'^patterns/(\d+)/$', 'fitbeats.views.edit_pattern'), # Trajectories (r'^patterns/(\d+)/trajectories/$', 'fitbeats.views.view_trajectories'), url(r'^patterns/(\d+)/trajectories/add/(\w+)/$', 'fitbeats.views.add_trajectory', name='add_trajectory'), url(r'^patterns/(\d+)/trajectories/(\d+)/$', 'fitbeats.views.edit_trajectory', name='edit_trajectory'), url(r'^patterns/(\d+)/trajectories/delete/(\d+)/$', 'fitbeats.views.delete_trajectory', name='delete_trajectory'), (r'^patterns/(\d+)/trajectories/(\d+)/xml/$', 'fitbeats.views.xml_trajectory'), # Parameters url(r'^patterns/(\d+)/parameters/$', 'fitbeats.views.edit_parameters', name='edit_parameters'), # Evolution (r'^patterns/(\d+)/evolve/$', 'fitbeats.views.evolve_pattern'), (r'^patterns/(\d+)/evolve/run/$', 'fitbeats.views.evolve_pattern_run'), (r'^patterns/(\d+)/evolve/display/$', 'fitbeats.views.evolve_pattern_display'), (r'^patterns/(\d+)/evolve/stop/$', 'fitbeats.views.evolve_pattern_stop'), (r'^patterns/instances/(\d+)/$', 'fitbeats.views.view_pattern_instance'), (r'^$', 'fitbeats.views.index'), )
Python
""" widgets.py Custom widgets for base_case forms. """ from django import newforms as forms class TextHiddenInput(forms.widgets.HiddenInput): """ A widget that allows split date and time inputs to have separate attributes """ is_hidden = False def __init__(self, attrs=None): if attrs is None or not attrs.has_key('display'): self.display = "Unknown instrument" else: self.display = attrs['display'] del attrs['display'] super(TextHiddenInput, self).__init__(attrs) def render(self, name, value, attrs=None): output = super(TextHiddenInput, self).render(name, value, attrs) return u'%s%s' % (output, self.display)
Python
""" functions.py Joining functions and helper functions. """ from random import randint from math import floor, ceil from collections import deque """ Joining Functions These are simple mathematical functions linearly parameterized by the constants "a" and "b" which shift the function domain to fit the user's requested initial and final fitness values. """ def bezier(p0, p1, p2, p3, t): """ @param p0 @param p1 @param p2 @param p3 @param t """ #calculate the polynomial coefficients cx = 3.0 * (p1[0] - p0[0]) bx = 3.0 * (p2[0] - p1[0]) - cx ax = p3[0] - p0[0] - cx - bx cy = 3.0 * (p1[1] - p0[1]) by = 3.0 * (p2[1] - p1[1]) - cy ay = p3[1] - p0[1] - cy - by # calculate the curve point at parameter value t tSquared = t * t tCubed = tSquared * t x = (ax * tCubed) + (bx * tSquared) + (cx * t) + p0[0] y = (ay * tCubed) + (by * tSquared) + (cy * t) + p0[1] result = (x, y) return result """ Helper functions """ def calculate_magnitude(d): dmagnitude = 0 for i in d: dmagnitude += i**2 dmagnitude = dmagnitude ** 0.5 return dmagnitude def normalize(d): dnorm = [] dmagnitude = calculate_magnitude(d) for i in d: dnorm.append(float(i) / dmagnitude) return dnorm def calculate_cos(x, y): """ Calculate the cosine simlarity between two vectors @param list x @param list y @return float cos the cosine similarity between the two vectors """ x = normalize(x) y = normalize(y) cos = 0 for key in xrange(len(x)): x_i = x[key] y_i = y[key] cos += x_i*y_i return cos def similarity(x, y): return calculate_cos(x, y)
Python
import pickle import random import subprocess import signal from xml.dom.minidom import parse from django import newforms as forms from django.db import transaction from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.template import RequestContext from fitbeat_project.fitbeats.models import * from fitbeat_project.fitbeats.widgets import TextHiddenInput import evolve_beats COORDINATE_TRAJECTORY_NAMES = ('Initial', 'Control Point 1', 'Control Point 2', 'Final') STATFILE = "/home/huddlej/fitbeats/testData.txt" STOPFILE = "/home/huddlej/fitbeats/stopfile.txt" def index(request): try: del(request.session['piece']) except(KeyError): pass if request.user.is_authenticated(): currentUser = True else: currentUser = False title = "Rhythm Research" return render_to_response('fitbeats/index.html', {'title': title, 'currentUser': currentUser}) def user_login(request): if request.user.is_authenticated(): return HttpResponseRedirect('/') errorMessage = None if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/') else: errorMessage = "Login failed" title = "Login" return render_to_response('fitbeats/login.html', {'title': title, 'errorMessage': errorMessage}) def user_logout(request): logout(request) return HttpResponseRedirect('/') def add_pattern(request): #fields = ('length', 'instruments', 'selector', 'crossover', 'mutators') PatternForm = forms.form_for_model(Pattern) if request.method == "POST": data = request.POST else: data = None form = PatternForm(data) if form.is_valid(): pattern = Pattern(length=form.cleaned_data['length'], selector=form.cleaned_data['selector'], crossover=form.cleaned_data['crossover'], author=request.user) pattern.save() pattern.instruments = form.cleaned_data['instruments'] pattern.mutators = form.cleaned_data['mutators'] pattern.save() #mutators=form.cleaned_data['mutators'], return HttpResponseRedirect(pattern.get_absolute_url()) title = heading = "Add Pattern" context = {'title': title, 'heading': heading, 'form': form} return render_to_response('fitbeats/edit_pattern.html', context, context_instance=RequestContext(request)) add_pattern = login_required(add_pattern) def edit_pattern(request, id): fields = ('length', 'instruments', 'selector', 'crossover', 'mutators') pattern = get_object_or_404(Pattern, pk=id, author__pk=request.user.id) PatternForm = forms.form_for_instance(pattern) if request.method == "POST": form = PatternForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(pattern.get_absolute_url()) else: form = PatternForm() title = heading = "Edit Pattern" context = {'title': title, 'heading': heading, 'form': form, 'pattern': pattern} return render_to_response('fitbeats/edit_pattern.html', context, context_instance=RequestContext(request)) edit_pattern = login_required(edit_pattern) def view_trajectories(request, pattern_id): pattern = get_object_or_404(Pattern, pk=pattern_id, author__pk=request.user.id) trajectories = pattern.fitnesstrajectory_set.all() title = heading = "View Trajectories" context = {'title': title, 'heading': heading, 'pattern': pattern, 'trajectory_types': TRAJECTORY_TYPES, 'trajectories': trajectories} return render_to_response('fitbeats/view_trajectories.html', context, context_instance=RequestContext(request)) view_trajectories = login_required(view_trajectories) @transaction.commit_manually def add_trajectory(request, pattern_id, trajectory_type): pattern = get_object_or_404(Pattern, pk=pattern_id, author__pk=request.user.id) value_forms = [] if request.method == "POST": data = request.POST else: data = None functions = FitnessFunction.objects.filter(trajectory_type=trajectory_type) functions = tuple([(function.id, str(function)) for function in functions]) TrajectoryForm = forms.form_for_model(FitnessTrajectory) TrajectoryForm.base_fields['function'].widget = forms.widgets.Select(choices=functions) TrajectoryValueForm = eval("forms.form_for_model(FitnessTrajectory%s)" % trajectory_type.capitalize()) if trajectory_type == "coordinate": form_count = 4 for i in xrange(0, form_count): TrajectoryValueForm.base_fields['sequence_number'].widget = TextHiddenInput(attrs={'value': i, 'display': COORDINATE_TRAJECTORY_NAMES[i]}) value_forms.append(TrajectoryValueForm(data, prefix=str(i))) else: value_id = 1 for instrument in pattern.instruments.all().order_by('sequence_number'): TrajectoryValueForm.base_fields['instrument'].widget = TextHiddenInput(attrs={'value': instrument.id, 'display': instrument.name}) value_forms.append(TrajectoryValueForm(data, prefix=str(value_id))) value_id += 1 form = TrajectoryForm(data) if form.is_valid(): # Add trajectory trajectory = FitnessTrajectory(pattern=pattern, function=form.cleaned_data['function'], trajectory_type=trajectory_type) trajectory.save() # Add values errors = [] valid_value_forms_count = 0 for f in value_forms: if f.is_valid(): valid_value_forms_count += 1 value = f.save() value.trajectory = trajectory value.save() else: errors.append(f.errors) # Only commit changes if at least one of the value forms validated if valid_value_forms_count > 0: transaction.commit() return HttpResponseRedirect(trajectory.get_absolute_url()) else: transaction.rollback() trajectory_types = dict(TRAJECTORY_TYPES) title = heading = "Add %s Trajectory" % trajectory_types[trajectory_type] context = {'title': title, 'heading': heading, 'pattern': pattern, 'trajectory_type': trajectory_type, 'trajectory_types': TRAJECTORY_TYPES, 'form': form, 'value_forms': value_forms, } return render_to_response('fitbeats/edit_trajectory.html', context, context_instance=RequestContext(request)) add_trajectory = login_required(add_trajectory) add_trajectory = transaction.commit_manually(add_trajectory) def edit_trajectory(request, pattern_id, id): pattern = get_object_or_404(Pattern, pk=pattern_id, author__pk=request.user.id) value_forms = [] if request.method == "POST": data = request.POST else: data = None trajectory = get_object_or_404(FitnessTrajectory, pk=id, pattern__pk=pattern_id) trajectory_type = trajectory.trajectory_type functions = FitnessFunction.objects.filter(trajectory_type=trajectory_type) functions = tuple([(function.id, str(function)) for function in functions]) TrajectoryForm = forms.form_for_instance(trajectory) TrajectoryForm.base_fields['function'].widget = forms.widgets.Select(choices=functions) #trajectory_values = eval("trajectory.fitnesstrajectory%s_set.all()" % trajectory_type) trajectory_values = trajectory.trajectory_set value_id = 1 for v in trajectory_values: TrajectoryValueForm = forms.form_for_instance(v) if trajectory_type == "coordinate": TrajectoryValueForm.base_fields['sequence_number'].widget = TextHiddenInput(attrs={'value': v.sequence_number, 'display': COORDINATE_TRAJECTORY_NAMES[v.sequence_number]}) else: TrajectoryValueForm.base_fields['instrument'].widget = TextHiddenInput(attrs={'value': v.instrument.id, 'display': v.instrument.name}) value_forms.append(TrajectoryValueForm(data, prefix=str(value_id))) value_id += 1 form = TrajectoryForm(data) if form.is_valid(): # Update trajectory form.save() # Update values errors = [] valid_value_forms_count = 0 for f in value_forms: if f.is_valid(): valid_value_forms_count += 1 value = f.save() else: errors.append(f.errors) # Only commit changes if at least one of the value forms validated if valid_value_forms_count > 0: transaction.commit() return HttpResponseRedirect(trajectory.get_absolute_url()) else: transaction.rollback() raise Exception(errors) trajectory_types = dict(TRAJECTORY_TYPES) title = heading = "Edit %s Trajectory" % trajectory_types[trajectory_type] context = {'title': title, 'heading': heading, 'pattern': pattern, 'trajectory': trajectory, 'trajectory_type': trajectory_type, 'trajectory_types': TRAJECTORY_TYPES, 'form': form, 'value_forms': value_forms, } return render_to_response('fitbeats/edit_trajectory.html', context, context_instance=RequestContext(request)) edit_trajectory = login_required(edit_trajectory) edit_trajectory = transaction.commit_manually(edit_trajectory) def delete_trajectory(request, pattern_id, id): pattern = get_object_or_404(Pattern, pk=pattern_id, author__pk=request.user.id) trajectory = get_object_or_404(FitnessTrajectory, pk=id, pattern__pk=pattern_id) trajectory.delete() return HttpResponseRedirect("%strajectories/" % pattern.get_absolute_url()) delete_trajectory = login_required(delete_trajectory) def edit_parameters(request, pattern_id): pattern = get_object_or_404(Pattern, pk=pattern_id, author__pk=request.user.id) if request.method == "POST": data = request.POST else: data = None parameters = pattern.parameters.all().order_by('name') parameter_forms = [] value_id = 1 errors = [] valid_form_count = 0 for parameter in parameters: # population_max_generations -> Population Max Generations label_name = " ".join([s.capitalize() for s in parameter.name.split("_")]) ParameterForm = forms.form_for_instance(parameter) ParameterForm.base_fields['value'].label = label_name f = ParameterForm(data, prefix=str(value_id)) parameter_forms.append(f) value_id += 1 if data is not None: if f.is_valid(): valid_form_count += 1 value = f.save() else: errors.append(f.errors) if data is not None: # Only commit changes if at least one of the value forms validated if valid_form_count > 0: transaction.commit() return HttpResponseRedirect("%sparameters/" % pattern.get_absolute_url()) else: transaction.rollback() raise Exception("Could not save all parameters: %s" % ", ".join(errors)) title = heading = "Edit Parameters" context = {'title': title, 'heading': heading, 'pattern': pattern, 'parameter_forms': parameter_forms, } return render_to_response('fitbeats/edit_parameters.html', context, context_instance=RequestContext(request)) edit_parameters = login_required(edit_parameters) edit_parameters = transaction.commit_manually(edit_parameters) @login_required def evolve_pattern(request, pattern_id): pattern = get_object_or_404(Pattern, pk=pattern_id, author__pk=request.user.id) # Clear the existing data fhandle = open(STATFILE, "w") fhandle.close() fhandle = open(STOPFILE, "w") fhandle.close() title = heading = "Evolve Pattern" context = {'title': title, 'heading': heading, 'pattern': pattern, } return render_to_response('fitbeats/evolve.html', context, context_instance=RequestContext(request)) @login_required def evolve_pattern_display(request, pattern_id): pattern = get_object_or_404(Pattern, pk=pattern_id, author__pk=request.user.id) pattern_instances = pattern.patterninstance_set.all() instruments = pattern.instruments.order_by('sequence_number') instruments = [[instrument.name] for instrument in instruments] try: fhandle = open(STATFILE, "r") data = pickle.load(fhandle) fhandle.close() if isinstance(data, dict) and data.has_key('is_done'): is_done = data['is_done'] fitness = data['bestfitness'] population_fitness = data['popfitness'] diversity = data['diversity'] best_pattern = data['best_pattern'] best_pattern = best_pattern.genes.tolist() for i in xrange(len(instruments)): instruments[i].extend(best_pattern[i]) best_pattern = instruments generation = data['generation'] else: raise Exception except: best_pattern = [] is_done = False fitness = None population_fitness = None diversity = None generation = 0 title = heading = "Best Pattern" context = {'pattern': pattern, 'pattern_instances': pattern_instances, 'best_pattern': best_pattern, 'is_done': is_done, 'fitness': fitness, 'population_fitness': population_fitness, 'diversity': diversity, 'generation': generation } return render_to_response('fitbeats/evolve_pattern_results.html', context, context_instance=RequestContext(request)) @login_required def evolve_pattern_run(request, pattern_id): pattern = get_object_or_404(Pattern, pk=pattern_id, author__pk=request.user.id) request.session[str(pattern_id)] = subprocess.Popen(["python", "/home/huddlej/fitbeats/evolve_beats.py", "-d", str(pattern_id)]).pid return HttpResponse("Finished evolving pattern %s." % pattern) @login_required def evolve_pattern_stop(request, pattern_id): pattern = get_object_or_404(Pattern, pk=pattern_id, author__pk=request.user.id) stop = True fhandle = open(STOPFILE, "w") pickle.dump(stop, fhandle) fhandle.close() return HttpResponseRedirect("%sevolve/display/" % pattern.get_absolute_url()) @login_required def view_pattern_instance(request, instance_id): instance = get_object_or_404(PatternInstance, pk=instance_id) response = HttpResponse(mimetype="text/xml") response['Content-Disposition'] = 'attachment; filename=yoursong.h2song' response.write(instance.value) return response def xml_trajectory(request, pattern_id, id): bezFilename = "/home/huddlej/fitbeats/media/xmltest.xml" pattern = get_object_or_404(Pattern, pk=pattern_id, author__pk=request.user.id) trajectory = get_object_or_404(FitnessTrajectory, pk=id, pattern__pk=pattern_id) pattern.length = pattern.length trajectory_set = trajectory.trajectory_set rowMax = 150 xScale = 280 / pattern.length yScale = 10 x1 = trajectory_set[0].x y1 = rowMax - (trajectory_set[0].y * yScale) cx1 = trajectory_set[1].x * xScale cy1 = rowMax - (trajectory_set[1].y * yScale) cx2 = trajectory_set[2].x * xScale cy2 = rowMax - (trajectory_set[2].y * yScale) x2 = trajectory_set[3].x * xScale y2 = rowMax - (trajectory_set[3].y * yScale) bez = parse(bezFilename) bezsh = bez.getElementsByTagName("shape")[0] vals = ["x1", "y1", "x2", "y2", "cx1", "cy1", "cx2", "cy2"] for val in vals: bezsh.setAttribute(val, str(eval(val))) #print bez.toxml() bezFile = open(bezFilename, "w") bez.writexml(bezFile) bezFile.close() return HttpResponseRedirect('/site_media/xmltest.xml') return HttpResponseRedirect('/xml/')
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
"""Lower level method to support the PISA variator interface.""" files = { "configuration": "cfg", "initial_population": "ini", "archive": "arc", "sample": "sel", "offspring": "var", "state": "sta" } STATE_0 = 0 STATE_1 = 1 STATE_2 = 2 STATE_3 = 3 STATE_4 = 4 STATE_5 = 5 STATE_6 = 6 class CorruptedDataException(Exception): pass def read_data_file(filename): f = open(filename) try: lines = f.readlines() if len(lines) <= 2: raise CorruptedDataException("File %s is empty or improperly \ formatted." % filename) expected_number_of_elements = int(lines.pop(0)) end_of_file = lines.pop() actual_number_of_elements = len(lines) if actual_number_of_elements != expected_number_of_elements or end_of_file != "END": raise CorruptedDataException("File %s does not contain the expected number of values. Expected %s values, found %s." % (filename, expected_number_of_elements, actual_number_of_elements)) data = None for line in lines: values = line.split() index = int(values.pop(0)) if len(values) == 0: # No more values means this is an index file. if data is None: data = [] try: value = int(index) except: value = float(index) data.append(value) else: # More values means this is a fitness value file. if data is None: data = {} try: values = map(int, values) except: values = map(float, values) data[index] = values f.close() f = open(filename, "w") f.write("0") return data finally: f.close() def read_configuration_file(filename): f = open(filename) try: lines = f.readlines() if len(lines) == 0: raise CorruptedDataException("File %s is empty." % filename) data = {} for line in lines: values = line.split() if len(values) > 0: index = values[0] try: value = int(values[1]) except: value = float(values[1]) data[index] = value if len(data) == 0: raise CorruptedDataException("Configuraton file %s is empty." % filename) return data finally: f.close() def read_state_file(filename): f = open(filename) try: state = f.readline() if len(state) == 0: raise CorruptedDataException("State file %s is empty." % filename) try: state = int(state) return state except ValueError: raise CorruptedDataException("State file %s contains invalid state data." % filename) finally: f.close() def write_file(filename, data, dimensions=0): f = open(filename, "w") try: if isinstance(data, list) or isinstance(data, tuple): elements = len(data) * (dimensions + 1) f.write("%i\n" % elements) for value in data: if isinstance(value, list) or isinstance(value, tuple): f.write(" ".join(map(str, value))) else: f.write(str(value)) f.write("\n") f.write("END") elif isinstance(data, dict): elements = len(data) * (dimensions + 1) f.write("%i\n" % elements) for key, values in data.items(): line = [key] + list(values) f.write(" ".join(map(str, line))) f.write("\n") f.write("END") else: f.write(str(data)) f.write("\n") finally: f.close() def write_configuration_file(filename, data): order = ('alpha', 'mu', 'lambda', 'dim') f = open(filename, "w") for key in order: f.write("%s %s\n" % (key, data[key])) f.close()
Python
from xml.dom.minidom import parse import Numeric SONG_TEMPLATE_PATH = "/home/huddlej/fitbeats/song_template.h2song" def savePatternToXml(pattern, fileobject, debug=False): """ Open the Hydrogen song template, write the new beats, and save the resulting XML into a new file. @param PatternOrganism pattern @param string filename @param boolean debug whether if true, will print xml instead of saving to file """ pattern_length = pattern.length instrument_length = pattern.instrument_length pattern_genes = pattern.genes.tolist() instruments = [i.sequence_number for i in pattern.instruments] song = parse(SONG_TEMPLATE_PATH) xml_pattern = song.getElementsByTagName("pattern")[0] size = int(xml_pattern.getElementsByTagName("size")[0].childNodes[0].nodeValue) increment = size / pattern_length for row in xrange(instrument_length): """ At the beginning of a new pattern line, increment the instrument and select the next note list. """ instrument_value = instruments[row] noteList = xml_pattern.getElementsByTagName("noteList")[instrument_value] for column in xrange(pattern_length): if(pattern_genes[row][column] == 0): """ Don't add notes for silence """ continue position_value = column * increment note = song.createElement("note") position = song.createElement("position") position.appendChild(song.createTextNode(str(position_value))) note.appendChild(position) velocity = song.createElement("velocity") velocity.appendChild(song.createTextNode("0.8")) note.appendChild(velocity) pan_L = song.createElement("pan_L") pan_L.appendChild(song.createTextNode("1")) note.appendChild(pan_L) pan_R = song.createElement("pan_R") pan_R.appendChild(song.createTextNode("1")) note.appendChild(pan_R) pitch = song.createElement("pitch") pitch.appendChild(song.createTextNode("0")) note.appendChild(pitch) length = song.createElement("length") length.appendChild(song.createTextNode("-1")) note.appendChild(length) instrument = song.createElement("instrument") instrument.appendChild(song.createTextNode(str(instrument_value))) note.appendChild(instrument) noteList.appendChild(note) if debug: print "Debug..." return song else: song.writexml(fileobject) if __name__ == "__main__": class Instrument(object): def __init__(self, sequence_number): self.sequence_number = sequence_number class PatternOrganism(object): pass pattern = PatternOrganism() pattern.genes = Numeric.array([[1, 0, 1, 0], [0, 1, 0, 1]]) pattern.length = Numeric.shape(pattern.genes)[1] pattern.instruments = [Instrument(1), Instrument(5)] pattern.instrument_length = len(pattern.instruments) fhandle = open("test.h2song", "w") savePatternToXml(pattern, fhandle) #savePatternToXml(pattern, None, True)
Python
""" fitness.py Fitness Functions Each of these functions calculates the actual fitness of a genetic individual based on the individual's dimensions and the expected fitness based on a joining function and its linear parameters, "a" and "b". """ from random import randint from math import floor, ceil from collections import deque def temporal_beat_density(individual, ft): """ @param PatternOrganism individual @param FitnessTrajectory ft """ dim_row = individual.instrument_length dim_col = individual.length fitness = 0.0 row_range = xrange(dim_row) for column_index in xrange(dim_col): actual_total = 0 for row_index in row_range: # Calculate actual values if(individual.genes[row_index][column_index].value > 0): actual_total += 1 #Calculate expected values expected_total = ft.values[column_index][1] fitness += (expected_total - actual_total)**2 #print "Expected: %i, Actual: %i" % (expected_total, actual_total) return fitness def instrument_beat_density(individual, ft): """ Calculate beat density over the length of a pattern for each instrument. @param PatternOrganism individual @param FitnessTrajectory ft """ dim_col = individual.length fitness = 0.0 column_range = xrange(dim_col) for value in ft.values: row_index = value[0] expected_value = value[1] actual_value = 0 for column_index in column_range: # Calculate actual values if(individual.genes[row_index][column_index].value > 0): actual_value += 1 # Calculate fitness as square of the difference between expected and # actual values. fitness += (expected_value - actual_value)**2 return fitness def unison(individual, ft): """ Determine the degree to which the requested number of instruments are not playing in unison. @param PatternOrganism individual @param FitnessTrajectory ft """ dim_col = individual.length fitness = 0.0 actual_value = 0 value_count = len(ft.values) # If there is only one instrument, it is already in unison with itself. if value_count == 1: return 0 rows_a = xrange(value_count - 1) rows_b = xrange(1, value_count) for i in rows_a: row_a = ft.values[i] for j in rows_b: row_b = ft.values[j] for column_index in xrange(dim_col): # If value in instrument i is not the same as value in master_row, # decrease fitness by increasing total if individual.genes[row_a][column_index] != individual.genes[row_b][column_index]: actual_value += 1 # Calculate fitness as square of the difference between expected and # actual values. expected_value = 0 fitness += (expected_value - actual_value)**2 return fitness def double_rhythms(individual, ft): """ Determine the degree to which the requested number of instruments are not playing in double rhythm. @param PatternOrganism individual @param FitnessTrajectory ft """ dim_row = individual.instrument_length dim_col = individual.length fitness = 0.0 unified_instruments = [int(i) for i in ft.rows.split(",")] master_row = ft.master_row if not master_row in unified_instruments: unified_instruments.append(master_row) # Calculate distances between beats for each instrument row. distances = {} column_range = xrange(dim_col) for instrument_row in unified_instruments: distances[instrument_row] = [] count = 0 for column_index in column_range: beat = individual.genes[instrument_row][column_index].toscalar() if beat: distances[instrument_row].append(count) count = 0 continue count += 1 if len(distances[instrument_row]) > 0: distances[instrument_row][0] += count # Remove the master row from the list if it is listed try: index = unified_instruments.index(master_row) unified_instruments.pop(index) except ValueError: pass # Compare each instrument row's beat spacings to the master row's actual_value = 0 master_distance = deque(distances[master_row]) for instrument_row in unified_instruments: distance = deque(distances[instrument_row]) match = False for j in xrange(len(distance)): if j > 0: distance.rotate(1) if distance == master_distance: match = True break if match: """ print "Match!" print "---" print individual print distances """ continue else: fitness += 2 return fitness if __name__ == "__main__": import os os.environ['DJANGO_SETTINGS_MODULE'] = "fitbeat_project.settings" import doctest doctest.testmod()
Python
""" Crossover classes implementing various Crossover algorithms """ from random import random, randint import sys class Crossover(object): """ Abstract base Crossover object contains standard methods """ def mate(self, parent1, parent2): """ @param Organism parent1 @param Organism parent2 """ raise Exception("mate method is not implemented.") class OnePointCrossover(Crossover): """The simplest crossover.""" def mate(self, parent1, parent2): x = len(parent1) crossPoint = randint(1, x - 1) child1, child2 = parent1.copy(), parent2.copy() temp = parent1[crossPoint:] child1[crossPoint:] = parent2[crossPoint:] child2[crossPoint:] = temp return (child1, child2) class TwoPointCrossover(Crossover): """ Based on the algorithm presented by Holland (1975) and Goldberg (1989b) """ def mate(self, parent1, parent2): pass class PartExchangeCrossover(Crossover): def mate(self, parent1, parent2): # TODO: Rewrite for array data structure child1 = self.copy() child2 = partner.copy() # Select a random instrument to exchange instrument = randint(0, self.instrument_length - 1) # Calculate the range of genes represented by the chosen instrument row range_start = instrument * self.length range_end = (instrument + 1) * self.length for i in range(range_start, range_end): # Copy genes from partner sources child1.genes[str(i)], child2.genes[str(i)] = child2.genes[str(i)], child1.genes[str(i)] return (child1, child2) class GroupPartExchangeCrossover(Crossover): def mate(self, parent1, parent2): # TODO: Rewrite for array data structure child1 = self.copy() child2 = partner.copy() # Select a random number of instrument to exchange #totalExchange = randint(1, self.instrument_length) totalExchange = randint(1, self.instrument_length / 2) instrument_length = range(self.instrument_length) exchangeinstrument_length = [] for i in range(totalExchange): index = randint(0, len(instrument_length) - 1) exchangeinstrument_length.append(instrument_length.pop(index)) for instrument in exchangeinstrument_length: # Calculate the range of genes represented by the chosen instrument row range_start = instrument * self.length range_end = (instrument + 1) * self.length for i in range(range_start, range_end): # Copy genes from partner sources child1.genes[str(i)], child2.genes[str(i)] = child2.genes[str(i)], child1.genes[str(i)] return (child1, child2)
Python
#!/usr/bin/env python """ pisa_beats.py Evolves a pattern of beats based on a collection of user-defined fitness trajectories. The genetic algorithm is based on the pygene library. @author John Huddleston """ import os import sys import pickle os.environ['DJANGO_SETTINGS_MODULE'] = "fitbeat_project.settings" from random import choice, random from optparse import OptionParser from pattern import PatternGene, MultiObjectivePatternOrganism, MultiObjectiveDictPopulation from fitbeat_project.fitbeats.models import * from selector import RouletteSelector, TournamentSelector, NewRouletteSelector from crossover import OnePointCrossover def main(pattern_id=None): if pattern_id: return_best = True else: return_best = False usage = "usage: %prog [-p] [[options] pattern_id]" parser = OptionParser(usage) parser.add_option("-f", "--prefix", dest="pisa_prefix", type="string", default="PISA_", help="the prefix to use for all PISA configuration files.") parser.add_option("-t", "--poll", dest="pisa_period", type="float", default=1.0, help="the amount of time the variator should wait between\ polling the PISA state file.") parser.add_option("-s", "--stats", dest="statfile", type="string", default="stats.txt", help="a filename for the statistical output") parser.add_option("-o", "--output", dest="songfile", type="string", default=None, help="a filename for the song output") parser.add_option("-d", dest="database_dump", action="store_true", default=False, help="dump best pattern to database") parser.add_option("-l", dest="limit_mutation", action="store_true", default=False, help="limit mutation based on fitness value and mutator impact") parser.add_option("-q", dest="quiet", action="store_true", default=False, help="suppress debug output") parser.add_option("-p", dest="list_patterns", action="store_true", default=False, help="list available patterns and their ids") (options, args) = parser.parse_args() if options.list_patterns: patterns = Pattern.objects.all() print "Id | Dimensions | Name" print "----------------------" for p in patterns: try: print "%i | (%i x %i) | %s | %s" % (p.id, p.length, p.instrument_length, p, p.fitnesstrajectory_set.all()) except: pass sys.exit() elif pattern_id is None and len(args) != 1: parser.error("""You must supply a pattern id as an argument or use the -p flag to list the available patterns.""") else: try: pattern_id = pattern_id or int(args[0]) except ValueError: parser.error("You must supply an integer value for the pattern id.") try: pattern = Pattern.objects.get(pk=pattern_id) except Pattern.DoesNotExist: print "Error: could not load pattern %s" % pattern_id sys.exit(1) selector = eval(pattern.selector.get_short_name()) crossover = eval(pattern.crossover.get_short_name()) mutators = ["%sMutator" % m.name for m in pattern.mutators.all()] trajectory_set = pattern.fitnesstrajectory_set.all() for trajectory in trajectory_set: trajectory.calculate_trajectory() parameters = dict([(parameter.name, parameter.value) for parameter in pattern.parameters.all()]) # Prepare gene PatternGene.mutProb = parameters['gene_mutation_probability'] # Prepare organism MultiObjectivePatternOrganism.mutProb = parameters['organism_mutation_probability'] MultiObjectivePatternOrganism.crossoverRate = parameters['organism_crossover_rate'] MultiObjectivePatternOrganism.instrument_length = pattern.instrument_length MultiObjectivePatternOrganism.instruments = pattern.instruments.all() MultiObjectivePatternOrganism.length = pattern.length MultiObjectivePatternOrganism.crossover = crossover() MultiObjectivePatternOrganism.mutators = mutators MultiObjectivePatternOrganism.limit_mutation = options.limit_mutation MultiObjectivePatternOrganism.trajectory_set = trajectory_set MultiObjectivePatternOrganism.gene = PatternGene # Prepare population dimensions = len(trajectory_set) childCount = int(parameters['population_new_children']) selector=selector() initial_population_size = int(parameters['population_initial_size']) ph = MultiObjectiveDictPopulation(options.pisa_prefix, options.pisa_period, dimensions, childCount, selector, init=initial_population_size, species=MultiObjectivePatternOrganism) max_generations = int(parameters['population_max_generations']) if not options.quiet: print "Pattern Length: %i" % pattern.length print "Instruments:" for i in pattern.instruments.all(): print "\t%s" % i print "Generations: %i" % max_generations print "Selector: %s" % pattern.selector.name print "Crossover: %s" % pattern.crossover.name print "Mutators:\n\t%s" % "\n\t".join(mutators) print "Fitness Trajectories:" for t in trajectory_set: print "\t%s" % t print "Parameters:" for key, value in parameters.iteritems(): print "\t%s: %s" % (key, value) stats = {} webstats = None lastBest = None lastBestCount = 0 i = 0 stopfile = "/home/huddlej/fitbeats/stopfile.txt" for i in xrange(max_generations): # Check for file-based exit command. if options.database_dump: try: fhandle = open(stopfile, "r") stop = pickle.load(fhandle) if stop: break except: pass try: b = ph.best() if not options.quiet: print "generation %i:\n%s best=%s)" % (i, repr(b), b.fitness()) stats[i] = {'generation': i, 'bestfitness': b.fitness(), 'best_pattern': b, 'is_done': False} webstats = stats[i] # Store for web, TODO: make this better fhandle = open(options.statfile, "w") pickle.dump(webstats, fhandle) fhandle.close() if b.fitness() <= 0: break # Start the next generation. ph.gen() except KeyboardInterrupt: break if options.database_dump: p = PatternInstance(pattern=pattern, fitness=b.fitness(), value=b.xmlDumps()) p.save() if webstats: webstats['is_done'] = True fhandle = open(options.statfile, "w") pickle.dump(webstats, fhandle) fhandle.close() if not options.quiet: for p in ph.sample: print ph[p] # Store new statistics data #fileHandle = open(options.statfile, 'w') #pickle.dump(stats, fileHandle) #fileHandle.close() if options.songfile: testxml = open(options.songfile, "w") b.xmlDump(testxml) testxml.close() if not options.quiet: print "Wrote %s" % options.songfile else: if not options.quiet: print "No file written." if __name__ == '__main__': main()
Python
""" pygene is a library for genetic algorithms in python It aims to be very simple to use, and suitable for people new to genetic algorithms. """ version = "0.2.1" __all__ = [ 'gene', 'gamete', 'organism', 'population', 'xmlio', 'prog', ]
Python
""" mutator.py Base Mutator class for all mutation operators and extensions of this base class for the following organism-level mutations: * Classic - randomly mutate each bit in an individual with a given probability * Reverse - reverse the order of the beats in each instrument or in one random instrument * RotateRight - rotate to the right by a random or specified amount * Invert - silence to noise, noise to silence * TimbreExchange - randomly swap two instrument parts """ from random import choice, randint from collections import deque import operator class Mutator(object): """ Base Mutator class All mutation operators will extend this class """ """ @var string @private """ mutationImpact = None def __init__(self, organism=None, **kw): """ @param organism organism the organism to be mutated which may or may not be a copy; mutators do not need to worry about that. """ self.organism = organism self.args = kw def __str__(self): """ Override this method @return string the string representation of the mutator's parameters """ raise Exception("The __str__ method must be overridden") def mutate(self): """ Override this method @return organism organism the organism to be mutated """ raise Exception("The mutate method must be overridden") class ClassicMutator(Mutator): """ Perform simple, classic mutation on a randomly selected gene or on each gene individually. """ mutationImpact = "SMALL" def __repr__(self): return "ClassicMutator" def __str__(self): """ @return string the string representation of the mutator's parameters """ s = "impact: %s" % (self.mutationImpact) return s def mutate(self): if self.organism.mutateOneOnly: # Unconditionally mutate just one gene. # Choose random row and column. rowIndex = randint(0, self.organism.instrument_length - 1) columnIndex = randint(0, self.organism.length - 1) gene = self.organism.genes[rowIndex][columnIndex].toscalar() gene.mutate() else: # Conditionally mutate all genes. for row in self.organism.genes: for gene in row: gene.maybeMutate() return self.organism class InvertMutator(Mutator): """ Invert the values of an organism's genes by swapping silence for noise and noise for silence. """ def __init__(self, organism, **kw): """ @param organism organism @param boolean singleMutation whether a single individual should be mutated instead of all individuals @param mixed minValue minimum value assignable to genes in the organism @param mixed maxValue maximum value assignable to genes in the organism """ self.organism = organism if kw.has_key('singleMutation'): self.singleMutation = kw['singleMutation'] else: self.singleMutation = False if kw.has_key('minValue'): self.minValue = kw['minValue'] else: self.minValue = 0 if kw.has_key('maxValue'): self.maxValue = kw['maxValue'] else: self.maxValue = 1 if self.singleMutation: self.mutationImpact = "MEDIUM" else: self.mutationImpact = "LARGE" def __repr__(self): return "InvertMutator" def __str__(self): """ @return string the string representation of the mutator's parameters """ s = "singleMutation: %s|minValue: %i|maxValue: %i|impact: %s" % ( self.singleMutation, self.minValue, self.maxValue, self.mutationImpact ) return s def mutate(self): # Set the range of genes to invert. if self.singleMutation: # Select a random instrument to invert. instruments = [randint(0, self.organism.instrument_length - 1)] else: # Use all instruments instruments = xrange(self.organism.instrument_length) for instrument in instruments: row = self.organism.genes[instrument].tolist() for gene in row: if gene.value > self.minValue: gene.value = self.minValue else: gene.value = self.maxValue self.organism.genes[instrument] = row return self.organism class ReverseMutator(Mutator): """ Reverse the order of beats in one or more instrument rows. """ def __init__(self, organism, **kw): """ @param PatternOrganism organism @param boolean singleMutation whether a single individual should be mutated instead of all individuals """ self.organism = organism if kw.has_key('singleMutation'): self.singleMutation = kw['singleMutation'] else: self.singleMutation = False if self.singleMutation: self.mutationImpact = "MEDIUM" else: self.mutationImpact = "LARGE" def __repr__(self): return "ReverseMutator" def __str__(self): """ @return string the string representation of the mutator's parameters """ s = "singleMutation: %s|impact: %s" % (self.singleMutation, self.mutationImpact) return s def mutate(self): if self.singleMutation: instruments = [randint(0, self.organism.instrument_length - 1)] else: instruments = xrange(self.organism.instrument_length) for instrument in instruments: row = self.organism.genes[instrument].tolist() row.reverse() self.organism.genes[instrument] = row return self.organism class RotateMutator(Mutator): """ Rotate one or more instrument rows to the right by a specified or random amount. """ def __init__(self, organism=None, **kw): """ @param organism organism the organism to be mutate which may or may not be a copy. Mutators do not need to worry about @param int rotateAmount the amount by which the individual should be rotated @param boolean singleMutation whether a single row should be mutated instead of all rows """ self.organism = organism if kw.has_key('singleMutation'): self.singleMutation = kw['singleMutation'] else: self.singleMutation = False if kw.has_key('rotateAmount') and kw['rotateAmount'] > 0: self.rotateAmount = -1 * (kw['rotateAmount'] % organism.length) else: self.rotateAmount = -1 * randint(1, organism.length - 1) """ Determine how much impact is made based on the percentage of the individual being rotated and whether all instruments are being rotated or not. 1. If all rows being rotated and rotation is more than a third of the individual it's a large impact. 2. If all rows are being rotated and rotation is less than a third but more than one value, it's a medium impact. 3. If all rows are being rotated by one value, it's a small impact. 4. If one row is being rotated more than a third, it's a medium impact. 5. If one row is being rotated less than a third, it's a small impact. """ rotFraction = float(self.rotateAmount) / organism.length if (not self.singleMutation and rotFraction > 0.33): self.mutationImpact = "LARGE" elif ((not self.singleMutation and rotFraction <= 0.33 and self.rotateAmount > 1) or (self.singleMutation and rotFraction > 0.33)): self.mutationImpact = "MEDIUM" else: self.mutationImpact = "SMALL" def __repr__(self): return "RotateMutator" def __str__(self): """ @return string the string representation of the mutator's parameters """ s = "singleMutation: %s|rotate amount: %i|impact: %s" % ( self.singleMutation, self.rotateAmount, self.mutationImpact ) return s def mutate(self): if self.singleMutation: instruments = [randint(0, self.organism.instrument_length - 1)] else: instruments = xrange(self.organism.instrument_length) for instrument in instruments: row = self.organism.genes[instrument] row = row[self.rotateAmount:] + row[:self.rotateAmount] self.organism.genes[instrument] = row return self.organism class TimbreExchangeMutator(Mutator): """ Exchange instrument parts between two randomly selected instruments. """ mutationImpact = "SMALL" def __repr__(self): return "TimbreExchangeMutator" def __str__(self): """ @return string the string representation of the mutator's parameters """ s = "impact: %s" % self.mutationImpact return s def mutate(self): """ Select two instrument rows to exchange parts between. """ # Select random instrument 1 to exchange instrument1 = instrument2 = randint(0, self.organism.instrument_length - 1) # Select random instrument 2 to exchange while instrument1 == instrument2: instrument2 = randint(0, self.organism.instrument_length - 1) # Exchange instrument rows row1 = self.organism.genes[instrument1].tolist() row2 = self.organism.genes[instrument2].tolist() self.organism.genes[instrument1] = row2 self.organism.genes[instrument2] = row1 return self.organism
Python
import re from pygments.lexer import RegexLexer from pygments.token import Text, Name, Comment, String, Generic from sphinx import addnodes from docutils import nodes class FitykLexer(RegexLexer): name = 'fityklexer' tokens = { 'root': [ (r"'[^']*'", String.Single), (r'[#].*?$', Comment), (r'^=-> ', Generic.Prompt), (r"[^'#\n]+", Text), ], } comment_re = re.compile(r'(\(\*.*?\*\))') def doctree_read(app, doctree): env = app.builder.env for node in doctree.traverse(addnodes.productionlist): for production in node: if not isinstance(production, addnodes.production): continue if not isinstance(production[-1], nodes.Text): continue parts = comment_re.split(production.pop().astext()) new_nodes = [] for s in parts: if comment_re.match(s): new_nodes.append(nodes.emphasis(s, s)) elif s: new_nodes.append(nodes.Text(s)) production += new_nodes def setup(app): app.add_lexer('fityk', FitykLexer()); app.connect('doctree-read', doctree_read)
Python
# -*- coding: utf-8 -*- # Sphinx v1.0.7 # # sphinx-build -d ./doctrees/ -b html . html import sys, os sys.path.append(os.path.abspath('.')) extensions = ["sphinx.ext.pngmath", "sphinx.ext.extlinks", "fityk_ext"] exclude_trees = ['html', 'latex', '.svn'] exclude_patterns = ['index.rst', 'screens.rst'] templates_path = ['.'] source_suffix = '.rst' source_encoding = 'utf-8' master_doc = 'fityk-manual' project = 'Fityk' copyright = '2001-2011, Fityk Developers' version = '1.1.1' release = version default_role = None #highlight_language = "none" highlight_language = "fityk" pygments_style = "trac" html_theme = "sphinxdoc" html_sidebars = {'index': [], 'screens': [], '**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html']} html_title = 'Fityk %s manual' % version html_short_title = 'Manual' html_favicon = 'fityk.ico' html_static_path = ['fityk-banner.png', 'fityk.css'] html_style = 'fityk.css' html_last_updated_fmt = '%Y-%m-%d' html_use_smartypants = True html_use_modindex = False html_use_index = False html_add_permalinks = False #html_compact_lists = True html_show_copyright = False latex_documents = [ ('fityk-manual', 'fityk-manual.tex', 'Fityk manual', '', 'manual', True), ] latex_logo = 'fityk-banner.pdf' latex_elements = { 'papersize': 'a4paper', # 'letterpaper' 'pointsize': '10pt,oneside,openany', #'classoptions': ',oneside,openany', 'inputenc': r""" \usepackage{ucs} \usepackage[utf8x]{inputenc}""", 'utf8extra': '', # put notes into boxes 'preamble': r""" \usepackage{ifthen} \definecolor{gray03}{gray}{0.3} \let\origbeginnotice\notice \let\origendnotice\endnotice \renewenvironment{notice}[2]{% \def\noticetype{#1} \def\inTheGui{\equal{#2}{In the GUI}} \ifthenelse{\equal{#1}{note}}{% \setlength{\fboxrule}{1pt} \setlength{\fboxsep}{6pt} \setlength{\mylen}{\linewidth} \addtolength{\mylen}{-2\fboxsep} \addtolength{\mylen}{-4\fboxrule} %\setlength{\shadowsize}{3pt} \Sbox \minipage{\mylen} \ifthenelse{\inTheGui}{\color{gray03}}{} \par\strong{#2} }{% \origbeginnotice{#1}{#2}% } }{% \ifthenelse{\equal{\noticetype}{note}}{% \endminipage \endSbox \ifthenelse{\inTheGui}{\ovalbox{\TheSbox}}{\fbox{\TheSbox}} }{% \origendnotice% } } """ } latex_show_pagerefs = True latex_show_urls = True # determine vertical alignment of the math PNGs pngmath_use_preview = True dl_dir = 'http://fityk.nieto.pl/subscribers/' dl_prefix = 'fityk-%s' % version extlinks = { 'wiki': ('https://github.com/wojdyr/fityk/wiki/%s', ''), 'download': (dl_dir + dl_prefix + '%s', dl_prefix), }
Python
#!/usr/bin/env python import os.path, sys from fityk import Fityk class GaussianFitter(Fityk): def __init__(self, filename): Fityk.__init__(self) if not os.path.isfile(filename): raise ValueError("File `%s' not found." % filename) self.filename = filename self.execute("@0 < '%s'" % filename) print "Data info:", self.get_info("data", 0) def run(self): self.execute("guess %g = Gaussian") print "Fitting %s ..." % self.filename self.execute("fit") print "WSSR=", self.get_wssr() print "Gaussian center: %.5g" % self.calculate_expr("%g.center") def save_session(self, filename): self.execute("info state >'%s'" % filename) f = Fityk() print f.get_info("version", True) print "ln(2) =", f.calculate_expr("ln(2)") del f g = GaussianFitter("nacl01.dat") g.run() g.save_session("tmp_save.fit") # output from commands can be handled by callback function in Python def show_msg(s): print "output:", s g.py_set_show_message(show_msg) # or it can be redirected to file g.redir_messages(sys.stderr)
Python
#!/usr/bin/env python import os.path, sys from fityk import Fityk class GaussianFitter(Fityk): def __init__(self, filename): Fityk.__init__(self) if not os.path.isfile(filename): raise ValueError("File `%s' not found." % filename) self.filename = filename self.execute("@0 < '%s'" % filename) print "Data info:", self.get_info("data", 0) def run(self): self.execute("guess %g = Gaussian") print "Fitting %s ..." % self.filename self.execute("fit") print "WSSR=", self.get_wssr() print "Gaussian center: %.5g" % self.calculate_expr("%g.center") def save_session(self, filename): self.execute("info state >'%s'" % filename) f = Fityk() print f.get_info("version", True) print "ln(2) =", f.calculate_expr("ln(2)") del f g = GaussianFitter("nacl01.dat") g.run() g.save_session("tmp_save.fit") # output from commands can be handled by callback function in Python def show_msg(s): print "output:", s g.py_set_show_message(show_msg) # or it can be redirected to file g.redir_messages(sys.stderr)
Python
#!/bin/env python # -*- coding: utf-8 -*- import pygtk pygtk.require('2.0') import gtk from random import choice import os class LongText(object): def __init__(self, content=u'', generation=4, max_length=1000): assert(generation>1) assert(generation<=len(content)) # convert content to unicode if necessary if type(content) != type(u''): try: content = unicode(content,'utf-8') except: content = unicode(content,'latin-1','replace') if content[-1] == u'\n': sep = u'' else: sep = u'\n' self.content = content + sep + content[:generation] self.generation=generation self.max_length=max_length def generate(self): # start with the first letters of a random paragraph result = choice( [x for x in self.content.split('\n') if len(x) > self.generation] )[:self.generation-1] current = result while len(result) < self.max_length: bits = [x[0] for x in self.content.split(current) if x!= '' ][1:] newchar = choice(bits) current = current[1:] + newchar result += newchar # try to finish with a meaningful sentence ending newlen = max(result.rfind('.'), result.rfind('!'), result.rfind('?')) if newlen > self.max_length * 0.8: result = result[:newlen+1] return result class FiWaGe(object): def __init__(self): self.statusicon = gtk.StatusIcon() self.statusicon.set_from_stock(gtk.STOCK_ABOUT) self.statusicon.set_visible(True) self.statusicon.set_tooltip("FiWaGe") mainmenu = gtk.Menu() fiwagedir = 'textfiles/' for fname in os.listdir(fiwagedir): mainmenuitem = gtk.MenuItem('%s' % fname.replace('_','-')) submenu = gtk.Menu() for maxlen in (20,50,100,500,1000,10000): submenuitem = gtk.MenuItem('%i characters' % maxlen) submenuitem.max_length= maxlen submenuitem.originaltext = file(fiwagedir + fname).read() submenuitem.generation = 4 submenuitem.connect('activate', self.generate, self.statusicon) submenu.append(submenuitem) mainmenuitem.set_submenu(submenu) mainmenu.append(mainmenuitem) mainmenu.append(gtk.SeparatorMenuItem()) quitmenuitem = gtk.ImageMenuItem(gtk.STOCK_QUIT) quitmenuitem.connect('activate', self.do_quit, self.statusicon) mainmenu.append(quitmenuitem) self.statusicon.connect('popup-menu', self.do_menu, mainmenu) self.statusicon.set_visible(1) gtk.main() def generate(self, widget, event, data=None): txt = LongText(widget.originaltext, generation=widget.generation, max_length=widget.max_length).generate() clipboard = gtk.clipboard_get() # ctrl-c/v clipboard clipboard.set_text(txt) clipboard.store() os.popen('xsel', 'wb').write(txt) # middleclick clipboard # window = gtk.Window(gtk.WINDOW_TOPLEVEL) # window.set_border_width(10) # # button = gtk.Button("Hello World") # button.connect_object("clicked", gtk.Widget.destroy, window) # # window.add(button) # button.show() # window.show() def do_quit(self, widget, data = None): gtk.main_quit() def do_menu(self, widget, button, time, data=None): if button == 3: if data: data.show_all() data.popup(None, None, gtk.status_icon_position_menu, 3, time, self.statusicon) if __name__ == "__main__": FiWaGe()
Python
#!/bin/env python # -*- coding: utf-8 -*- import pygtk pygtk.require('2.0') import gtk from random import choice import os class LongText(object): def __init__(self, content=u'', generation=4, max_length=1000): assert(generation>1) assert(generation<=len(content)) # convert content to unicode if necessary if type(content) != type(u''): try: content = unicode(content,'utf-8') except: content = unicode(content,'latin-1','replace') if content[-1] == u'\n': sep = u'' else: sep = u'\n' self.content = content + sep + content[:generation] self.generation=generation self.max_length=max_length def generate(self): # start with the first letters of a random paragraph result = choice( [x for x in self.content.split('\n') if len(x) > self.generation] )[:self.generation-1] current = result while len(result) < self.max_length: bits = [x[0] for x in self.content.split(current) if x!= '' ][1:] newchar = choice(bits) current = current[1:] + newchar result += newchar # try to finish with a meaningful sentence ending newlen = max(result.rfind('.'), result.rfind('!'), result.rfind('?')) if newlen > self.max_length * 0.8: result = result[:newlen+1] return result class FiWaGe(object): def __init__(self): self.statusicon = gtk.StatusIcon() self.statusicon.set_from_stock(gtk.STOCK_ABOUT) self.statusicon.set_visible(True) self.statusicon.set_tooltip("FiWaGe") mainmenu = gtk.Menu() fiwagedir = 'textfiles/' for fname in os.listdir(fiwagedir): mainmenuitem = gtk.MenuItem('%s' % fname.replace('_','-')) submenu = gtk.Menu() for maxlen in (20,50,100,500,1000,10000): submenuitem = gtk.MenuItem('%i characters' % maxlen) submenuitem.max_length= maxlen submenuitem.originaltext = file(fiwagedir + fname).read() submenuitem.generation = 4 submenuitem.connect('activate', self.generate, self.statusicon) submenu.append(submenuitem) mainmenuitem.set_submenu(submenu) mainmenu.append(mainmenuitem) mainmenu.append(gtk.SeparatorMenuItem()) quitmenuitem = gtk.ImageMenuItem(gtk.STOCK_QUIT) quitmenuitem.connect('activate', self.do_quit, self.statusicon) mainmenu.append(quitmenuitem) self.statusicon.connect('popup-menu', self.do_menu, mainmenu) self.statusicon.set_visible(1) gtk.main() def generate(self, widget, event, data=None): txt = LongText(widget.originaltext, generation=widget.generation, max_length=widget.max_length).generate() clipboard = gtk.clipboard_get() # ctrl-c/v clipboard clipboard.set_text(txt) clipboard.store() os.popen('xsel', 'wb').write(txt) # middleclick clipboard # window = gtk.Window(gtk.WINDOW_TOPLEVEL) # window.set_border_width(10) # # button = gtk.Button("Hello World") # button.connect_object("clicked", gtk.Widget.destroy, window) # # window.add(button) # button.show() # window.show() def do_quit(self, widget, data = None): gtk.main_quit() def do_menu(self, widget, button, time, data=None): if button == 3: if data: data.show_all() data.popup(None, None, gtk.status_icon_position_menu, 3, time, self.statusicon) if __name__ == "__main__": FiWaGe()
Python
import mimetypes import urllib import string import settings import jinja2 import os import webapp2 from datetime import datetime from google.appengine.api import users from google.appengine.ext import db key_prefix = 'file_' log_prefix = 'log_' prefs_prefix = 'prefs_' segment_size = 10**6 column_names = ['name', 'mime', 'size', 'gets', 'when'] jinja_env = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + '/templates/')) def is_auth(): try: return users.User().email() in settings.auth_emails except users.UserNotFoundError: return None def print_default(self): values = { 'site_name': settings.site_name, 'login_url': users.create_login_url('/'), 'logout_url': users.create_logout_url('/'), 'logged_in': is_auth() is not None, 'user': users.get_current_user(), } template = jinja_env.get_template('default.html') self.response.out.write(template.render(values)) def print_404(self): self.error(404) values = { 'error_text': '404 File Not Found', } template = jinja_env.get_template('error.html') self.response.out.write(template.render(values)) def put_log(text, fore = 'black', back = 'transparent'): log = LogEntry(key_name = log_prefix + users.User().email()) log.text = text log.fore = fore log.back = back log.put() def get_log(): log = LogEntry.get_by_key_name(log_prefix + users.User().email()) if log is not None: log.delete() return log def get_prefs(): return Preferences.get_or_insert(prefs_prefix + users.User().email()) def time_since(dt, default='0 seconds ago'): diff = datetime.now() - dt periods = ( (diff.days / 365, 'year', 'years'), (diff.days / 30, 'month', 'months'), (diff.days / 7, 'week', 'weeks'), (diff.days, 'day', 'days'), (diff.seconds / 3600, 'hour', 'hours'), (diff.seconds / 60, 'minute', 'minutes'), (diff.seconds, 'second', 'seconds'), ) for period, singular, plural in periods: if period: return '%d %s ago' % (period, period == 1 and singular or plural) return default def intcomma(val): return '{:,d}'.format(val) jinja_env.filters['intcomma'] = intcomma class FileSegment(db.Model): data = db.BlobProperty() next = db.SelfReferenceProperty() class File(db.Model): name = db.StringProperty() data = db.BlobProperty() seg1 = db.ReferenceProperty(FileSegment) mime = db.StringProperty() when = db.DateTimeProperty(auto_now_add=True) gets = db.IntegerProperty() size = db.IntegerProperty() def since(self): return time_since(self.when) class LogEntry(db.Model): text = db.StringProperty() fore = db.StringProperty() back = db.StringProperty() class Preferences(db.Model): sort = db.StringProperty(default='-when') class MainPage(webapp2.RequestHandler): def get(self): if not is_auth(): print_default(self) return prefs = get_prefs() sort = self.request.get('sort') if sort != '': try: col = column_names[int(sort)] if prefs.sort == col: prefs.sort = '-' + col else: prefs.sort = col prefs.put() except (ValueError, IndexError): pass self.redirect('/') return headers = [] sort_col = column_names.index(prefs.sort.split('-')[-1]) sort_dir = prefs.sort.startswith('-') and ' &#x25bc;' or ' &#x25b2;' for c, col in enumerate(('Name', 'Type', 'Size', 'Downloads', 'Uploaded')): headers.append('%s%s' % (col, c == sort_col and sort_dir or '')) files = File.all().order(prefs.sort) values = { 'site_name': settings.site_name, 'email': users.get_current_user().email(), 'logout_url': users.create_logout_url('/'), 'log': get_log(), 'headers': headers, 'files': files, 'num_cols': len(column_names), } template = jinja_env.get_template('filelist.html') self.response.out.write(template.render(values)) class UploadFile(webapp2.RequestHandler): def post(self): if not is_auth(): self.redirect('/') return try: filename = self.request.params['upload'].filename exists = File.get_by_key_name(key_prefix + filename) if exists is not None: put_log('Upload failed: a file with that name already exists', 'red') self.redirect('/') return file = File(key_name = key_prefix + filename) data = self.request.get('upload') index = 0 datalen = len(data) while (datalen - index) > 0: seg = FileSegment() seg.data = db.Blob(data[index:index + segment_size]) seg.next = None seg.put() if file.seg1 is None: file.seg1 = seg tail = seg else: tail.next = seg tail.put() tail = seg index += segment_size file.name = filename # file.data = db.Blob(self.request.get('upload')) file.mime = mimetypes.guess_type(file.name, False)[0] or 'application/octet-stream' file.gets = 0 file.size = datalen file.put() put_log('Uploaded ' + file.name, 'green') except Exception: put_log('Upload failed!', 'red') self.redirect('/') def get(self): self.redirect('/') class GetFile(webapp2.RequestHandler): def get(self): file = File.get_by_key_name(key_prefix + unicode(urllib.unquote(self.request.path[1:]), 'utf-8')) if file is None: print_404(self) return file.gets += 1 file.put() self.response.headers['Content-Type'] = str(file.mime) if file.data is not None: self.response.out.write(file.data) else: seg = file.seg1 while seg is not None: self.response.out.write(seg.data) seg = seg.next class DeleteFile(webapp2.RequestHandler): def get(self): if not is_auth(): self.redirect('/') return file = File.get_by_key_name(key_prefix + unicode(urllib.unquote(self.request.path[8:]), 'utf-8')) if file is None: put_log('Delete failed: no such file', 'red') else: seg = file.seg1 while seg is not None: seg.delete() seg = seg.next file.delete() put_log('Deleted ' + file.name, 'green') self.redirect('/') class RenameFile(webapp2.RequestHandler): def get(self): if not is_auth(): self.redirect('/') return split = string.split(unicode(urllib.unquote(self.request.path), 'utf-8'), '/') if len(split) != 4: put_log('Rename failed: invalid arguments', 'red') self.redirect('/') return file = File.get_by_key_name(key_prefix + split[2]) if file is None: put_log('Rename failed: no such file', 'red') self.redirect('/') return newname = string.strip(split[3]) if not newname: put_log('Rename failed: invalid name', 'red') self.redirect('/') return exists = File.get_by_key_name(key_prefix + newname) if exists is not None: put_log('Rename failed: a file with that name already exists', 'red') self.redirect('/') return newfile = File(key_name = key_prefix + newname) newfile.name = newname newfile.data = file.data newfile.seg1 = file.seg1 newfile.mime = file.mime newfile.when = file.when newfile.gets = file.gets newfile.size = file.size file.delete() newfile.put() put_log('Renamed %s to %s' % (file.name, newfile.name), 'green') self.redirect('/') application = webapp2.WSGIApplication( [('/', MainPage), ('/upload/', UploadFile), ('/delete/.*', DeleteFile), ('/rename/.*', RenameFile), ('/.*', GetFile)], debug=True)
Python
# site name (used for display purposes) site_name = 'example.com' # email addresses authorized to upload, rename and delete files auth_emails = ( 'test@example.com', )
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/usr/bin/python # # Run the script with path to the JSON file you downloaded from google.drive. # eg. checkin.py ~/Downloads/GmailDelaySendWeb.json # # Script will unpack JSON and edit/updates files in git for you. # # REMEMBER: You still need to commit & push import json import os import sys from subprocess import call def Usage(msg=None): if msg: print msg print 'Usage: %s <path_to_json_file>' % os.path.basename(sys.argv[0]) sys.exit(1) if len(sys.argv) < 2: Usage('Must supply path to JSON file.') json_path = sys.argv[1] if not os.path.isfile(json_path): Usage('Expected to find file at: %s' % json_path) with open(json_path) as f: json_objects = json.loads(f.read()) print 'Found %d files in JSON' % len(json_objects['files']) files = json_objects['files'] for f_dict in files: file_name = f_dict['name'] file_contents = f_dict['source'] print '-- Processing %s --' % file_name with open(os.path.join('src',file_name), 'w') as f: f.write(file_contents.encode('utf-8')) print ' Finished' call(['git','add','.']) print '-- REMEMBER YOU STILL NEED TO COMMIT AND PUSH CHANGES --'
Python
"""Graph.py Description: Simple, undirected and connected graph implementation for course 75.29 Teoria de Algoritmos at University of Buenos Aires. Provide simple graph operations, calculates the minimum spanning tree using Kruskal algorithm and work with Union and Set dataStructures defined on DisjointSet code, which represent a Union by rank and uses path compression. Authors: Garay, Ignacio Liguori, Ariel Musumeci, Pablo """ import re import heapq from DisjointSets import * class Edges: def __init__(self, vertex1, vertex2, weight): self.vertex1 = vertex1 self.vertex2 = vertex2 self.weight = weight def __str__(self): s= "%s -> %s : %s" % (self.vertex1, self.vertex2, self.weight) return s class Vertex: def __init__(self, value): self.value = value def __str__(self): return self.value class Graph: def __str__(self): #Imprime el contenido de los vertices y las aristas s = "Vertex -> Edges\n" for k, v in self.graph.iteritems(): s+= "%s -> %s\n" % (k, v) return s def __init__(self): self.graph = {} def __init__(self, filePointer): #Construye el graph a partir de parsear el archivo self.graph = {} for line in filePointer: lines = line.replace(' ','').split(':') # Guardo el vertice actual verticeActual = lines[0] if (not self.isVertex(Vertex(verticeActual))): self.addVertex(Vertex(verticeActual)) num = "" verticeVecino = "" cadena = lines[1] # Proceso la linea for i in range(len(cadena)): char = cadena[i] if (char == ')'): # Agrego arista entre VActual y V que estoy procesando x = int(num) #print "Agrego arista %s , %s , %s" % (verticeActual, verticeVecino, x) self.addEdge( Edges(Vertex(verticeActual), Vertex(verticeVecino), x) ) #print "("+verticeActual +","+ verticeVecino+"," +num+")" elif (char == '('): num = "" elif (char == ','): verticeVecino = num if (not self.isVertex(Vertex(verticeVecino))): self.addVertex(Vertex(verticeVecino)) num = "" else: num += char def addVertex(self, vertice): #Agrega un vertice al graph self.graph[vertice.value] = {} def delVertex(self, vertice): #Si el vertice esta en el graph, lo remueve try: self.graph.pop(vertice) return True except KeyError: #El vertice no estan en el graph return False def isVertex(self, vertice): #Retorna true si el vertice esta en el geafo try: self.graph[vertice.value] return True except KeyError: return False def addEdge(self, edge): #Agrega una arista si los vertices existen try: self.graph[edge.vertex1.value][edge.vertex2.value] = edge.weight self.graph[edge.vertex2.value][edge.vertex1.value] = edge.weight #print "V1: ",self.graph[edge.vertex1.value] #print "V2: ",self.graph[edge.vertex2.value] return True except KeyError: print "Error trying to add edge: Vertexs doesn't belong to graph" #Los vertices no estan en el graph return False def delEdge(self, vertice1, vertice2): #Remueve la arista del graph try: self.graph[vertice][vertice2].pop() return True except KeyError: #Los vertices no estan en el graph print "Error: Vertexs doesn't belong to graph" return False def getEdge(self, vertice1, vertice2): try: return self.graph[vertice1][vertice2] except KeyError: #Los vertices no estan en el grafo print "Error: Vertexs doesn't belong to graph" return False # Kruskal Definition # - create a forest F (a set of trees), where each vertex in the graph is a separate tree # - create a set S containing all the edges in the graph # - while S is nonempty and F is not yet spanning # remove an edge with minimum weight from S # if that edge connects two different trees, then add it to the forest, combining the trees, # otherwise discard that edge. # - At the termination of the algorithm, the forest has only one component (ST). # Complexity order: O (E log E) + O(V) + O(E) # - Since G is connected |E| >= |V| --> O( E log E) + O(E) + O(E) --> O(E log E) # - |E| <= |V|^2 -> log |E| = O(2 log V) = O(log V) # - Finally the worst case analysis is: O ( E log V) def kruskal(self): edges = [] # E=Edges; V=Vertex # O(|E| log E) for u in self.getAllVertex(): #O(1) for v in self.getVecinos(u): #O(1) heapq.heappush(edges, (self.getEdge(u,v),Edges(u,v,self.getEdge(u,v))) ) #O(1) T = [] #this contains all the edges in the tree # O( |V| * MakeSet) = O(V) for vertex in self.getAllVertex(): MakeSet(vertex) #O(1) See dijoint set for verification. #O(E) while edges: min_edge = heapq.heappop(edges)[1] #O(E) if FindSet(min_edge.vertex1) is not FindSet(min_edge.vertex2): #O(2 log E) = O(log E) #perform a union and add this edge to the Tree T.append(min_edge) #O(1) Union(min_edge.vertex1, min_edge.vertex2) #O(log E) return T def getAllVertex(self): # Devuelve una lista con todos los vertices return self.graph.keys() def getAllEdges(self): edges = [] for u in self.getAllVertex(): for v in self.getVecinos(u): heapq.heappush(edges, Edges(u,v,self.getEdge(u,v))) return edges def getVecinos(self, vertex): try: return self.graph[vertex] except KeyError: print "Error: Vertex doesn't belong to graph" return False
Python
from Graph import Graph def main(): graphFile = raw_input("Enter the file name containing a valid graph:") filep = open(graphFile) graph = Graph(filep) print "Evaluating the graph:\n" print graph T = graph.kruskal() print "Min. Spanning tree: \n" for edges in T: print edges return 0 if __name__ == '__main__': main()
Python