text
stringlengths
0
1.05M
meta
dict
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a Animal class Dog(Animal): def __init__(self, name): ## Dog has-a name self.name = name ## Cat is-a Aniaml class Cat(Animal): def __init__(self, name): ## Cat has-a name self.name = name ## Person is-a object class Person(object): def __init__(self, name): ## Person has-a name self.name = name ## Person has-a pet of some kind self.pet = None ## Employee is-a Person class Employee(Person): def __init__(self, name, salary): ## Employee has a name like a Person. `super` means to look at the #super class (in this case, the super class is Person) and we are using #the __init__ method to assign the name. super(Employee, self).__init__(name) ## Employee has-a salary self.salary = salary ## Fish is-a object class Fish(object): pass ## Salmon is-a Fish class Salmon(Fish): pass ## Halibut is-a Fish class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## satan is-a Cat satan = Cat("Satan") ## mary is-a Person mary = Person("Mary") ## mary has-a pet (satan) mary.pet = satan ## frank is-a Employee and frank has-a salary of 120000 frank = Employee("Frank", 120000) ## frank has-a pet (rover). Frank is Employee, therefore, Frank is Person. frank.pet = rover ## flipper is-a Fish flipper = Fish() ## crouse is-a Salmon crouse = Salmon() ## harry is-a Halibut harry = Halibut()
{ "repo_name": "Paul-Haley/LPTHW_python3", "path": "ex42.py", "copies": "1", "size": "1568", "license": "mit", "hash": 6522094526725255000, "line_mean": 18.8481012658, "line_max": 79, "alpha_frac": 0.6173469388, "autogenerated": false, "ratio": 2.9696969696969697, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.408704390849697, "avg_score": null, "num_lines": null }
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a Animal. class Dog(Animal): def __init__(self, name): ## Dog has-a name. self.name = name ## Cat is-a Animal. class Cat(Animal): def __init__(self, name): ## Cat has-a name. self.name = name ## Person is-a Object. class Person(object): def __init__(self, name): ## Person has-a name. self.name = name ## Person has-a pet of some kind. self.pet = None ## Employee is-a Person. class Employee(Person): def __init__(self, name, salary): ## Employee calls the base constructor. ## Employee has-a name. super(Employee, self).__init__(name) ## Employee has-a salary. self.salary = salary ## Fish is-a Object. class Fish(object): pass ## Salmon is-a Fish. class Salmon(Fish): pass ## Halibut is-a Fish. class Halibut(Fish): pass ## Rover is-a Dog rover = Dog("Rover") ## Satan is-a Cat. satan = Cat("Satan") ## Mary is-a Person. mary = Person("Mary") ## Mary has-a Cat (`satan`). mary.pet = satan ## Frank is-a Employee. frank = Employee("Frank", 120000) ## Frank has-a Dog (`rover`). frank.pet = rover ## Fish is-a Object. flipper = Fish() ## Salmon is-a Fish. crouse = Salmon() ## Halibut is-a Fish. harry = Halibut()
{ "repo_name": "afronski/playground-other", "path": "python/books/learn-python-the-hard-way/ex42.py", "copies": "1", "size": "1381", "license": "mit", "hash": 2392046382255056400, "line_mean": 16.9350649351, "line_max": 71, "alpha_frac": 0.5923244026, "autogenerated": false, "ratio": 2.8357289527720737, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39280533553720737, "avg_score": null, "num_lines": null }
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a Animal class Dog(Animal): def __init__(self, name): ## Dog has-a name self.name = name ## Cat is-a Animal class Cat(Animal): def __init__(self, name): ## Cat has-a name self.name = name print(f"The name of the cat is: {self.name}") ## Person is-a object class Person(object): def __init__(self, name): ## Person has-a name self.name = name ## Person has-a pet of some kind self.pet = None ## Employee is-a Person class Employee(Person): def __init__(self, name, salary): ##?? hmmm what is this? super(Employee,self).__init__(name) ##Employee has-a salary self.salary = salary ## Fish is-a object class Fish(object): pass ## Salmon is-a Fish class Salmon(Fish): pass ## Halibut is-a Fish class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## statan is-a Cat satan = Cat("Satan") ## Mary is-a person mary = Person("Mary") ## Mary has-a pet will name it satan mary.pet = satan ## Employee that has-a name Frank and has-a salary of 12000 frank = Employee("Frank", 12000) ## Will name Frank's pet to rover frank.pet = rover ## Set flipper to instance of Fish flipper = Fish() ## Set crouse to instance of Salmon crouse = Salmon() ## Set harry to instance of Halibut harry = Halibut()
{ "repo_name": "hbenaouich/Learning-Python", "path": "Learning-Python3-The-Hard-Way/42-Is-A, Objects, and Classes/ex42.py", "copies": "1", "size": "1460", "license": "apache-2.0", "hash": 2765258478336412700, "line_mean": 18.2236842105, "line_max": 71, "alpha_frac": 0.6178082192, "autogenerated": false, "ratio": 2.9494949494949494, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8979357035116485, "avg_score": 0.01758922671569285, "num_lines": 76 }
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a animal class Dog(Animal): def __init__(self, name): ## __init__ has-a reference with Dog's name self.name = name ## Cat is-a animal class Cat(Animal): def __init__(self, name): ## __init__ has-a reference with Cat's name self.name = name ## Person is-a object class Person(object): def __init__(self, name): ## __init__ has-a reference with Person's name self.name = name ## Person has-a pet of some kind self.pet = None ## Employee is-a Person class Employee(Person): def __init__(self, name, salary): ## __init__ has-a reference with Employee's name and salary super(Employee, self).__init__(name) ## ?? self.salary = salary ## Fish is-a object class Fish(object): pass ## Salmon is-a Fish class Salmon(Fish): pass ## Halibut is-a Fish class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## Satan is-a Cat satan = Cat("Satan") ## Mary is-a Person mary = Person("Mary") ## Mary has-a pet cat named Satan mary.pet = satan ## Frank is-a employee that has-a salary of $120000 frank = Employee("Frank", 120000) ## Frank has-a pet dog named Rover frank.pet = rover ## Flipper is-a Fish flipper = Fish() ## Crouse is-a Salmon crouse = Salmon() ## Harry is-a Halibut harry = Halibut()
{ "repo_name": "chrisortman/CIS-121", "path": "k0765065/lpthw/ex42.py", "copies": "1", "size": "1453", "license": "mit", "hash": 929865869857550200, "line_mean": 18.1184210526, "line_max": 71, "alpha_frac": 0.6139022712, "autogenerated": false, "ratio": 2.9294354838709675, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8961895847792446, "avg_score": 0.01628838145570421, "num_lines": 76 }
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a(n) Animal class Dog(Animal): def __init__(self, name): ## Dog has-a name self.name = name ## Cat is-a(n) Animal class Cat(Animal): def __init__(self, name): ## Cat has-a name self.name = name ## Person is-a object class Person(object): def __init__(self, name): ## Person has-a name self.name = name ## Person has-a pet self.pet = None ## Employee is-a Person class Employee(Person): def __init__(self, name, salary): ## super(Employee, self).__init__(name) ## Employee has-a salary self.salary = salary ## Fish is-a object class Fish(object): pass ## Salmon is-a Fish class Salmon(Fish): pass ## Halibut is-a Fish class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## satan is-a Cat satan = Cat("Satan") ## mary is-a Person mary = Person("Mary") ## mary has-a pet which is satan mary.pet = satan ## frank is-a Employee frank = Employee("Frank", 120000) ## frank has-a pet which is rover frank.pet = rover ## flipper is-a Fish flipper = Fish() ## crouse is-a Fish crouse = Salmon() ## harry is-a Halibut harry = Halibut()
{ "repo_name": "Furzoom/learnpython", "path": "learnpythonthehardway/ex42.py", "copies": "1", "size": "1285", "license": "mit", "hash": -4780861400302553000, "line_mean": 19.7258064516, "line_max": 71, "alpha_frac": 0.6062256809, "autogenerated": false, "ratio": 2.8303964757709252, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39366221566709253, "avg_score": null, "num_lines": null }
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dos is-a Animal class Dog(Animal): def __init__(self, name): self.name = name ## Cat is-a Animal class Cat(Animal): def __init__(self, name): self.name = name ## Person is-a object class Person(object): def __init__(self, name): self.name = name self.pet = None ## Employee is-a Person class Employee(Person): def __init__(self, name, salary): super(Employee, self).__init__(name) self.salary = salary ## Fish is-a object class Fish(object): pass ## Salmon is-a Fish class Salmon(Fish): pass ## Halibut is a fish class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## satan is-a Cat satan = Cat("Satan") ## mary is-a Person mary = Person("Mary") ## Frank is-a Employee frank = Employee("Frank", 120000) ## frank has-a pet called rover frank.pet = rover ## flipper is-a Fish flipper = Fish() ## crouse is-a Salmon crouse = Salmon() ## harry is-a Halibut harry = Halibut()
{ "repo_name": "CodeSheng/LPLHW", "path": "ex42.py", "copies": "1", "size": "1081", "license": "apache-2.0", "hash": 5419582200617410000, "line_mean": 16.7213114754, "line_max": 71, "alpha_frac": 0.625346901, "autogenerated": false, "ratio": 2.764705882352941, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8798587022509765, "avg_score": 0.01829315216863515, "num_lines": 61 }
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## is-a class Dog(Animal): def __init__(self, name): ## has-a self.name = name ## is-a class Cat(Animal): def __init__(self, name): ## has-a self.name = name ## is-a class Person(object): def __init__(self, name): ## has-a self.name = name ## Person has-a pet of some kind self.pet = None ## is-a class Employee(Person): def __init__(self, name, salary): ## has-a super(Employee, self).__init__(name) ## has-a self.salary = salary ## is-a class Fish(object): pass ## is-a class Salmon(Fish): pass ## is-a class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## satan is-a Cat satan = Cat("Satan") ## mary is-a Person mary = Person("Mary") ## mary has-a pet satan mary.pet = satan ## frank is-a Employee frank = Employee("Frank", 120000) ## frank has-a pet rover frank.pet = rover ## flipper is-a Fish flipper = Fish() ## crouse is-a Salmon crouse = Salmon() ## harry is-a Halibut harry = Halibut()
{ "repo_name": "amolborcar/learnpythonthehardway", "path": "ex42.py", "copies": "1", "size": "1158", "license": "mit", "hash": 4202523109551547000, "line_mean": 14.25, "line_max": 71, "alpha_frac": 0.5751295337, "autogenerated": false, "ratio": 2.7505938242280283, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3825723357928028, "avg_score": null, "num_lines": null }
## Animal is-a object (yes,sort of confusing) look at the extra credit class Animal(object): pass ## ?? class Dog(Animal): def __init__(self,name): ##?? self.name = name ## ?? class Cat(Animal): def __init__(self,name): ## ?? self.name = name ## ?? class Person(object): def __init__(self,name): ## ?? self.name = name ## Person has-a pet of some kind self.pet = None ## ?? class Employee(Person): def __init__(self,name,salary): ## ?? hmm waht is the strange magic ? super(Employee,self).__init__(name) ## ?? self.salary = salary ## ?? class Fish(object): pass ## ?? class Salmon(Fish): pass ## ?? class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## ?? satan = Cat("Satan") ## ?? mary = Person("Mary") ## ?? mary.pet = satan ## ?? frank = Employee("Frank",120000) ## ?? frank.pet = rover ## ?? flipper = Fish() ## ?? crouse = Salmon() ## ?? harry = Halibut()
{ "repo_name": "AisakaTiger/Learn-Python-The-Hard-Way", "path": "ex42.py", "copies": "1", "size": "1038", "license": "mit", "hash": -3256692257039010000, "line_mean": 12.84, "line_max": 70, "alpha_frac": 0.5125240848, "autogenerated": false, "ratio": 2.7828418230563003, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8518081480736757, "avg_score": 0.05545688542390882, "num_lines": 75 }
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## ?? class Dog(Animal): def __init__(self, name): ## ?? self.name = name ## ?? class Cat(Animal): def __init__(self, name): ## ?? self.name = name ## ?? class Person(object): def __init__(self, name): ## ?? self.name = name ## Person has-a pet of some kind self.pet = None ## ?? class Employee(Person): def __init__(self, name, salary): ## ?? hmm what is this strange magic? super(Employee, self).__init__(name) ## ?? self.salary = salary ## ?? class Fish(object): pass ## ?? class Salmon(Fish): pass ## ?? class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## ?? satan = Cat("Satan") ## ?? mary = Person("Mary") ## ?? mary.pet = satan ## ?? frank = Employee("Frank", 120000) ## ?? frank.pet = rover ## ?? flipper = Fish() ## ?? crouse = Salmon() ## ?? harry = Halibut()
{ "repo_name": "zedshaw/learn-python3-thw-code", "path": "ex42.py", "copies": "1", "size": "1037", "license": "mit", "hash": 4254801259559874600, "line_mean": 12.2948717949, "line_max": 71, "alpha_frac": 0.5139826422, "autogenerated": false, "ratio": 2.772727272727273, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.37867099149272726, "avg_score": null, "num_lines": null }
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object) pass ## ?? class Dog(Animal): def __init__(self, name): ## ?? self.name = name ## ?? class Cat(Animal): def __init__(self, name): ## ?? self.name = name ## ?? class Person(object): def __init__(self, name): ## ?? self.name = name ## Person has-a pet of some kind self.pet = None ## ?? class Employee(Person): def __init__(self, name, salary): ## ?? hmm what is this strange magic? super(Employee, self).__init__(name) ## ?? self.salary = salary ## ?? class Fish(object): pass ## ?? class Salmon(Fish): pass ## ?? class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## ?? satan = Cat("Satan") ## ?? mary = Person("Mary") ## ?? mary.pet = satan ## ?? frank = Employee("Frank", 120000) ## ?? frank.pet = rover ## ?? flipper = Fish() ## ?? crouse = Salmon() ## ?? harry = Halibut()
{ "repo_name": "apoloxie/learning-python", "path": "42/ex42.py", "copies": "1", "size": "1034", "license": "mit", "hash": 2452911978684430300, "line_mean": 12.6052631579, "line_max": 71, "alpha_frac": 0.5154738878, "autogenerated": false, "ratio": 2.764705882352941, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.37801797701529416, "avg_score": null, "num_lines": null }
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## ?? class Dog(Animal): def __init__(self, name): ## ?? self.name = name ## ?? class Cat(Animal): def __init__(self, name): ## ?? self.name = name ## ?? class Person(object): def __init__(self, name): ## ?? self.name = name ## Person has-a pet pf some kind self.pet = None ## ?? class Employee(Person): def __init__(self, name, salary): ## ?? hmm what is this strange magic? super(Employee, self).__init__(name) ## ?? self.salary = salary ## ?? class Fish(object): pass ## ?? class Salmon(Fish): pass ## ?? class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## ?? satan = Cat("Satan") ## ?? mary = Person("Mary") ## ?? mary.pet = satan ## ?? frank = Employee("Frank", 120000) ## ?? frank.pet = rover ## ?? flipper = Fish() ## ?? crouse = Salmon() ## ?? harry = Halibut()
{ "repo_name": "enkaynitin/python-learn", "path": "ex42.py", "copies": "1", "size": "1035", "license": "cc0-1.0", "hash": -4161249300555916300, "line_mean": 12.6184210526, "line_max": 71, "alpha_frac": 0.5149758454, "autogenerated": false, "ratio": 2.767379679144385, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3782355524544385, "avg_score": null, "num_lines": null }
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a Animal class Dog(Animal): def __init__(self, name): ## Dog has-a name self.name = name ## Cat is-a Animal class Cat(Animal): def __init__(self, name): ## Cat has-a name self.name = name ## Person is-a object class Person(object): def __init__(self, name): ## Person has-a name self.name = name ## Person has-a pet of some kind self.pet = None ## Employee is-a Person class Employee(Person): def __init__(self, name, salary): ## Employee has-a name, hmm what is this strange magic? super(Employee, self).__init__(name) ## Employee has-a salary self.salary = salary ## Fish is-a object class Fish(object): pass ## Salmon is-a Fish class Salmon(Fish): pass ## Halibut is-a Fish class Halibut(Fish): pass ## rover is-a Dog with the name Rover rover = Dog("Rover") ## satan is-a Cat with the name Satan satan = Cat("Satan") ## mary is-a Person with the name Mary mary = Person("Mary") ## mary has-a pet satan mary.pet = satan ## frank is-a Employee with the name Frank and a salary of 120000 frank = Employee("Frank", 120000) ## frank has-a pet rover frank.pet = rover ## flipper is-a Fish flipper = Fish() ## crouse is-a Salmon crouse = Salmon() ## harry is-a Halibut harry = Halibut()
{ "repo_name": "CodeCatz/litterbox", "path": "Pija/LearnPythontheHardWay/ex42.py", "copies": "1", "size": "1347", "license": "mit", "hash": 316950003191939400, "line_mean": 16.7368421053, "line_max": 71, "alpha_frac": 0.6659242762, "autogenerated": false, "ratio": 2.615533980582524, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8607024609663502, "avg_score": 0.03488672942380441, "num_lines": 76 }
#animal OOP assignment ### animal parent class class Animal(object): def __init__(self, name): self.name = name self.health = 100 def walk(self, x=1): self.health -= 1*x return self def run(self, y=1): self.health -= 5*y return self def displayHealth(self): print self.name print self.health return self animal = Animal('Thunder') print animal.walk(3).run(2).displayHealth() ### dog child class class Dog(Animal): def __init__(self, name): super(Dog, self).__init__(name) self.health = 150 def pet(self, x=1): self.health += 5*x return self fido = Dog('Fido') print fido.walk(3).run(2).pet(1).displayHealth() ### dragon child class class Dragon(Animal): def __init__(self, name): super(Dragon, self).__init__(name) self.health = 170 def fly(self, x=1): self.health -= 10*x return self def displayHealth(self): print 'This is a dragon!' super(Dragon, self).displayHealth() drazo = Dragon('Drazo') print drazo.walk(3).run(2).fly(2).displayHealth()
{ "repo_name": "authman/Python201609", "path": "Nguyen_Ken/Assignments/Python OOP/animal.py", "copies": "1", "size": "1145", "license": "mit", "hash": 311394836570735400, "line_mean": 21.0192307692, "line_max": 49, "alpha_frac": 0.5799126638, "autogenerated": false, "ratio": 3.2436260623229463, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.927123834263273, "avg_score": 0.010460076698043238, "num_lines": 52 }
# animal.py - create animal table and # retrieve information from it import sys from rdbhdb import rdbhdb as db from rdbhdb import extensions DictCursor = extensions.DictCursor # connect to the RdbHost server authcode = 'KF7IUQPlwfSth4sBvjdqqanHkojAZzEjMshrkfEV0O53yz6w6v' try: conn = db.connect ('s000015', authcode=authcode) except db.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) # create the animal table and populate it try: cursor = conn.cursor () cursor.execute ("DROP TABLE IF EXISTS animal") cursor.execute (""" CREATE TABLE animal ( name CHAR(40), category CHAR(40) ) """) cursor.execute (""" INSERT INTO animal (name, category) VALUES ('snake', 'reptile'), ('frog', 'amphibian'), ('tuna', 'fish'), ('racoon', 'mammal') """) print "Number of rows inserted: %d" % cursor.rowcount # perform a fetch loop using fetchone() cursor.execute ("SELECT name, category FROM animal") while (1): row = cursor.fetchone () if row == None: break print "%s, %s" % (row[0], row[1]) print "Number of rows returned: %d" % cursor.rowcount # perform a fetch loop using fetchall() cursor.execute ("SELECT name, category FROM animal") rows = cursor.fetchall () for row in rows: print "%s, %s" % (row[0], row[1]) print "Number of rows returned: %d" % cursor.rowcount # issue a statement that changes the name by including data values # literally in the statement string, then change the name back # by using placeholders cursor.execute (""" UPDATE animal SET name = 'turtle' WHERE name = 'snake' """) print "Number of rows updated: %d" % cursor.rowcount print "Reptile category example changed to turtle from snake" # perform a fetch loop using fetchall() cursor.execute ("SELECT name, category FROM animal") rows = cursor.fetchall () for row in rows: print "%s, %s" % (row[0], row[1]) cursor.execute (""" UPDATE animal SET name = %s WHERE name = %s """, ("snake", "turtle")) print "Number of rows updated: %d" % cursor.rowcount print "Reptile category example changed back to snake" # create a dictionary cursor so that column values # can be accessed by name rather than by position cursor.close () cursor = conn.cursor (curDef=DictCursor) cursor.execute ("SELECT name, category FROM animal") result_set = cursor.fetchall () for row in result_set: print "%s, %s" % (row["name"], row["category"]) print "Number of rows returned: %d" % cursor.rowcount cursor.close () except db.Error, e: print "Error %s: %s" % (e.args[0], e.args[1]) sys.exit (1) conn.commit () conn.close ()
{ "repo_name": "rdbhost/Rdbhdb", "path": "examples/animal.py", "copies": "1", "size": "2875", "license": "mit", "hash": 3213750046008830000, "line_mean": 28.3469387755, "line_max": 66, "alpha_frac": 0.6153043478, "autogenerated": false, "ratio": 3.6027568922305764, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47180612400305766, "avg_score": null, "num_lines": null }
animals = {'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} animals['d'] = ['donkey'] animals['d'].append('dog') animals['d'].append('dingo') {'a': ['aardvark'], 'c': ['coati'], 'b': ['baboon'], 'd': ['donkey', 'dog', 'dingo']} def howMany(animals): """ returns the number of values in a dictionary which holds lists of values """ # len(animals) = 4 # len(animals['d']) = 3 count = 0 for key, val in animals.items(): for k in val: count += 1 return count # another way to solve this for value in animals.values(): result += len(value) # and another one for key in animals.keys(): result += len(animals[key]) animals = {'a': ['aardvark'], 'c': ['coati'], 'b': ['baboon'], 'd': ['donkey', 'dog', 'dingo']} def biggest(animals): """ Returns the maximum value of a key in a dictionary """ return max(animals, key=animals.get) # Correct answer result = None biggestValue = 0 for key in animals.keys(): if len(animals[key]) >= biggestValue: result = key biggestValue = len(animals[key]) return result
{ "repo_name": "teichopsia-/python_practice", "path": "old_class_material/dictionary_practice.py", "copies": "1", "size": "1182", "license": "mpl-2.0", "hash": -4734342584628461000, "line_mean": 24.6956521739, "line_max": 95, "alpha_frac": 0.5406091371, "autogenerated": false, "ratio": 3.2295081967213113, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4270117333821311, "avg_score": null, "num_lines": null }
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} animals['d'] = ['donkey'] animals['d'].append('dog') animals['d'].append('dingo') print howMany(animals) # 6 def howMany(aDict): ''' aDict: A dictionary, where all the values are lists. returns: int, how many values are in the dictionary. ''' count = 0 for a in aDict: for b in aDict[a]: count += 1 return count ### Other was of solving the problem ### def howMany(aDict): ''' aDict: A dictionary, where all the values are lists. returns: int, how many individual values are in the dictionary. ''' result = 0 for value in aDict.values(): # Since all the values of aDict are lists, aDict.values() will # be a list of lists result += len(value) return result def howMany2(aDict): ''' Another way to solve the problem. aDict: A dictionary, where all the values are lists. returns: int, how many individual values are in the dictionary. ''' result = 0 for key in aDict.keys(): result += len(aDict[key]) return result
{ "repo_name": "teichopsia-/python_practice", "path": "week_3/dic_count.py", "copies": "1", "size": "1139", "license": "mpl-2.0", "hash": -6106985654295398000, "line_mean": 21.78, "line_max": 71, "alpha_frac": 0.5961369622, "autogenerated": false, "ratio": 3.5817610062893084, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9522745650448271, "avg_score": 0.03103046360820751, "num_lines": 50 }
animals = [ {'name': 'Fluffykins', 'species': 'rabbit'}, {'name': 'Caro', 'species': 'dog'}, {'name': 'Hamilton', 'species': 'dog'}, {'name': 'Harold', 'species': 'fish'}, {'name': 'Ursula', 'species': 'cat'}, {'name': 'Jimmy', 'species': 'fish'} ] # Get dogs from list with dictionaries def return_dogs(animals): dogs = [] for animal in animals: if animal['species'] == 'dog': dogs.append(animal) return dogs # Short way to get dogs # Get only species equal to dog def is_dog(animal): return animal['species'] == 'dog' # Filter the list with 'is_dog' and return them def filter_and_return(animals): return filter(is_dog, animals) # Get names from list with dictionaries def animal_names(animals): names = [] for animal in animals: names.append(animal['name']) return names # Short way to get names # Get only names from dictionaries def get_animal_name(animal): return animal['name'] def return_animal_name(animals): return map(get_animal_name, animals) do = filter_and_return(animals) print do to = return_animal_name(animals) print to #dogs = return_dogs(animals) #print dogs #names = animal_names(animals) #print names """ def animal_name(animals): return map(lambda animal: animal['name'], animals) do = animal_name(animals) print do Notes: Tova koeto pravq e da otdelq chast ot kolekciqta v nova -> filtiram tova e edin pohvat ot fukncionalnoto programirane, fuknciata 'filter' NA EDNO def get_dog_species(animals): dogs = filter(lamda a : a['species'] == 'dog', animals) return map(lambda d : d['species'], dogs) """
{ "repo_name": "Valka7a/python-playground", "path": "projects/training/working_with_collections.py", "copies": "1", "size": "1678", "license": "mit", "hash": -4557726215841528300, "line_mean": 20.2405063291, "line_max": 67, "alpha_frac": 0.6418355185, "autogenerated": false, "ratio": 2.9335664335664338, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40754019520664336, "avg_score": null, "num_lines": null }
# animal speed weight lifespan brain # (mph) (kg) (years) mass (g) animals = [("dog", 46, 35, 13, 280 ), ("elephant", 30, 3500, 50, 6250 ), ("frog", 5, 0.5, 8, 3 ), ("hippopotamus", 45, 1600, 45, 573 ), ("horse", 40, 385, 30, 642 ), ("human", 27, 80, 78, 2000 ), ("lion", 50, 250, 30, 454 ), ("mouse", 8, 0.025, 2, 0.625), ("rabbit", 25, 4, 12, 40 ), ("shark", 26, 230, 20, 92 ), ("sparrow", 16, 0.024, 7, 2 )] def importance_rank(items, weights): names = [item[0] for item in items] # get the list of animal names scores = [sum([a*b for (a,b) in zip(item[1:], weights)]) for item in items] # get the list of overall scores for each animal results = zip(scores,names) # make a list of tuple res2 = sorted(results) # sort the tuple based on the score return res2 answer = importance_rank(animals, (552,3,7,1)) for i in range(len(answer)): print(i, answer[i][1], "(", answer[i][0], ")")
{ "repo_name": "dazz22/udacity-coursework", "path": "Algorithms_intro_to/l9_quiz2.py", "copies": "1", "size": "1245", "license": "apache-2.0", "hash": -6339986590129668000, "line_mean": 48.8, "line_max": 129, "alpha_frac": 0.4369477912, "autogenerated": false, "ratio": 3.051470588235294, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39884183794352934, "avg_score": null, "num_lines": null }
animals=[] addloop=True loopno=0 while addloop==True: addname1=raw_input("Enter animal to add to list:") animals.append(addname1) print str("animal added") loopno=loopno+1 if loopno==5: addloop=False program=1 while program==1: print str(animals)+" This is the list of animals. There are "+ str(len(animals)) + " animals" menu=raw_input("Welcome to my menu. you can choose from 4 options. type in the number of your option. 1. add a new animal 2. find the position of the animal in the list 3. remove an animal from the list 4. exit") if menu=="1": addloop2=raw_input(str("There are currently ") + str(len(animals)) + " animals in the list. Add more? [Y/N]").lower() if addloop2=="y": addname2 = raw_input("Enter animal to add to list") animals.append(addname2) addloop3=raw_input(str("There are currently ") + str(len(animals)) + " animals in the list. Add more? [Y/N]").lower() print "returning to menu" program=0 program=1 elif menu=="2": location=raw_input("which animal would you like to locate? ") print location+" is at position "+str(animals.index(location)) elif menu == 4: blank=raw_input()
{ "repo_name": "husky-prophet/personal-backup", "path": "lists.py", "copies": "1", "size": "1307", "license": "mit", "hash": 8631617438289245000, "line_mean": 44.75, "line_max": 216, "alpha_frac": 0.6082631982, "autogenerated": false, "ratio": 3.513440860215054, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46217040584150537, "avg_score": null, "num_lines": null }
"""Animated brownian motion.""" import numpy as np from matplotlib.colors import hsv_to_rgb from galry import * class MyVisual(Visual): def initialize(self, X, color, T): n = X.shape[0] self.n = n self.size = n self.bounds = [0, n] self.primitive_type = 'LINE_STRIP' self.add_attribute('position', vartype='float', ndim=2, data=X) self.add_attribute('color', vartype='float', ndim=3, data=color) self.add_attribute('i', vartype='float', ndim=1, data=i) self.add_varying('vcolor', vartype='float', ndim=3) self.add_varying('vi', vartype='float', ndim=1) self.add_uniform('t', vartype='float', ndim=1, data=0.) self.add_vertex_main(""" vcolor = color; vi = i; """) self.add_fragment_main(""" out_color.rgb = vcolor; out_color.a = .1 * ceil(clamp(t - vi, 0, 1)); """) # number of steps n = 1e6 # duration of the animation T = 30. b = np.array(np.random.rand(n, 2) < .5, dtype=np.float32) b[b == True] = 1 b[b == False] = -1 X = np.cumsum(b, axis=0) # print X # exit() # generate colors by varying linearly the hue, and convert from HSV to RGB h = np.linspace(0., 1., n) hsv = np.ones((1, n, 3)) hsv[0,:,0] = h color = hsv_to_rgb(hsv)[0,...] i = np.linspace(0., T, n) m = X.min(axis=0) M = X.max(axis=0) center = (M + m)/2 X = 2 * (X - center) / (max(M) - min(m)) # current camera position x = np.array([0., 0.]) y = np.array([0., 0.]) # filtering parameter dt = .015 # zoom level dx = .25 def anim(fig, params): global x, y, dx t, = params i = int(n * t / T) + 15000 # follow the current position if i < n: y = X[i,:] # or unzoom at the end else: y *= (1 - dt) dx = np.clip(dx + dt * (1 - dx), 0, 1) if dx < .99: # filter the current position to avoid "camera shaking" x = x * (1 - dt) + dt * y viewbox = [x[0] - dx, x[1] - dx, x[0] + dx, x[1] + dx] # set the viewbox fig.process_interaction('SetViewbox', viewbox) fig.set_data(t=t) figure(constrain_ratio=True, toolbar=False) visual(MyVisual, X, color, T) animate(anim, dt=.01) show()
{ "repo_name": "rossant/galry", "path": "examples/brownian.py", "copies": "1", "size": "2263", "license": "bsd-3-clause", "hash": 4279430590562426000, "line_mean": 23.597826087, "line_max": 74, "alpha_frac": 0.5395492709, "autogenerated": false, "ratio": 2.82875, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8800063795815227, "avg_score": 0.013647095016954557, "num_lines": 92 }
# Animated Towers of Hanoi using Tk with optional bitmap file in # background. # # Usage: tkhanoi [n [bitmapfile]] # # n is the number of pieces to animate; default is 4, maximum 15. # # The bitmap file can be any X11 bitmap file (look in # /usr/include/X11/bitmaps for samples); it is displayed as the # background of the animation. Default is no bitmap. # This uses Steen Lumholt's Tk interface from Tkinter import * # Basic Towers-of-Hanoi algorithm: move n pieces from a to b, using c # as temporary. For each move, call report() def hanoi(n, a, b, c, report): if n <= 0: return hanoi(n-1, a, c, b, report) report(n, a, b) hanoi(n-1, c, b, a, report) # The graphical interface class Tkhanoi: # Create our objects def __init__(self, n, bitmap = None): self.n = n self.tk = tk = Tk() self.canvas = c = Canvas(tk) c.pack() width, height = tk.getint(c['width']), tk.getint(c['height']) # Add background bitmap if bitmap: self.bitmap = c.create_bitmap(width/2, height/2, bitmap=bitmap, foreground='blue') # Generate pegs pegwidth = 10 pegheight = height/2 pegdist = width/3 x1, y1 = (pegdist-pegwidth)/2, height*1/3 x2, y2 = x1+pegwidth, y1+pegheight self.pegs = [] p = c.create_rectangle(x1, y1, x2, y2, fill='black') self.pegs.append(p) x1, x2 = x1+pegdist, x2+pegdist p = c.create_rectangle(x1, y1, x2, y2, fill='black') self.pegs.append(p) x1, x2 = x1+pegdist, x2+pegdist p = c.create_rectangle(x1, y1, x2, y2, fill='black') self.pegs.append(p) self.tk.update() # Generate pieces pieceheight = pegheight/16 maxpiecewidth = pegdist*2/3 minpiecewidth = 2*pegwidth self.pegstate = [[], [], []] self.pieces = {} x1, y1 = (pegdist-maxpiecewidth)/2, y2-pieceheight-2 x2, y2 = x1+maxpiecewidth, y1+pieceheight dx = (maxpiecewidth-minpiecewidth) / (2*max(1, n-1)) for i in range(n, 0, -1): p = c.create_rectangle(x1, y1, x2, y2, fill='red') self.pieces[i] = p self.pegstate[0].append(i) x1, x2 = x1 + dx, x2-dx y1, y2 = y1 - pieceheight-2, y2-pieceheight-2 self.tk.update() self.tk.after(25) # Run -- never returns def run(self): while 1: hanoi(self.n, 0, 1, 2, self.report) hanoi(self.n, 1, 2, 0, self.report) hanoi(self.n, 2, 0, 1, self.report) hanoi(self.n, 0, 2, 1, self.report) hanoi(self.n, 2, 1, 0, self.report) hanoi(self.n, 1, 0, 2, self.report) # Reporting callback for the actual hanoi function def report(self, i, a, b): if self.pegstate[a][-1] != i: raise RuntimeError # Assertion del self.pegstate[a][-1] p = self.pieces[i] c = self.canvas # Lift the piece above peg a ax1, ay1, ax2, ay2 = c.bbox(self.pegs[a]) while 1: x1, y1, x2, y2 = c.bbox(p) if y2 < ay1: break c.move(p, 0, -1) self.tk.update() # Move it towards peg b bx1, by1, bx2, by2 = c.bbox(self.pegs[b]) newcenter = (bx1+bx2)/2 while 1: x1, y1, x2, y2 = c.bbox(p) center = (x1+x2)/2 if center == newcenter: break if center > newcenter: c.move(p, -1, 0) else: c.move(p, 1, 0) self.tk.update() # Move it down on top of the previous piece pieceheight = y2-y1 newbottom = by2 - pieceheight*len(self.pegstate[b]) - 2 while 1: x1, y1, x2, y2 = c.bbox(p) if y2 >= newbottom: break c.move(p, 0, 1) self.tk.update() # Update peg state self.pegstate[b].append(i) # Main program def main(): import sys, string # First argument is number of pegs, default 4 if sys.argv[1:]: n = string.atoi(sys.argv[1]) else: n = 4 # Second argument is bitmap file, default none if sys.argv[2:]: bitmap = sys.argv[2] # Reverse meaning of leading '@' compared to Tk if bitmap[0] == '@': bitmap = bitmap[1:] else: bitmap = '@' + bitmap else: bitmap = None # Create the graphical objects... h = Tkhanoi(n, bitmap) # ...and run! h.run() # Call main when run as script if __name__ == '__main__': main()
{ "repo_name": "TathagataChakraborti/resource-conflicts", "path": "PLANROB-2015/seq-sat-lama/Python-2.5.2/Demo/tkinter/guido/hanoi.py", "copies": "6", "size": "4637", "license": "mit", "hash": -8876093801075369000, "line_mean": 29.1103896104, "line_max": 69, "alpha_frac": 0.5309467328, "autogenerated": false, "ratio": 3.0872170439414113, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.661816377674141, "avg_score": null, "num_lines": null }
"""animate_event.py Usage: animate_event.py <f_anim_config> """ from sportvu.data.dataset import BaseDataset from sportvu.data.extractor import BaseExtractor, EncDecExtractor from sportvu.data.loader import BaseLoader, Seq2SeqLoader from sportvu.vis.Event import Event import cPickle as pkl import yaml import os from docopt import docopt arguments = docopt(__doc__) print ("...Docopt... ") print(arguments) print ("............\n") f_anim_config = arguments['<f_anim_config>'] anim_config = yaml.load(open(f_anim_config, 'rb')) futures = pkl.load(open(anim_config['tmp_pkl'], 'rb')) f_config = 'data/config/rev3-ed-target-history.yaml' dataset = BaseDataset(f_config, 0, load_raw=True) gameid = anim_config['gameid'] eventid = anim_config['event_id'] event = dataset.games[gameid]['events'][eventid] event_obj = Event(event, gameid) event_obj.show('/u/wangkua1/Pictures/vis/%s.mp4' % os.path.basename(f_anim_config).split('.')[0], futures) # [(idx, event_obj.player_ids_dict[p.id]) for (idx,p) in enumerate(event_obj.moments[0].players)]
{ "repo_name": "wangkua1/sportvu", "path": "sportvu/animate_event.py", "copies": "1", "size": "1067", "license": "mit", "hash": -5335725068570691000, "line_mean": 27.8378378378, "line_max": 97, "alpha_frac": 0.7075913777, "autogenerated": false, "ratio": 2.8605898123324396, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9055766224046045, "avg_score": 0.0024829931972789113, "num_lines": 37 }
'''Animates distances using single measurment mode''' from hokuyolx import HokuyoLX import matplotlib.pyplot as plt DMAX = 3000 IMIN = 300. IMAX = 2000. images = [] fig = None def get_colors(intens): max_val = intens.max() return np.repeat(intens, 3).reshape((4,3))/max_val def update(laser, plot, text): timestamp, scan = laser.get_filtered_intens(dmax=DMAX,imin= 2300) kscan = [] #for i in range(len(scan)): # if scan[i][1]>2000 and scan[i][0]<4000: # kscan.append(scan[i][1]) #scan = kscan plot.set_offsets(scan[:, :2]) plot.set_array(scan[:, 2]) text.set_text('t: %d' % timestamp) plt.show() plt.pause(0.001) def run(): plt.ion() laser = HokuyoLX(tsync=False) laser.convert_time=False ax = plt.subplot(111, projection='polar') plot = ax.scatter([0, 1], [0, 1], s=10, c='b', lw=0) text = plt.text(0, 1, '', transform=ax.transAxes) ax.set_rmax(DMAX) ax.grid(True) images.append((plot,)) plt.show() while plt.get_fignums(): update(laser, plot, text) laser.close() if __name__ == '__main__': run() #from matplotlib.animation import ArtistAnimation #line_anim = ArtistAnimation(fig, images, interval=50, blit=True) # line_anim.save('my_animation.mp4')
{ "repo_name": "SkRobo/Eurobot-2017", "path": "NewCommunication/animate.py", "copies": "1", "size": "1305", "license": "mit", "hash": -3418679648794265000, "line_mean": 25.1, "line_max": 69, "alpha_frac": 0.6084291188, "autogenerated": false, "ratio": 2.8369565217391304, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8892249617388508, "avg_score": 0.01062720463012454, "num_lines": 50 }
"""Animates the simulation to show quantities that change over time""" # coding=utf-8 import matplotlib.animation as anim import matplotlib.pyplot as plt import numpy as np from matplotlib import gridspec from .time_snapshots import FrequencyPlot, \ PhasePlot, SpatialDistributionPlot, IterationCounter, \ TripleFieldPlot, TripleCurrentPlot, CurrentPlot, FieldPlot, ChargeDistributionPlot, SpatialPerturbationDistributionPlot, \ PoyntingFieldPlot from ..helper_functions import helpers # formatter = matplotlib.ticker.ScalarFormatter(useMathText=True, useOffset=False) class Animation: def __init__(self, S, alpha=1, frames="few" ): """ Creates an animation from `Plot`s. Parameters ---------- S : Simulation Data source alpha : float Opacity value from 0 to 1, used in the phase plot. Returns ------- figure or matplotlib animation Plot object, depending on `frame_to_draw`. """ assert alpha <= 1, "alpha too large!" assert alpha >= 0, "alpha must be between 0 and 1!" self.S = S.postprocess() self.fig = plt.figure(figsize=(13, 10)) self.alpha = alpha self.fig.suptitle(str(self.S), fontsize=12) self.fig.subplots_adjust(top=0.81, bottom=0.08, left=0.15, right=0.95, wspace=.25, hspace=0.6) # REFACTOR: remove particle windows if there are no particles if frames == "all": self.frames = np.arange(0, S.NT, dtype=int) self.frames_to_draw = self.frames elif frames == "few": self.frames = np.arange(0, S.NT, helpers.calculate_particle_iter_step(S.NT), dtype=int) self.frames_to_draw = self.frames[::30] elif isinstance(frames, list): self.frames_to_draw = frames else: raise ValueError("Incorrect frame_to_draw - must be 'animation' or number of iteration to draw.") def add_plots(self, plots): self.plots = plots self.updatable = [] for plot in plots: for result in plot.return_animated(): self.updatable.append(result) def animate(self, i): """draws the i-th frame of the simulation""" for plot in self.plots: plot.update(i) return self.updatable def init(self): """initializes animation window for faster drawing""" for plot in self.plots: plot.animation_init() return self.updatable def full_animation(self, save=False, writer="ffmpeg"): """ Parameters ---------- save : bool Whether to save the simulation. This may take a long time. writer : Returns ------- """ print("Drawing full animation.") # noinspection PyTypeChecker animation_object = anim.FuncAnimation(self.fig, self.animate, interval=100, frames=self.frames, blit=True, init_func=self.init) if save: mpl_Writer = anim.writers[writer] mpl_writer = mpl_Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800) # TODO: does bitrate matter here helpers.make_sure_path_exists(self.S.filename) videofile_name = self.S.filename.replace(".hdf5", ".mp4") print(f"Saving animation to {videofile_name}") animation_object.save(videofile_name, writer=mpl_writer)#, extra_args=['-vcodec', 'libx264']) print(f"Saved animation to {videofile_name}") return animation_object def snapshot_animation(self): print("Drawing animation as snapshots.") for i in self.frames_to_draw: self.animate(i) helpers.make_sure_path_exists(self.S.filename) file_name = self.S.filename.replace(".hdf5", f"_{i:06}.png") print(f"Saving iteration {i} to {file_name}") self.fig.savefig(file_name, dpi=1200) self.fig.savefig(file_name.replace('.png', '.pdf'), dpi=1200) return self.fig class FullAnimation(Animation): def __init__(self, S, alpha=1, frames="few"): super().__init__(S, alpha=alpha, frames=frames) if any([species.individual_diagnostics for species in S.list_species]): gs = gridspec.GridSpec(4, 3, ) phase_axes = [plt.subplot(gs[0, i]) for i in range(3)] start_index = 1 phase_plot_x = PhasePlot(self.S, phase_axes[0], "x", "v_x", self.alpha) phase_plot_y = PhasePlot(self.S, phase_axes[1], "x", "v_y", self.alpha) phase_plot_z = PhasePlot(self.S, phase_axes[2], "x", "v_z", self.alpha) plots = [phase_plot_x, phase_plot_y, phase_plot_z] else: start_index = 0 gs = gridspec.GridSpec(3, 3) plots = [] current_axes = [plt.subplot(gs[0 + start_index, i]) for i in range(3)] field_axes = [plt.subplot(gs[1 + start_index, i]) for i in range(3)] bonus_row = [plt.subplot(gs[2 + start_index, i]) for i in range(3)] density_axis, density_perturbation_axis, charge_axes = bonus_row charge_plot = ChargeDistributionPlot(self.S, charge_axes) density_plot = SpatialDistributionPlot(self.S, density_axis) iteration = IterationCounter(self.S, charge_axes) current_plots = TripleCurrentPlot(self.S, current_axes) field_plots = TripleFieldPlot(self.S, field_axes) poynting_plot = PoyntingFieldPlot(S, density_perturbation_axis) plots += [ charge_plot, density_plot, iteration, current_plots, poynting_plot, field_plots] super().add_plots(plots) class FastAnimation(Animation): def __init__(self, S, alpha=1, frames="few"): super().__init__(S, alpha=alpha, frames=frames) density_axis = self.fig.add_subplot(421) current_axes = [self.fig.add_subplot(423 + 2 * i) for i in range(3)] field_axes = [self.fig.add_subplot(424 + 2 * i) for i in range(2)] charge_axis = self.fig.add_subplot(428) density_perturbation_axis = self.fig.add_subplot(422) charge_plot = ChargeDistributionPlot(self.S, charge_axis) density_perturbation_plot = SpatialPerturbationDistributionPlot(S, density_perturbation_axis) density_plot = SpatialDistributionPlot(self.S, density_axis) iteration = IterationCounter(self.S, charge_axis) current_plots = TripleCurrentPlot(self.S, current_axes) field_plots = TripleFieldPlot(self.S, field_axes) plots = [ charge_plot, density_plot, iteration, current_plots, density_perturbation_plot, field_plots] super().add_plots(plots) class OneDimPhaseAnim(Animation): def __init__(self, S, alpha=0.6, frames="few"): super().__init__(S, alpha=alpha, frames=frames) self.fig.suptitle("") phase_axes_x = self.fig.add_subplot(111) if any([species.individual_diagnostics for species in S.list_species]): phase_plot_x = PhasePlot(self.S, phase_axes_x, "x", "v_x", self.alpha) plots = [phase_plot_x] else: raise UserWarning("You need diagnostics here!") super().add_plots(plots) self.fig.tight_layout() class OneDimGridAnim(Animation): def __init__(self, S, alpha=0.6, frames="few"): super().__init__(S, alpha=alpha, frames=frames) self.fig.suptitle("") field_axis = self.fig.add_subplot(121) density_axis = self.fig.add_subplot(122) plots = [ FieldPlot(self.S, field_axis, 1), SpatialDistributionPlot(self.S, density_axis) ] super().add_plots(plots) self.fig.tight_layout() class OneDimFieldAnim(Animation): def __init__(self, S, alpha=0.6, frames="few"): super().__init__(S, alpha=alpha, frames=frames) self.fig.suptitle("") field_axis = self.fig.add_subplot(111) plots = [ FieldPlot(self.S, field_axis, 1), ] super().add_plots(plots) self.fig.tight_layout() class OneDimAnimation(Animation): def __init__(self, S, alpha=0.6, frames="few"): super().__init__(S, alpha=alpha, frames=frames) density_axis = self.fig.add_subplot(321) charge_axis = self.fig.add_subplot(323) current_axis = self.fig.add_subplot(324) field_axis = self.fig.add_subplot(326) phase_axes_x = self.fig.add_subplot(322) freq_axes = self.fig.add_subplot(325) if any([species.individual_diagnostics for species in S.list_species]): phase_plot_x = PhasePlot(self.S, phase_axes_x, "x", "v_x", self.alpha) plots = [phase_plot_x] else: plots = [] freq_plot = FrequencyPlot(self.S, freq_axes) density_plot = SpatialDistributionPlot(self.S, density_axis) charge_plot = ChargeDistributionPlot(self.S, charge_axis) iteration = IterationCounter(self.S, freq_axes) current_plot = CurrentPlot(self.S, current_axis, 0) field_plot = FieldPlot(self.S, field_axis, 0) plots += [ freq_plot, density_plot, charge_plot, iteration, current_plot, field_plot] super().add_plots(plots) class ParticleDensityAnimation(Animation): def __init__(self, S, alpha, frames="few"): super().__init__(S, alpha=alpha, frames=frames) density_axis = self.fig.add_subplot(221) charge_x_axis = self.fig.add_subplot(222) charge_y_axis = self.fig.add_subplot(223) charge_z_axis = self.fig.add_subplot(224) current_plots = TripleCurrentPlot(self.S, [charge_x_axis, charge_y_axis, charge_z_axis]) density_plot = SpatialDistributionPlot(self.S, density_axis) iteration = IterationCounter(self.S, charge_x_axis) plots = [ density_plot, current_plots, iteration] super().add_plots(plots)
{ "repo_name": "StanczakDominik/PythonPIC", "path": "pythonpic/visualization/animation.py", "copies": "1", "size": "10546", "license": "bsd-3-clause", "hash": -4513514958369669600, "line_mean": 36.1338028169, "line_max": 126, "alpha_frac": 0.5754788545, "autogenerated": false, "ratio": 3.7623974313235817, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4837876285823582, "avg_score": null, "num_lines": null }
'''animation: animate a simulation in a PyQt5 widget''' from PyQt5 import QtGui, QtCore, QtWidgets from PyQt5.QtCore import Qt from dynamics.constants import meter2foot import numpy as np class EnergyBar(QtWidgets.QWidget): '''widget to display potential, kinetic, and dissipated energies''' def __init__(self, sim, frame): super().__init__() self.sim, self.frame = sim, frame def sizeHint(self): #IGNORE:invalid-name '''return minimum size for widget''' return QtCore.QSize(400,20) def paintEvent(self, _): #IGNORE:invalid-name '''paint widget''' painter = QtGui.QPainter() painter.begin(self) # clear background width,height = self.size().width(), self.size().height() painter.setBrush(QtGui.QBrush(QtGui.QColor(190,190,190))) painter.drawRect(0, 0, width, height) # draw potential energy bar potential_fraction = float((self.frame.PE() - self.frame.PEmin) / self.sim.total_energy) painter.setBrush(QtGui.QBrush(QtGui.QColor(25,255,25))) painter.drawRect(0, 0, int(width*potential_fraction), height) # draw kinetic energy bar kinetic_fraction = float(self.frame.KE() / self.sim.total_energy) painter.setBrush(QtGui.QBrush(QtGui.QColor(255,25,25))) painter.drawRect(width*potential_fraction, 0, int(width*kinetic_fraction), height) painter.end() class EnergiesBox(QtWidgets.QGroupBox): '''box of energy bars, one per frame and spring''' def __init__(self, sim): super().__init__('Energies') grid = QtWidgets.QGridLayout() row = 0 for frame in sim.frames: label = QtWidgets.QLabel(frame.name) grid.addWidget(label, row, 0) label.show() frame.energy_bar = EnergyBar(sim, frame) grid.addWidget(frame.energy_bar, row, 1) row=row+1 self.setLayout(grid) class RangeBox(QtWidgets.QGroupBox): '''display scalar value''' def __init__(self, max_range): super().__init__('Range') self.range_bar = QtWidgets.QProgressBar() self.range_bar.setRange(0, int(max_range)) hbox = QtWidgets.QHBoxLayout() self.text_box = QtWidgets.QLabel() hbox.addWidget(self.text_box) hbox.addWidget(self.range_bar) self.setLayout(hbox) def set_range(self, range_): '''set value''' self.range_bar.setValue(int(range_)) self.text_box.setText("%g feet" % (meter2foot(range_))) class TimeSlider(QtWidgets.QHBoxLayout): timeChanged = QtCore.pyqtSignal() def __init__(self, sim): self.sim = sim super().__init__() self._text = QtWidgets.QLabel() self.addWidget(self._text) self._slider = QtWidgets.QSlider(Qt.Horizontal) self.addWidget(self._slider) self._slider.setRange(0, sim.Y.shape[0]-1) self._slider.setValue(0) self._slider.setPageStep(sim.Y.shape[0]/100) self._slider.setSingleStep(1) self._slider.valueChanged.connect(self._value_changed) def _value_changed(self, _): self._text.setText("{:.3f} sec".format(self.time)) self.timeChanged.emit() @property def time(self): return self.sim.time_step * self._slider.value() class Animation(QtWidgets.QWidget): def __init__(self, sim, dist): super().__init__() self.sim, self.dist = sim, dist self.set_sim_state(time_idx=0) self.sim.total_energy = sum([frame.KE() + frame.PE() - frame.PEmin for frame in sim.frames]) vbox = QtWidgets.QVBoxLayout() self.time_slider = TimeSlider(sim) draw_forces_button = QtWidgets.QCheckBox("Draw Force Vectors") self.drawing=Drawing(self.time_slider, draw_forces_button, sim) energies_box = EnergiesBox(sim) self.range_box = RangeBox(np.max(self.dist(self.sim, self.sim.Y))) vbox.addWidget(self.drawing) vbox.addLayout(self.time_slider) vbox.addWidget(energies_box) vbox.addWidget(self.range_box) vbox.addWidget(draw_forces_button) self.setLayout(vbox) self.time_slider.timeChanged.connect(self.update) draw_forces_button.stateChanged.connect(self.update) self.update() self.show() def set_sim_state(self, time_idx): c_idx=0 for constraint in self.sim.constraints: constraint.enabled = self.sim.constraints_enabled[time_idx,c_idx] c_idx=c_idx+1 self.sim.time_idx = time_idx self.sim.deriv(time_idx * self.sim.time_step, self.sim.Y[time_idx]) def update(self): '''set the simulation state and update the widget''' time = self.time_slider.time time_idx = round(time/self.sim.time_step) time_idx = min(self.sim.num_steps-1, time_idx) self.set_sim_state(time_idx) self.range_box.set_range(self.dist(self.sim, self.sim.Y[time_idx])) self.drawing.update() super().update() class Drawing(QtWidgets.QGraphicsView): def __init__(self, time_slider, draw_forces_button, sim): self.time_slicer = time_slider self.draw_forces_button, self.sim = draw_forces_button, sim self.scene = QtWidgets.QGraphicsScene() super().__init__(self.scene) self.setDragMode(self.ScrollHandDrag) self.setRenderHint(QtGui.QPainter.Antialiasing) self.setRenderHint(QtGui.QPainter.HighQualityAntialiasing) self.setTransformationAnchor(self.AnchorUnderMouse) self.setTransform(QtGui.QTransform.fromScale(1.0, -1.0)) self.sim.time_idx = 0 self.scene.setSceneRect(-10.0, -5.0, 20.0, 20.0) # in drawing units self.scale(32.0,32.0) def sizeHint(self): return QtCore.QSize(400,400) def wheelEvent(self, event): scale_factor = 1.15 if event.delta() > 0: self.scale(scale_factor, scale_factor) else: self.scale(1/scale_factor, 1/scale_factor) def update(self): self.scene.clear() # draw the objects and constraints for frame in self.sim.frames: frame.draw(self.scene) for constraint in self.sim.constraints: constraint.draw(self.scene, self.draw_forces_button.isChecked()) for spring in self.sim.springs: spring.draw(self.scene, self.draw_forces_button.isChecked()) super().update()
{ "repo_name": "treygreer/treb", "path": "treb_sim/src/dynamics/animation.py", "copies": "1", "size": "6659", "license": "mit", "hash": -3767042638693265400, "line_mean": 37.9415204678, "line_max": 77, "alpha_frac": 0.6089502928, "autogenerated": false, "ratio": 3.6249319542732716, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9705075314961511, "avg_score": 0.005761386422352072, "num_lines": 171 }
"""Animation classes.""" import threading import time import random from abc import abstractmethod, ABC from lights import colour as lcolour from lights.action import Effect, TickedEffect, StreamEffect class StaticEffect(Effect): """Constantly display the same colours.""" def run(self, delta): for i, colour in enumerate(self.colours): self.light_string[i] = colour self.light_string.show() # Prevent flicker time.sleep(1/1000) class BrightnessEffect(TickedEffect): """Effect class based on varying the brightness of lights. This class manipulates lights so that they constantly fade between full brightness and black. May be initialised with different starting brightnesses and fade directions (brightening or dimming) to create different effects. Attributes: values: array of floats between 0 and 1 representing light brightness. directions: array of {-1, 1} indicating direction to move brightness. speed: number indicating time taken to cycle brightness from 0 to 0 """ def __init__(self, light_string, colours=None, speed=4, values=None, directions=None): # 100 brightness steps, up and down = 200 interval = speed / 200 if colours is None: colours = [(0, 0, 0)] if len(colours) < len(light_string): padded_colours = [] for i in range(len(light_string)): padded_colours.append(colours[i % len(colours)]) colours=padded_colours super().__init__(light_string, colours, interval=interval) lsl = len(self.light_string) if values is None: # Default to one-off-one-on pattern self.values = [i % 2 for i in range(lsl)] elif len(values) < lsl: self.values = [values[i % len(values)] for i in range(lsl)] else: self.values = values if directions is None: self.directions = [1 if i % 2 == 0 else -1 for i in range(lsl)] elif len(directions) < lsl: self.directions = [directions[i % len(values)] for i in range(lsl)] else: self.directions = directions def update(self): """Fade lights up and down individually.""" # Update brightness values for i in range(len(self.light_string)): self.values[i] += 0.01 * self.directions[i] # Check for bounce for i in range(len(self.light_string)): if self.values[i] < 0: self.values[i] = 0 self.directions[i] = 1 elif self.values[i] > 1: self.values[i] = 1 self.directions[i] = -1 def display(self): # Calculate values to write to Lights for i in range(len(self.light_string)): lum = self.values[i] self.light_string[i] = lcolour.fade(self.colours[i], lum) self.light_string.show() class LoopEffect(StreamEffect): """Removes colours from one end of string and shifts them to the other.""" def get_next_colour(self): if self.reverse: return self.colours[0] else: return self.colours[-1] class MaskShiftEffect(TickedEffect): """Shifts a mask down the string turning lights off according to a pattern. Attributes: pattern: array of {0, 1} to be repeated down the string of lights. """ def __init__(self, light_string, colours, interval=1.0, pattern=None, reverse=False): super().__init__(light_string, colours, interval=interval) if pattern is None: self.pattern = [0, 1] else: self.pattern = pattern self.offset = 0 self.reverse = reverse def update(self): """Move mask down string of lights.""" # Shift pattern if self.reverse: self.offset -= 1 else: self.offset += 1 self.offset %= len(self.pattern) def display(self): for i in range(len(self.light_string)): if self.pattern[(i + self.offset) % len(self.pattern)] == 0: self.light_string[i] = (0, 0, 0) else: self.light_string[i] = self.colours[i] self.light_string.show() class GradientEffect(TickedEffect): """Effect that interpolates between a number of colours Colours are interpolated evening along the string and looped around. Attributes: cycle_time: number indicating time for a colour to loop back smoothing: number indicating ratio of virtual colours to create """ def __init__(self, light_string, colours, cycle_time=10, smoothing=4, reverse=False, interp=lcolour.linear_interpolate): """Initialise gradient effect Args: cycle_time: number indicating time for a colour to loop back smoothing: number indicating ratio of virtual colours to create """ super().__init__(light_string, colours) # Specific to this subclass self.cycle_time = cycle_time self.offset = [0 for i in range(len(self.light_string))] self.reverse = reverse self.interp = interp # Create virtual lights self.smoothing = smoothing self.virtual_length = self.calc_virtual_length() # XXX Can't get virtual_length until super init run # But can't get interval to init without virtual_length self._interval = cycle_time / self.virtual_length self.calc_virtual_colours() def calc_virtual_length(self): return len(self.light_string) * self.smoothing def calc_virtual_colours(self): self.virtual_colours = [] # Calculate colour locations step_between_colours = self.virtual_length / len(self.colours) steps = [] for i in range(len(self.colours)): steps.append(round(i * step_between_colours)) steps.append(self.virtual_length) # Repeat first colour self.colours.append(self.colours[0]) # Calculate virtual colours indices = [(i, steps[i], steps[i+1]) for i in range(len(steps) - 1)] for i, step_a, step_b in indices: t_step = 1 / (step_b - step_a) for j in range(step_b - step_a): colour = self.interp(self.colours[i], self.colours[i + 1], j * t_step) self.virtual_colours.append(colour) def display(self): for i in range(len(self.light_string)): index = (i * self.smoothing - self.offset[i]) % self.virtual_length self.light_string[i] = self.virtual_colours[index] self.light_string.show() def update(self): # Shift pattern for i in range(len(self.light_string)): if self.reverse: self.offset[i] -= 1 else: self.offset[i] += 1 self.offset[i] %= self.virtual_length class ColourFadeEffect(GradientEffect): def __init__(self, light_string, colours, steps=100, **kwargs): self.steps = steps super().__init__(light_string, colours, **kwargs) def calc_virtual_length(self): return int(self.steps * self.cycle_time) def display(self): index = self.offset[0] % self.virtual_length for i in range(len(self.light_string)): self.light_string[i] = self.virtual_colours[index] self.light_string.show() class ColourTwinkleEffect(GradientEffect): def __init__(self, light_string, colours, steps=100, **kwargs): self.steps = steps super().__init__(light_string, colours, **kwargs) self.offsets = [] for i in range(len(self.light_string)): self.offset[i] = random.randint(0, self.virtual_length - 1) def calc_virtual_length(self): return int(self.steps * self.cycle_time)
{ "repo_name": "snorecore/lights", "path": "lights/action/effects.py", "copies": "1", "size": "8035", "license": "mit", "hash": 8449938469253829000, "line_mean": 33.0466101695, "line_max": 79, "alpha_frac": 0.592159303, "autogenerated": false, "ratio": 3.9367956883880453, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0002723970944309927, "num_lines": 236 }
"""Animation classes.""" import threading import time import random from abc import abstractmethod, ABC from lights import colour as lcolour class EffectThread(threading.Thread): """Thread class which runs effects on a string of lights""" def __init__(self, stop_event, effect): """Initialise EffectThread to run an effect Args: stop_event: threading.Event object used to signal shutdown effect: Effect object to run wait: float indicating sleep time between runs """ super().__init__() self.__stopped = stop_event self.__effect = effect self.daemon = True def run(self): """Run effect as quick as possible, with optional delay""" last_time = time.time() delta_time = 0 while not self.__stopped.is_set(): self.__effect.run(delta_time) now = time.time() delta_time = now - last_time last_time = now class Effect(ABC): """Defines effects and manages the threads that run them. Attributes: light_string: Lights object to run effects on colours: Array of 3-tuples representing colours used to initialise effects. """ def __init__(self, light_string, colours): """Initialise Effect with given light_string and colours. Args: light_string: Lights object to run effects on colours: Array of 3-tuples representing colours used to initialise effects. """ super().__init__() self.light_string = light_string self.colours = list(colours) self._thread = None self._stop_event = threading.Event() def start(self): """Start running the effect, stopping any existing thread first.""" if self._thread is not None and self._thread.is_alive(): self.stop() while self._thread.is_alive(): pass self._stop_event.clear() self._thread = EffectThread(self._stop_event, self) self._thread.start() def stop(self): """Stop effect if it is running.""" self._stop_event.set() def is_running(self): """Returns True if the Effect is running.""" if self._thread is None: return False if self._stop_event.is_set(): return False if self._thread.is_alive(): return False return True def join(self, timeout=None): """Wait for effect to stop running. timeout: number indicating time to wait before method returns even if the thread is still running. """ if self._thread is not None: self._thread.join(timeout) @abstractmethod def run(self, delta): """Subclass to implement effects. Args: delta: float indicating time the effect was last run. """ pass class TickedEffect(Effect): """Base class for effects which tick, or update at regular intervals.""" # pylint:disable=abstract-method def __init__(self, *args, interval=1.0, **kwargs): super().__init__(*args, **kwargs) self._interval = interval self._last_tick = 0 def run(self, delta): self._last_tick += delta dirty = False while self._last_tick >= self._interval: dirty = True self.update() self._last_tick -= self._interval if dirty: self.display() @abstractmethod def update(self): """Subclass to update, but not display lights""" pass @abstractmethod def display(self): """Subclass to display lights.""" pass class StreamEffect(TickedEffect): """Effect based on generating a stream of colours. Attributes: delay: float indicating time between adding new colours. reverse: boolean if True add colours to the other end of the string """ def __init__(self, light_string, colours=None, interval=1.0, reverse=False): """Initialise stream effect. If no colours are supplied generates them all using get_next_colour. Args: delay: float indicating time between adding new colours. reverse: boolean if True add colours to the other end of the string """ if colours is None: colours = [] for _ in range(len(light_string)): colours.append(self.get_next_colour()) super().__init__(light_string, colours, interval=interval) self.reverse = reverse @abstractmethod def get_next_colour(self): """Get or generate next colour to add to string""" pass def update(self): """Add colours to string shifting old colours off.""" next_colour = self.get_next_colour() # Shift string if self.reverse: self.colours.pop(0) self.colours.append(next_colour) else: self.colours.pop() self.colours.insert(0, next_colour) def display(self): for i in range(self.light_string.length): self.light_string[i] = self.colours[i] self.light_string.show()
{ "repo_name": "snorecore/lights", "path": "lights/action/__init__.py", "copies": "1", "size": "5274", "license": "mit", "hash": -315602568332536200, "line_mean": 29.4855491329, "line_max": 80, "alpha_frac": 0.5828593098, "autogenerated": false, "ratio": 4.435660218671152, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5518519528471152, "avg_score": null, "num_lines": null }
import time from uiot import colors as _c class Animation(): def __init__(self, device, command_str): self.program = command_str.split() self.device = device self.playing = True self.program = command_str.split() self.step = 0 self.fade_goals = {} self.length = 0 self.starttime = 0 self.delta = 0 self.lasttime = time.ticks_ms() self.effect = None def stop(self): self.playing = False def start(self): if self.program is not None and len(self.program) > 0: if self.step >= len(self.program): self.step = 0 self.playing = True def effect_move(self): count = self.device.ws_leds if self.effect_steps >= 0: # forward # print("forward") top = self.device.get(led_num=count - 1) for i in range(count - 1): c = self.device.get(led_num=count - i - 2) self.device.set(*c, led_num=count - i - 1) self.device.set(*top, led_num=0) else: # backward # print("backward") bottom = self.device.get(led_num=0) for i in range(count - 1): c = self.device.get(led_num=i + 1) self.device.set(*c, led_num=i) self.device.set(*bottom, led_num=count - 1) def next(self): current_time = time.ticks_ms() while self.length <= 0: # find next command commands = "sfpre" while self.step < len(self.program) \ and self.program[self.step] not in commands: self.step += 1 if self.step >= len(self.program): self.stop() return cmd = self.program[self.step] # read arguments args = [] self.step += 1 while self.step < len(self.program) \ and self.program[self.step] not in commands: args.append(self.program[self.step]) self.step += 1 if cmd == "s": # set self.device._command_list_rgb(args) elif cmd == "f": # fade goal: f nr color led_num = int(args[0]) - 1 if led_num <= 0: led_num = 0 self.fade_goals[led_num] = \ (self.device.get(led_num=led_num), \ _c.get(args[1])) print("Fade goal:", led_num, self.fade_goals[led_num]) elif cmd == "e": # effect: e name steps [param 0 [param 1 ...]] e = args[0] self.effect_steps = int(args[1]) if e == "move": self.effect = self.effect_move self.effect_args = args[2:] self.effect_step = 0 print("Move effect:", self.effect_steps) elif cmd == "p": self.length = int(args[0]) self.starttime = current_time elif cmd == "r": self.step = 0 self.length = 0 break # even if this loses a bit of time, # we want to prevent endless loops if self.length > 0: # play animation delta = time.ticks_diff(current_time, self.starttime) progress = min(1.0, delta / self.length) changed = False for i in self.fade_goals: ((fr, fg, fb), (tr, tg, tb)) = self.fade_goals[i] (cr, cg, cb) = self.device.get(led_num=i) if self.length <= delta: (nr, ng, nb) = (tr, tg, tb) self.length = 0 # signal finished of this animation del (self.fade_goals[i]) # clear them else: nr = int(fr + (tr - fr) * progress) # print("i",i,"new r",nr,"from r",fr,"to r",tr,"progress",progress) # debug ng = int(fg + (tg - fg) * progress) nb = int(fb + (tb - fb) * progress) if (cr, cg, cb) != (nr, ng, nb): self.device._set(nr, ng, nb, i) changed = True if self.effect is not None: stepsize = self.length / abs(self.effect_steps) # print("step-debug-1", self.effect_step, stepsize, delta,self.length) # debug while True: current = stepsize * (self.effect_step + 1) # print("step-debug-2", current) # debug if current > delta or current >= self.length + stepsize: break; self.effect_step += 1 # print("executing step", self.effect_step, current, delta, stepsize) # debug self.effect() changed = True if delta >= self.length: # print("finishing", self.effect_step, current, delta, stepsize, changed) # debug self.length = 0 self.effect = None if changed: self.device._write()
{ "repo_name": "ulno/micropython-extra-ulno", "path": "lib/node_types/esp8266/compile/uiot/_rgb_animator.py", "copies": "1", "size": "5302", "license": "mit", "hash": 2538766561035498500, "line_mean": 39.1666666667, "line_max": 101, "alpha_frac": 0.4677480196, "autogenerated": false, "ratio": 3.986466165413534, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4954214185013534, "avg_score": null, "num_lines": null }
"""Animation class which is a DisplayElement which plays animations.""" # animation.py # Mission Pinball Framework # Written by Brian Madden & Gabe Knuth # Released under the MIT License. (See license info at the end of this file.) # Documentation and more info at http://missionpinball.com/mpf import time from mpf.media_controller.core.display import DisplayElement import mpf.media_controller.display_modules.dmd from mpf.system.assets import Asset dmd_palette = [(0, 0, 0), (1, 0, 0), (2, 0, 0), (3, 0, 0), (4, 0, 0), (5, 0, 0), (6, 0, 0), (7, 0, 0), (8, 0, 0), (9, 0, 0), (10, 0, 0), (11, 0, 0), (12, 0, 0), (13, 0, 0), (14, 0, 0), (15, 0, 0)] * 16 class Animation(Asset): def _initialize_asset(self): if 'alpha_color' in self.config: self.alpha_color = (self.config['alpha_color']) else: self.alpha_color = None self.surface_list = None def do_load(self, callback): # todo: # depth # w, h # load from image file if self.file_name.endswith('.dmd'): self.surface_list = mpf.media_controller.display_modules.dmd.load_dmd_file( self.file_name, dmd_palette, self.alpha_color) else: pass # add other animation formats # todo add the alpha self.loaded = True if callback: callback() def _unload(self): self.surface_list = None class AnimationDisplayElement(DisplayElement): """Represents an animation display element. Args: slide: The Slide object this animation is being added to. machine: The main machine object. animation: The name of the registered animation element you'd like to play width: The width of the animation. A value of None means that it will play at its native width. height: The height of the animation. A value of None means that it will play at its native height. start_frame: Frame number (based on a 0-index) that this animation will start playing from. fps: How many frames per second this animation will play. Note that it's not possible to play animations faster that your machine HZ rate. Default is 10. repeat: True/False for whether you want this animation to repeat when it's done. Default is True. drop_frames: Whether this animation should drop (skip) any frames if it gets behind. True means that it will drop frames and skip ahead to whatever frame it should be at based on its fps. False means that it will always play the next frame, even if it's behind. Default is True. play_now: True/False for whether this animation should start playing now. Default is True. x: The horizontal position offset for the placement of this element. y: The vertical position offset for the placement of this element. h_pos: The horizontal anchor. v_pos: The vertical anchor. Note: Full documentation on the use of the x, y, h_pos, and v_pos arguments can be found at: https://missionpinball.com/docs/displays/display-elements/positioning/ """ def __init__(self, slide, machine, animation, width=None, height=None, start_frame=0, fps=10, repeat=False, drop_frames=True, play_now=True, x=None, y=None, h_pos=None, v_pos=None, layer=0, **kwargs): super(AnimationDisplayElement, self).__init__(slide, x, y, h_pos, v_pos, layer) self.loadable_asset = True self.machine = machine if animation not in machine.animations: raise Exception("Received a request to add an animation, but " "the name registered animations.") else: self.animation = machine.animations[animation] self.current_frame = start_frame self.fps = 0 self.repeat = repeat self.drop_frames = drop_frames self.playing = False self.secs_per_frame = 0 self.next_frame_time = 0 self.last_frame_time = 0 self.set_fps(fps) self.layer = layer if self.animation.loaded: self._asset_loaded() else: self.ready = False self.animation.load(callback=self._asset_loaded) if play_now: self.play() # todo need to make it so that play() won't start until this all the # elements in this slide are ready to go def _asset_loaded(self): self.surface_list = self.animation.surface_list self.total_frames = len(self.surface_list) self.element_surface = self.surface_list[self.current_frame] self.set_position(self.x, self.y, self.h_pos, self.v_pos) self.ready = True super(AnimationDisplayElement, self)._asset_loaded() def set_fps(self, fps): """Sets the fps (frames per second) that this animation should play at. Args: fps: Integer value for how many fps you would like this animation to play at. If this animation is currently playing, this method will change the current playback rate. """ self.fps = fps self.secs_per_frame = (1 / float(self.fps)) self.next_frame_time = 0 # forces this to take place immediately def play(self, fps=None, start_frame=None, repeat=None): """Plays this animation. Args: fps: Sets the frames per second this animation should play at. If no value is passed, it will use whatever value was previously configured. start_frame: Sets the frame that you'd like this animation to start at. (The first frame in the animation is frame "0". If no value is passed, it will start at whatever frame it's currently set to. repeat: True/False for whether this animation should repeat when it reaches the end. If no value is passed, it will use whatever it's current repeat setting is. """ if fps: self.set_fps(fps) if start_frame: self.current_frame = start_frame if type(repeat) is bool: self.repeat = repeat self.next_frame_time = 0 self.playing = True self.dirty = True def stop(self, reset=False): """Stops this animation. Args: reset: True/False as to whether this animation should be reset to its first frame so it starts at the beginning the next time its played. Default is False. """ if reset: self.current_frame = 0 self.playing = False self.next_frame_time = 0 def stop_when_done(self): """Tells this animation to stop (i.e. not to repeat) when it reaches its final frame. You can use this while an animation is playing to cause it to gracefully end when it hits the end rather than abrubtly stopping at its current frame.""" self.repeat = False def jump_to_frame(self, frame, show_now=False): """Changes this animation to the frame you pass. Args: frame: Integer value of a frame number. (The first frame is "0"). show_now: True/False as to whether this new frame should be shown immediately. A value of False means that this animation will start at this new frame the next time it's played. """ self.current_frame = frame if show_now: self.show_frame() def jump(self, num_frames, show_now=False): """Jumps forward or backwards a given number of frames. Args: num_frames: An integer value of how many frames you'd like this animation to jump. A positive value jumps ahead, and a negative value jumps back. Note that if you pass a value that's greater than the total number of frames, the animation will "roll over" to the frame you passed. (For example, telling an animation with 10 frames to jump 25 frames will make it end up on frame #5). show_now: True/False as to whether this new frame should be shown immediately. A value of False means that this animation will start at this new frame the next time it's played. """ current_frame = self.current_frame current_frame += num_frames while current_frame > (self.total_frames - 1): if self.repeat: current_frame -= self.total_frames else: current_frame = self.total_frames - 1 self.playing = False self.current_frame = current_frame if show_now: self.show_frame() def show_frame(self): """Forces the current frame of this animation to be shown on the display. (Behind the scenes, this method marks this animation as 'dirty'). Note it might not actually be displayed based on whether the relative layer of this animation display element versus other display elements that may be active on this slide." """ self.element_surface = self.surface_list[self.current_frame] self.dirty = True def update(self): """Internal method which updates this animation to whatever the current frame should be and marks this element as dirty so it will be picked up when the display is refreshed. """ if not self.playing: return current_time = time.time() if not self.next_frame_time: # This animation is just starting up self.last_frame_time = current_time self.next_frame_time = current_time if self.next_frame_time <= current_time: # need to show a frame # Figure out how many frames ahead we should be. # Look at how much time has passed since the last frame was # shown and divide that by secs_per_frame, then convert to int # so we just get the whole number part. num_frames = int((current_time - self.last_frame_time) / self.secs_per_frame) self.last_frame_time = self.next_frame_time if num_frames > 1: # we're behind if self.drop_frames: # If we're dropping frames, then just set the next frame # time to show when it ordinarily should. This will keep # the playback speed consistent. self.next_frame_time = current_time + self.secs_per_frame #self.log.warning('Dropped %s frame(s)', num_frames-1) else: # don't drop any frames # If we're not dropping frames, we want to play them back # as fast as possible to hopefully catch up, so we set the # next frame time to the current time so we show another # frame on the next loop. self.next_frame_time = current_time #self.log.warning('Animation is set to not drop frames, ' # 'but is currently %s frame(s) behind', # num_frames-1) # Only advance 1 frame since we're not dropping any. num_frames = 1 else: # we're on time self.next_frame_time = current_time + self.secs_per_frame self.jump(num_frames, show_now=True) self.decorate() return True if self.decorate(): return True return False asset_class = Animation asset_attribute = 'animations' # self.machine.<asset_attribute> display_element_class = AnimationDisplayElement create_asset_manager = True path_string = 'animations' config_section = 'animations' file_extensions = ('dmd',) # The MIT License (MIT) # Copyright (c) 2013-2015 Brian Madden and Gabe Knuth # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE.
{ "repo_name": "qcapen/mpf", "path": "mpf/media_controller/elements/animation.py", "copies": "2", "size": "13596", "license": "mit", "hash": -5960462587478125000, "line_mean": 36.1475409836, "line_max": 87, "alpha_frac": 0.597675787, "autogenerated": false, "ratio": 4.356296058955463, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005038000139766197, "num_lines": 366 }
"""Animation easing functions using cubic bezier curves.""" def _cubic_bezier_parametric(t, p0, p1, p2, p3): """Return (x, y) on cubic bezier curve for t in [0, 1].""" return tuple([ pow(1 - t, 3) * p0[i] + 3 * pow(1 - t, 2) * t * p1[i] + 3 * (1 - t) * pow(t, 2) * p2[i] + pow(t, 3) * p3[i] for i in xrange(2)]) def _cubic_bezier(x, p0, p1, p2, p3, tolerance=0.001, start=0, end=1): """Return y for given x on the cubic bezier curve using binary search.""" midpoint = start + (end - start) / 2.0 r_x, r_y = _cubic_bezier_parametric(midpoint, p0, p1, p2, p3) difference = r_x - x if abs(difference) < tolerance: return r_y elif difference < 0: return _cubic_bezier(x, p0, p1, p2, p3, start=midpoint, end=end) else: return _cubic_bezier(x, p0, p1, p2, p3, start=start, end=midpoint) def cubic_bezier(x, x1, y1, x2, y2): """Return y for given x on cubic bezier curve with given control points. This is similar to the CSS3 cubic-bezier function. The curve always starts at (0, 0) and ends at (1, 1). The control points (x1, y1) and (x2, y2) define the shape of the curve. """ return _cubic_bezier(x, (0, 0), (x1, y1), (x2, y2), (1, 1)) # create using http://cubic-bezier.com/ linear = lambda x: cubic_bezier(x, 0, 0, 1, 1) ease = lambda x: cubic_bezier(x, .25, .1, .25, 1) elastic_out = lambda x: cubic_bezier(x, .52, 0, .86, 1.26)
{ "repo_name": "tdryer/netscramble", "path": "netscramble/easing.py", "copies": "1", "size": "1458", "license": "bsd-3-clause", "hash": -8700384179168484000, "line_mean": 38.4054054054, "line_max": 78, "alpha_frac": 0.5871056241, "autogenerated": false, "ratio": 2.4628378378378377, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3549943461937838, "avg_score": null, "num_lines": null }
import pygame import os class Animation(object): """ This is a simple library that stores frames for a simple animation """ def __init__(self): """ Constructor - No parameters """ self.frames = [] # Setting this at -1 so the first call of next() # v----- returns the frame 0 -----v self.currentframe = -1 def __iter__(self): """ Allows to return an iterator if necessary """ return self def __next__(self): """ Python2 Compatibility Layer""" return self.next() def next(self): """ This method returns the next frame in the animation, in a ring array fashion Returns: - Next frame from the frame list """ # Returns the frame number in a circular fashion # v----- 0 -> ... -> n-1 -> n -> 0 -----v self.currentframe = (self.currentframe+1) % len(self.frames) return self.frames[self.currentframe] def loadFromDir(self, directory): """ Loads the frames from a given directory using List generators, frames are sorted by name Keyword Arguments: - directory: The Directory to load the frames from Returns: - Nothing """ x = [(os.path.join(directory, f)) for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))] self.frames = [pygame.image.load(y).convert_alpha() for y in sorted(x)] def loadFromList(self, lst): """ Loads the frames from a given list Keyword Arguments: - lst: A list of frames Returns: - Nothing """ self.frames = lst
{ "repo_name": "Penaz91/Glitch_Heaven", "path": "Game/libs/DeprecatedLibs/animation.py", "copies": "1", "size": "1846", "license": "mit", "hash": -3946918026875217000, "line_mean": 27.4, "line_max": 79, "alpha_frac": 0.570964247, "autogenerated": false, "ratio": 4.323185011709602, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5394149258709602, "avg_score": null, "num_lines": null }
"""animation loading and manipulating functions. Please note that this file is alpha, and is subject to modification in future versions of pgu! """ print 'pgu.ani','This module is alpha, and is subject to change.' import math import pygame def _ani_load(tv,name,parts,frames,shape): l = len(frames) #print name,parts,l n = parts.pop() if len(parts): s = l/n for i in xrange(0,n): _ani_load(tv,name + ".%d"%i,parts[:],frames[s*i:s*(i+1)],shape) return for i in xrange(0,n): tv.images[name+".%d"%i] = frames[i],shape def ani_load(tv,name,img,size,shape,parts): """Load an animation from an image Arguments: tv -- vid to load into name -- prefix name to give the images image -- image to load anis from size -- w,h size of image shape -- shape of image (usually a subset of 0,0,w,h) used for collision detection parts -- list of parts to divide the animation into for example parts = [4,5] would yield 4 animations 5 frames long, 20 total for example parts = [a,b,c] would yield ... images['name.a.b.c'] ..., a*b*c total """ parts = parts[:] parts.reverse() w,h = size frames = [] for y in xrange(0,img.get_height(),h): for x in xrange(0,img.get_width(),w): frames.append(img.subsurface(x,y,w,h)) _ani_load(tv,name,parts,frames,shape) def image_rotate(tv,name,img,shape,angles,diff=0): """Rotate an image and put it into tv.images Arguments: tv -- vid to load into name -- prefix name to give the images image -- image to load anis from shape -- shape fimage (usually a subset of 0,0,w,h) used for collision detection angles -- a list of angles to render in degrees diff -- a number to add to the angles, to correct for source image not actually being at 0 degrees """ w1,h1 = img.get_width(),img.get_height() shape = pygame.Rect(shape) ps = shape.topleft,shape.topright,shape.bottomleft,shape.bottomright for a in angles: img2 = pygame.transform.rotate(img,a+diff) w2,h2 = img2.get_width(),img2.get_height() minx,miny,maxx,maxy = 1024,1024,0,0 for x,y in ps: x,y = x-w1/2,y-h1/2 a2 = math.radians(a+diff) #NOTE: the + and - are switched from the normal formula because of #the weird way that pygame does the angle... x2 = x*math.cos(a2) + y*math.sin(a2) y2 = y*math.cos(a2) - x*math.sin(a2) x2,y2 = x2+w2/2,y2+h2/2 minx = min(minx,x2) miny = min(miny,y2) maxx = max(maxx,x2) maxy = max(maxy,y2) r = pygame.Rect(minx,miny,maxx-minx,maxy-miny) #print r #((ww-w)/2,(hh-h)/2,w,h) tv.images["%s.%d"%(name,a)] = img2,r
{ "repo_name": "fablab-bayreuth/trommelbold", "path": "software/ColorfulSequencer/pgu/ani.py", "copies": "4", "size": "2923", "license": "unlicense", "hash": -3288663067599624700, "line_mean": 33.3882352941, "line_max": 106, "alpha_frac": 0.5788573384, "autogenerated": false, "ratio": 3.2191629955947136, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5798020333994713, "avg_score": null, "num_lines": null }
"""animation loading and manipulating functions. Please note that this file is alpha, and is subject to modification in future versions of pgu! """ print ('pgu.ani - This module is alpha, and is subject to change.') import math import pygame # Quick fix for python3 try: xrange except: xrange = range def _ani_load(tv,name,parts,frames,shape): l = len(frames) n = parts.pop() if len(parts): s = l/n for i in xrange(0,n): _ani_load(tv,name + ".%d"%i,parts[:],frames[s*i:s*(i+1)],shape) return for i in xrange(0,n): tv.images[name+".%d"%i] = frames[i],shape def ani_load(tv,name,img,size,shape,parts): """Load an animation from an image Arguments: tv -- vid to load into name -- prefix name to give the images image -- image to load anis from size -- w,h size of image shape -- shape of image (usually a subset of 0,0,w,h) used for collision detection parts -- list of parts to divide the animation into for example parts = [4,5] would yield 4 animations 5 frames long, 20 total for example parts = [a,b,c] would yield ... images['name.a.b.c'] ..., a*b*c total """ parts = parts[:] parts.reverse() w,h = size frames = [] for y in xrange(0,img.get_height(),h): for x in xrange(0,img.get_width(),w): frames.append(img.subsurface(x,y,w,h)) _ani_load(tv,name,parts,frames,shape) def image_rotate(tv,name,img,shape,angles,diff=0): """Rotate an image and put it into tv.images Arguments: tv -- vid to load into name -- prefix name to give the images image -- image to load anis from shape -- shape fimage (usually a subset of 0,0,w,h) used for collision detection angles -- a list of angles to render in degrees diff -- a number to add to the angles, to correct for source image not actually being at 0 degrees """ w1,h1 = img.get_width(),img.get_height() shape = pygame.Rect(shape) ps = shape.topleft,shape.topright,shape.bottomleft,shape.bottomright for a in angles: img2 = pygame.transform.rotate(img,a+diff) w2,h2 = img2.get_width(),img2.get_height() minx,miny,maxx,maxy = 1024,1024,0,0 for x,y in ps: x,y = x-w1/2,y-h1/2 a2 = math.radians(a+diff) #NOTE: the + and - are switched from the normal formula because of #the weird way that pygame does the angle... x2 = x*math.cos(a2) + y*math.sin(a2) y2 = y*math.cos(a2) - x*math.sin(a2) x2,y2 = x2+w2/2,y2+h2/2 minx = min(minx,x2) miny = min(miny,y2) maxx = max(maxx,x2) maxy = max(maxy,y2) r = pygame.Rect(minx,miny,maxx-minx,maxy-miny) #((ww-w)/2,(hh-h)/2,w,h) tv.images["%s.%d"%(name,a)] = img2,r
{ "repo_name": "ITA-ftuyama/TG", "path": "pgu/ani.py", "copies": "3", "size": "2952", "license": "mit", "hash": -8656625910157725000, "line_mean": 32.1685393258, "line_max": 106, "alpha_frac": 0.5809620596, "autogenerated": false, "ratio": 3.222707423580786, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.047036744207165145, "num_lines": 89 }
"""Animation. Animation is set of keyframes. Value of selected attribute changes in time. Keyframe: (time, value) Objects have animation manager which manages animation graph and switching.""" from __future__ import division from operator import itemgetter from xoinvader.utils import Point, Timer class AnimationBoundariesExceeded(Exception): """Exception to show that interpolated value will be incorrect.""" def __init__(self, first, current_time, second): super(AnimationBoundariesExceeded, self).__init__( self, "Animation frame boundaries exceeded: {0} <= {1} <= {2}".format( first, current_time, second)) class InterpolationUnknownTypes(Exception): """Such type combination is unsupported.""" def __init__(self, first, second): super(InterpolationUnknownTypes, self).__init__( self, "Unknown types of interpolating values: {0} and {1}".format( first, second)) # TODO: Implement animation graph and etc class AnimationManager(object): """Manage list of object animation.""" def __init__(self): self._animations = {} self._animation = None @property def animation(self): """AnimationManager's current animation name. To set animation - assign it's name. :getter: yes :setter: yes :type: str """ if self._animation: return self._animation.name else: raise AttributeError("There is no available animation.") @animation.setter def animation(self, name): if name in self._animations: self._animation = self._animations[name] else: raise ValueError("No such animation: '{0}'.".format(name)) def add(self, name, *args, **kwargs): """Add new animation, pass args to Animation class. See interface of `class::xoinvader.animation.Animation`. :param str name: animation name """ animation = Animation(name, *args, **kwargs) self._animations[name] = animation if not self._animation: self._animation = animation def update(self): """Update manager's state.""" if not self._animation: return try: self._animation.update() except StopIteration: return # TODO: think about method to change animation # pylint: disable=too-many-instance-attributes,too-many-arguments # pylint: disable=too-few-public-methods class Animation(object): """Animation unit. Animation object holds sorted list of (time, value) items and changes selected attribute of bound object according to local animation time. Time measured by timer. When current time is greater or equal then time of next keyframe - animation object changes it to appropriate value. When animation is done and if not looped - raise StopIteration. In case of interpolated animation value calculation occurs within two bounding frames and on frame switch. :param str name: animation name :param object bind: object to bind animation :param str attr: attribute to change in frames :param list keyframes: (float, object) tuples :param bool interp: interpolate values between frames or not :param bool loop: loop animation or not """ def __init__(self, name, bind, attr, keyframes, interp=False, loop=False): self._name = name self._obj = bind self._attr = attr if not keyframes: raise ValueError("Animation keyframes must not be empty.") self._keyframes = sorted(keyframes, key=itemgetter(0)) self._interp = interp self._loop = loop # Timer for tracking local time self._timer = Timer(self._keyframes[-1][0], lambda: True) self._timer.start() # Current keyframe index self._current = 0 if self._interp: self.update = self._update_interpolated else: self.update = self._update_discrete @property def name(self): """Animation's name. :getter: yes :setter: no :type: str """ return self._name def _apply_value(self, value): """Apply new value to linked object. :param obj value: value to apply """ setattr(self._obj, self._attr, value) def _update_interpolated(self): """Advance animation and interpolate value. NOTE: animation frame switching depends on interp mode animation with interpolation switches frame only when current local time exceeds NEXT frames' time border. """ self._check_animation_state() self._timer.update() current_time = self._timer.get_elapsed() keyframe = self._keyframes[self._current] next_keyframe = self._keyframes[self._current + 1] # it's time to switch keyframe if current_time >= next_keyframe[0]: self._current += 1 keyframe = self._keyframes[self._current] if self._current == len(self._keyframes) - 1: self._apply_value(keyframe[1]) self._current += 1 self._check_animation_state() return next_keyframe = self._keyframes[self._current + 1] value = interpolate(keyframe, next_keyframe, current_time) self._apply_value(value) def _update_discrete(self): """Advance animation without interpolating value. NOTE: animation frame switching depends on interp mode discrete animation swiches frame and updates value only if current local time is >= time of current keyframe. No need to worry about calculating value between frames - thus no need to complicate behaviour. """ self._check_animation_state() self._timer.update() keyframe = self._keyframes[self._current] # Check if animation need to switch keyframe if self._timer.get_elapsed() >= keyframe[0]: self._apply_value(keyframe[1]) self._current += 1 def _check_animation_state(self): """Check animation state and restart if needed. :raise StopIteration: when animation exceeded frames. """ if len(self._keyframes) == self._current: if self._loop: self._current = 0 self._timer.restart() else: self._timer.stop() raise StopIteration def linear_equation(val1, val2, time1, time2, current_time): """Linear equation to get interpolated value. :param float val1: first keyframe value :param float val2: second keyframe value :param float time1: first keyframe local time :param float time2: second keyframe local time :param float current_time: current animation local time """ return val1 + (val2 - val1) / (time2 - time1) * (current_time - time1) def same_type(values, types): """Check if values are belongs to same type or type tuple. :param collections.Iterable values: values to check type similarity :param tuple|type types: type or tuple of types """ return all(map(lambda it: isinstance(it, types), values)) def interpolate(first, second, current_time): """Interpolate value by two bounding keyframes. :param collections.Iterable first: first bounding keyframe :param collections.Iterable second: second bounding keyframe :param float current_time: current animation local time :raises AnimationBoundariesExceeded: when time interval is invalid :raises InterpolationUnknownTypes: when interpolating invalid types """ if not first[0] <= current_time <= second[0]: raise AnimationBoundariesExceeded(first[0], current_time, second[0]) def frames_of(*args): """If frames both of specified type.""" return same_type((first[1], second[1]), args) if frames_of(int, float): value = linear_equation( float(first[1]), float(second[1]), float(first[0]), float(second[0]), float(current_time)) elif frames_of(Point): value = linear_equation( first[1], second[1], float(first[0]), float(second[0]), float(current_time)) else: raise InterpolationUnknownTypes(type(first[1]), type(second[1])) return value
{ "repo_name": "pankshok/xoinvader", "path": "xoinvader/animation.py", "copies": "1", "size": "8460", "license": "mit", "hash": 7379855302645992000, "line_mean": 29.652173913, "line_max": 78, "alpha_frac": 0.6289598109, "autogenerated": false, "ratio": 4.417754569190601, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 276 }
"""Animation.""" from matplotlib import animation import matplotlib.pyplot as plt import numpy as np from moviepy.editor import VideoClip from moviepy.video.io.bindings import mplfig_to_npimage from .chart_utils import plotwrapper, noticks __all__ = ['save_movie', 'play', 'save_frames'] def save_movie(make_frame, duration, filename, fps=20): """Writes an animation to disk.""" anim = VideoClip(make_frame, duration=duration) if filename.endswith('.gif'): anim.write_gif(filename, fps=fps) elif filename.endswith('.mp4'): anim.write_videofile(filename, fps=fps) else: raise ValueError(f'Invalid file type for {filename}. Must be .gif or .mp4') return anim @plotwrapper def play(frames, repeat=True, fps=15, cmap='seismic_r', clim=None, **kwargs): """Plays the stack of frames as a movie""" fig = kwargs['fig'] ax = kwargs['ax'] img = ax.imshow(frames[0], aspect='equal') noticks(ax=ax) # Set up the colors img.set_cmap(cmap) img.set_interpolation('nearest') if clim is None: maxval = np.max(np.abs(frames)) img.set_clim([-maxval, maxval]) else: img.set_clim(clim) # Animation function (called sequentially) def animate(i): # ax.set_title('Frame {0:#d}'.format(i + 1)) img.set_data(frames[i]) # Call the animator dt = 1000 / fps anim = animation.FuncAnimation(fig, animate, np.arange(frames.shape[0]), interval=dt, repeat=repeat) return anim @plotwrapper def save_frames(frames, filename, cmap='seismic_r', T=None, clim=None, fps=15, figsize=None, **kwargs): """Saves the stack of frames as a movie""" fig = kwargs['fig'] ax = kwargs['ax'] # total length if T is None: T = frames.shape[0] X = frames.copy() img = ax.imshow(X[0]) ax.axis('off') ax.set_aspect('equal') ax.set_xlim(0, X.shape[1]) ax.set_ylim(0, X.shape[2]) ax.set_xticks([]) ax.set_yticks([]) # Set up the colors img.set_cmap(cmap) img.set_interpolation('nearest') if clim is None: maxval = np.max(np.abs(X)) img.set_clim([-maxval, maxval]) else: img.set_clim(clim) plt.show() plt.draw() dt = 1 / fps def animate(t): i = np.mod(int(t / dt), T) # ax.set_title(f't={i*0.01:2.2f} s') img.set_data(X[i]) return mplfig_to_npimage(fig) save_movie(animate, T * dt, filename, fps=fps)
{ "repo_name": "nirum/jetpack", "path": "jetpack/animation.py", "copies": "2", "size": "2567", "license": "mit", "hash": -8679784352238987000, "line_mean": 21.7168141593, "line_max": 79, "alpha_frac": 0.5890144137, "autogenerated": false, "ratio": 3.18091697645601, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9669362457718436, "avg_score": 0.020113786487514825, "num_lines": 113 }
# Animation of a quantum harmonic oscillator # # Units are such that m_e=1=h_bar=w # # When setting the range on n to be larger than roughly 50 there is crazy numbers # we have discussed this and it appears to be due to the fact that hermite # polynomials are so large that there is large errors as you go to higher orders # # This is was a very tricky code to write. I calucluates hermit polynomials # up to any order. Takes seconds to run. Sorry if this it is hard to understand # the algorithm although I try to explain in comments. It was helpuful to draw # a grid with no gridlines that had all the coefficants in it. Then if you look # down the diagnoal you see you multiply by two from the one up and to the # left. Then for all other terms you do some funny business that I explain above. # # Inputs nmin=40 nmax=50 si_squared=0 # Set to 1 if you would like to see si squared amination si_real=0 # Set to 1 if you would like to see read part of si animation si_imaginary=0 # Set to 1 if you would like to see the imaginary part of si animation from collections import defaultdict import cmath as c import math as m import matplotlib.pyplot as plt import matplotlib.animation as animation pi=m.pi xmin=-3*pi xmax=3*pi tmin=0 tmax=2*pi nstep=1 x_number=1000 # The larger the smoother the curve t_number=100 x_step=(xmax-xmin)/x_number t_step=(tmax-tmin)/t_number t=0 coef=defaultdict(list) order=101 # # Create an empty matrix with n=order and m=order # m=0 while m <= order-1: n=0 while n <= order: coef[m].append(0) n=n+1 m=m+1 # # Initialize the first two coefficants # coef[1][0] = 1 coef[2][1] = 2 n=2 counter=order-1 # # Goes through and applies the first rule in the recursion, the being # multiply the highest order coeficant of order say A in the previous # polynomial by 2 and put that value as the coefficant for the next # polynomial's highest order which is order A+1 # while n < order-1: while counter > 0: x=coef[n][counter] y=2*x coef[n+1][counter+1]=coef[n+1][counter+1]+y counter=counter-1 counter=order-1 n=n+1 n=2 counter=0 # # Goes through and applies the second rule in the recursion, that being # multiply every order term in the polynomial two n values down by two # and the n value you would like to create, and add that to the value to the # coefficant in the previous polynomial multiplied by two # while n < order-1: sort=len(coef[n])-1 while sort >0: if coef[n][sort] != 0: break else: sort=sort-1 while counter < order: if counter < sort: w=(n-1)*(-2)*coef[n-1][counter]+2*coef[n][counter-1] coef[n+1][counter]=coef[n+1][counter]+w counter=counter+1 else: break counter=0 n=n+1 # Calculates the value of the hermite polynomial for a particular order and a particular # x location def H_n(n,x): N=n m=0 H=0 while m < N: H=H+coef[n][m]*x**m m=m+1 return H # Calculates Si for a particular x and n value def Si(x,n,t): import math as m E=E_n(n,t) si=(m.cos(E)+1j*m.sin(E))*(1/pi)**(1/4)*(1/m.sqrt(((2**n)*(m.factorial(n)))))*H_n(n,x)*(m.exp(-.5*(x**2))) return si def E_n(n,t): E_n=-1*(t*(n-.5)) return E_n # # si_combo creates a super position of differnet states # # x = position # nmin = minimum state number # nmax= maximum state number # nstep = step number between states # t = time # def si_combo(x,t): si_combo=0 n=nmin while n <= nmax: si_combo=si_combo+Si(x,n,t) n=n+nstep return si_combo # Animation loop def animate_si_squared(i): global t x=xmin si_squared=[] x_list=[] while x <= xmax: si_squared.append((si_combo(x,t)*si_combo(x,t).conjugate()).real) x_list.append(x) x=x+x_step t=t+t_step ax1.clear() ax1.scatter(x_list,si_squared) ax1.axis([xmin,xmax,0,max(si_squared)]) plt.xlabel('X position') plt.ylabel('Si Squared (Probability)') plt.title(' Si Squared vs. X position ') def animate_si_real(i): global t x=xmin si_real=[] x_list=[] while x<= xmax: si_real.append(si_combo(x,t).real) x_list.append(x) x=x+x_step t=t+t_step ax1.clear() ax1.scatter(x_list,si_real) ax1.axis([xmin,xmax,min(si_real),max(si_real)]) plt.xlabel('X position') plt.ylabel('Re(Si)') plt.title('Re(Si) vs. X position ') def animate_si_imaginary(i): global t x=xmin si_imag=[] x_list=[] while x<= xmax: si_imag.append(si_combo(x,t).imag) x_list.append(x) x=x+x_step t=t+t_step ax1.clear() ax1.scatter(x_list,si_imag) ax1.axis([xmin,xmax,min(si_imag),max(si_imag)]) plt.xlabel('X position') plt.ylabel('Im(Si)') plt.title('Im(Si) vs. X position ') fig=plt.figure() ax1=fig.add_subplot(1,1,1) if si_squared == 1: ani=animation.FuncAnimation(fig,animate_si_squared,interval=1) if si_real == 1: ani=animation.FuncAnimation(fig,animate_si_real,interval=10) if si_imaginary == 1: ani=animation.FuncAnimation(fig,animate_si_imaginary,interval=10) plt.show()
{ "repo_name": "mannion9/Intro-to-Python", "path": "Simulations/Harmonic Oscillator Animation.py", "copies": "1", "size": "5257", "license": "mit", "hash": -4609989653512840700, "line_mean": 22.1585903084, "line_max": 110, "alpha_frac": 0.6380064676, "autogenerated": false, "ratio": 2.930323299888517, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4068329767488517, "avg_score": null, "num_lines": null }
# Animation of a quantum particle in a infitie square well # # Units are such that m_e=h_bar=1 # There are three main things shown in this simulation # # 1) When there is only one state it does not move, and thats why we call # these states stationary states # # 2) When there is the supperposition of two low states we get some movements # that slightly resembes a classical particle moving in a box # (choose nmin = 1 and nmax = 2) # # 3) When there is the supperposition of high energy states we get very # classical behavior # (choose nmin = 100 nmax = 110) # Inputs nmin=100 nmax=110 si_squared=1 # Set to 1 if you would like to see si squared animation si_real=0 # Set to 1 if you would like to see real part of si animation si_imaginary=0 # Set to 1 if you would like to see the imaginary part of si aniamtion three_D =1 # Set to 1 if you would like a 3D plot of the above value you selected # one of the above must be set to 1 # Beware you cannot let the first animation run too long (more than one # oscillation or else your computer will slow down because there will # be so many datapoints) # # 3D=0 for none # 3D=1 for si_squared # Imports plotting tools and math and complex math functions import matplotlib.pyplot as plt import matplotlib.animation as animation from mpl_toolkits.mplot3d import Axes3D import cmath as c import math as m x_global=[] t_global=[] si_squared_global=[] si_real_global=[] si_imag_global=[] pi=m.pi L=2*pi xmin=0 xmax=L tmin=0 tmax=2*pi # Found using classical I think (I forgot I initally wrote this code a few weeks ago) nstep=1 x_number=1000 # The larger the smoother the curve (This value is most efficant) t_number=1000 # The larger the smoother the change in frames x_step=(xmax-xmin)/x_number t_step=(tmax-tmin)/t_number t=0 # This is stationary state * the time dependence for the infinite square well def Si(x,n,t): E=E_n(n,t) si=m.sqrt(2/L)*m.sin(n*pi*x/L)*(m.cos(E)+1j*m.sin(E)) return si # Standard time dependence for infitine square well def E_n(n,t): E_n=-1*(t*n**2*pi**2/(2*L**2)) return E_n # Supperposition of states def si_combo(x,t): si_combo=0 n=nmin while n <= nmax: si_combo=si_combo+Si(x,n,t) n=n+nstep return si_combo # Animation loop def animate_si_squared(i): global t x=xmin si_squared=[] x_list=[] while x <= xmax: si_squared.append((si_combo(x,t)*si_combo(x,t).conjugate()).real) x_list.append(x) x_global.append(x) t_global.append(t) si_squared_global.append((si_combo(x,t)*si_combo(x,t).conjugate()).real) x=x+x_step t=t+t_step ax1.clear() ax1.scatter(x_list,si_squared) ax1.axis([xmin,xmax,0,max(si_squared)]) plt.xlabel('X position') plt.ylabel('Si Squared (Probability)') plt.title(' Si Squared vs. X position ') def animate_si_real(i): global t x=xmin si_real=[] x_list=[] while x<= xmax: si_real.append(si_combo(x,t).real) x_list.append(x) x_global.append(x) t_global.append(t) si_real_global.append(si_combo(x,t).real) x=x+x_step t=t+t_step ax1.clear() ax1.scatter(x_list,si_real) ax1.axis([xmin,xmax,min(si_real),max(si_real)]) plt.xlabel('X position') plt.ylabel('Re(Si)') plt.title('Re(Si) vs. X position ') def animate_si_imaginary(i): global t x=xmin si_imag=[] x_list=[] while x<= xmax: si_imag.append(si_combo(x,t).imag) x_list.append(x) x_global.append(x) t_global.append(t) si_imag_global.append(si_combo(x,t).imag) x=x+x_step t=t+t_step ax1.clear() ax1.scatter(x_list,si_imag) ax1.axis([xmin,xmax,min(si_imag),max(si_imag)]) plt.xlabel('X position') plt.ylabel('Im(Si)') plt.title('Im(Si) vs. X position ') fig=plt.figure() ax1=fig.add_subplot(1,1,1) if si_squared == 1: ani=animation.FuncAnimation(fig,animate_si_squared,interval=10) if si_real == 1: ani=animation.FuncAnimation(fig,animate_si_real,interval=10) if si_imaginary == 1: ani=animation.FuncAnimation(fig,animate_si_imaginary,interval=10) plt.show() if three_D == 1: fig=plt.figure() ax=fig.add_subplot(111,projection='3d') ax.scatter(x_global,t_global,si_squared_global) ax.set_xlabel('x position') ax.set_ylabel('time') ax.set_zlabel('si squared') plt.show()
{ "repo_name": "mannion9/Intro-to-Python", "path": "Simulations/Infinite Square Well Animation.py", "copies": "1", "size": "4524", "license": "mit", "hash": 7109962341381116000, "line_mean": 25, "line_max": 96, "alpha_frac": 0.6432360743, "autogenerated": false, "ratio": 2.8870453095086153, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4030281383808615, "avg_score": null, "num_lines": null }
# Animation.py # Aaron Taylor # Moose Abumeeiz # # This is the class for all animations in the game, based on time # it will advance the frame when it is the correct time # from pygame import * from time import time as cTime class Animation: """Class to handle all animation timing""" def __init__(self, frames, interval, shouldLoop=True): self.frames = frames self.frameCount = len(self.frames) self.interval = interval/self.frameCount # Wait between frames self.shouldLoop = shouldLoop self.lastFrame = cTime() # Creation time self.currentIndex = -1 # There will be an step right away, counter act it self.frame = self.frames[self.currentIndex] # Start off current frame self.looped = False # Has made a complete loop # Assume all images are the same size self.width = self.frames[0].get_width() self.height = self.frames[0].get_height() def resize(self, percent): 'Resize all frames' # Create new height self.width = int(self.width*percent) self.height = int(self.height*percent) # Resize all frames self.frames = [transform.scale(self.frames[i], (self.width, self.height)) for i in range(len(self.frames))] self.frame = self.frames[self.currentIndex] # Set new frame incase no step def setInterval(self, interval): 'Change animation interval' # Re-set the frame interval self.interval = interval/self.frameCount def setFrame(self, index): 'Sets the current frame index' # Ensure changing it wont cause an error if index < self.frameCount: self.currentIndex = index self.frame = self.frames[self.currentIndex] def reset(self, time): 'Reset animation to start' # Re-set the current index and re-set the current frame self.currentIndex = 0 self.frame = self.frames[self.currentIndex] self.lastFrame = time def step(self): 'Step the animation forward a frame' self.currentIndex += 1 if self.currentIndex >= self.frameCount: # The animation has surpassed the last frame, restart it if self.shouldLoop: self.currentIndex = 0 self.looped = True else: self.currentIndex -= 1 self.frame = self.frames[self.currentIndex] def render(self, time): 'Return the current frame' # Decide wether or not we should advance a frame if time-self.lastFrame >= self.interval: self.step() self.lastFrame = time return self.frame
{ "repo_name": "ExPHAT/binding-of-isaac", "path": "Animation.py", "copies": "1", "size": "2346", "license": "mit", "hash": 3485127968386562000, "line_mean": 26.6, "line_max": 109, "alpha_frac": 0.7169650469, "autogenerated": false, "ratio": 3.341880341880342, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4558845388780342, "avg_score": null, "num_lines": null }
# animation.py # Animation """ This is an example of animation using pygame. An example from Chapter 17 of 'Invent Your Own Games With Python' by Al Sweigart A.C. LoGreco """ import pygame, sys, time from pygame.locals import * # set up pygame pygame.init() # set up the window WINDOWWIDTH = 400 WINDOWHEIGHT = 400 windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32) pygame.display.set_caption('Animation') # set up direction vaiables DOWNLEFT = 1 DOWNRIGHT = 3 UPLEFT = 7 UPRIGHT = 9 MOVESPEED = 4 # set up the colors BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # set up the block data structure b1 = {'rect':pygame.Rect(300, 80, 50, 100), 'color':RED, 'dir':UPRIGHT} b2 = {'rect':pygame.Rect(200, 200, 20, 20), 'color':GREEN, 'dir':UPLEFT} b3 = {'rect':pygame.Rect(100, 150, 60, 60), 'color':BLUE, 'dir':DOWNLEFT} blocks = [b1, b2, b3] # main game loop while True: # check for the QUIT event for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() # draw the black background onto the surface windowSurface.fill(BLACK) for b in blocks: # move the blocks data structure if b['dir'] == DOWNLEFT: b['rect'].left -= MOVESPEED b['rect'].top += MOVESPEED if b['dir'] == DOWNRIGHT: b['rect'].left += MOVESPEED b['rect'].top += MOVESPEED if b['dir'] == UPLEFT: b['rect'].left -= MOVESPEED b['rect'].top -= MOVESPEED if b['dir'] == UPRIGHT: b['rect'].left += MOVESPEED b['rect'].top -= MOVESPEED # check if the block has moved out of the window if b['rect'].top < 0: # block has moved past the top if b['dir'] == UPLEFT: b['dir'] = DOWNLEFT if b['dir'] == UPRIGHT: b['dir'] = DOWNRIGHT if b['rect'].bottom > WINDOWHEIGHT: # block has moved past the bottom if b['dir'] == DOWNLEFT: b['dir'] = UPLEFT if b['dir'] == DOWNRIGHT: b['dir'] = UPRIGHT if b['rect'].left < 0: # blcok has moved past the left side if b['dir'] == DOWNLEFT: b['dir'] = DOWNRIGHT if b['dir'] == UPLEFT: b['dir'] = UPRIGHT if b['rect'].right > WINDOWWIDTH: # block has moved past the right side if b['dir'] == DOWNRIGHT: b['dir'] = DOWNLEFT if b['dir'] == UPRIGHT: b['dir'] = UPLEFT # draw the block onto the surface pygame.draw.rect(windowSurface, b['color'], b['rect']) # draw the window onto the screen pygame.display.update() time.sleep(0.02)
{ "repo_name": "aclogreco/InventGamesWP", "path": "ch17/animation.py", "copies": "1", "size": "2838", "license": "bsd-2-clause", "hash": -29043018623189908, "line_mean": 26.5533980583, "line_max": 75, "alpha_frac": 0.5412262156, "autogenerated": false, "ratio": 3.3825983313468413, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44238245469468407, "avg_score": null, "num_lines": null }
"""Animations of pulsating sphere.""" import sfs import numpy as np from matplotlib import pyplot as plt from matplotlib import animation def particle_displacement(omega, center, radius, amplitude, grid, frames, figsize=(8, 8), interval=80, blit=True, **kwargs): """Generate sound particle animation.""" velocity = sfs.fd.source.pulsating_sphere_velocity( omega, center, radius, amplitude, grid) displacement = sfs.fd.displacement(velocity, omega) phasor = np.exp(1j * 2 * np.pi / frames) fig, ax = plt.subplots(figsize=figsize) ax.axis([grid[0].min(), grid[0].max(), grid[1].min(), grid[1].max()]) scat = sfs.plot2d.particles(grid + displacement, **kwargs) def update_frame_displacement(i): position = (grid + displacement * phasor**i).apply(np.real) position = np.column_stack([position[0].flatten(), position[1].flatten()]) scat.set_offsets(position) return [scat] return animation.FuncAnimation( fig, update_frame_displacement, frames, interval=interval, blit=blit) def particle_velocity(omega, center, radius, amplitude, grid, frames, figsize=(8, 8), interval=80, blit=True, **kwargs): """Generate particle velocity animation.""" velocity = sfs.fd.source.pulsating_sphere_velocity( omega, center, radius, amplitude, grid) phasor = np.exp(1j * 2 * np.pi / frames) fig, ax = plt.subplots(figsize=figsize) ax.axis([grid[0].min(), grid[0].max(), grid[1].min(), grid[1].max()]) quiv = sfs.plot2d.vectors( velocity, grid, clim=[-omega * amplitude, omega * amplitude], **kwargs) def update_frame_velocity(i): quiv.set_UVC(*(velocity[:2] * phasor**i).apply(np.real)) return [quiv] return animation.FuncAnimation( fig, update_frame_velocity, frames, interval=interval, blit=True) def sound_pressure(omega, center, radius, amplitude, grid, frames, pulsate=False, figsize=(8, 8), interval=80, blit=True, **kwargs): """Generate sound pressure animation.""" pressure = sfs.fd.source.pulsating_sphere( omega, center, radius, amplitude, grid, inside=pulsate) phasor = np.exp(1j * 2 * np.pi / frames) fig, ax = plt.subplots(figsize=figsize) im = sfs.plot2d.amplitude(np.real(pressure), grid, **kwargs) ax.axis([grid[0].min(), grid[0].max(), grid[1].min(), grid[1].max()]) def update_frame_pressure(i): distance = np.linalg.norm(grid) p = pressure * phasor**i if pulsate: p[distance <= radius + amplitude * np.real(phasor**i)] = np.nan im.set_array(np.real(p)) return [im] return animation.FuncAnimation( fig, update_frame_pressure, frames, interval=interval, blit=True) if __name__ == '__main__': # Pulsating sphere center = [0, 0, 0] radius = 0.25 f = 750 # frequency omega = 2 * np.pi * f # angular frequency # Axis limits xmin, xmax = -1, 1 ymin, ymax = -1, 1 # Animations frames = 20 # frames per period # Particle displacement amplitude = 5e-2 # amplitude of the surface displacement grid = sfs.util.xyz_grid([xmin, xmax], [ymin, ymax], 0, spacing=0.025) ani = particle_displacement( omega, center, radius, amplitude, grid, frames, c='Gray') ani.save('pulsating_sphere_displacement.gif', dpi=80, writer='imagemagick') # Particle velocity amplitude = 1e-3 # amplitude of the surface displacement grid = sfs.util.xyz_grid([xmin, xmax], [ymin, ymax], 0, spacing=0.04) ani = particle_velocity( omega, center, radius, amplitude, grid, frames) ani.save('pulsating_sphere_velocity.gif', dpi=80, writer='imagemagick') # Sound pressure amplitude = 1e-6 # amplitude of the surface displacement impedance_pw = sfs.default.rho0 * sfs.default.c max_pressure = omega * impedance_pw * amplitude grid = sfs.util.xyz_grid([xmin, xmax], [ymin, ymax], 0, spacing=0.005) ani = sound_pressure( omega, center, radius, amplitude, grid, frames, pulsate=True, colorbar=True, vmin=-max_pressure, vmax=max_pressure) ani.save('pulsating_sphere_pressure.gif', dpi=80, writer='imagemagick')
{ "repo_name": "sfstoolbox/sfs-python", "path": "doc/examples/animations_pulsating_sphere.py", "copies": "1", "size": "4376", "license": "mit", "hash": -2020896889671153700, "line_mean": 37.3859649123, "line_max": 79, "alpha_frac": 0.6208866545, "autogenerated": false, "ratio": 3.432156862745098, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9553043517245099, "avg_score": 0, "num_lines": 114 }
"""AnimControlInterval module: contains the AnimControlInterval class""" __all__ = ['AnimControlInterval'] from panda3d.core import * from panda3d.direct import * from direct.directnotify.DirectNotifyGlobal import * from . import Interval import math class AnimControlInterval(Interval.Interval): # create AnimControlInterval DirectNotify category notify = directNotify.newCategory('AnimControlInterval') # Name counter animNum = 1 # Class methods # Plays an animation. The subrange of the animation # to be played may be specified via frames (startFrame up to and # including endFrame) or seconds (startTime up to and including # endTime). If neither is specified, the default is the entire # range of the animation. # this class requires either an AnimControl, or an AnimControlCollection # (in which case, each anim control must be the same length) # The duration may be implicit or explicit. If it is omitted, it # is taken to be endTime - startTime. There's not much point in # specifying otherwise unless you also specify loop=1, which will # loop the animation over its frame range during the duration of # the interval. # Note: if loop == 0 and duration > anim duration then the # animation will play once and then hold its final pose for the # remainder of the interval. # loop = 1 implies a loop within the entire range of animation, # while constrainedLoop = 1 implies a loop within startFrame and # endFrame only. def __init__(self, controls, loop=0, constrainedLoop=0, duration=None, startTime=None, endTime=None, startFrame=None, endFrame=None, playRate=1.0, name=None): # Generate unique id id = 'AnimControl-%d' % (AnimControlInterval.animNum) AnimControlInterval.animNum += 1 # Record class specific variables if(isinstance(controls, AnimControlCollection)): self.controls = controls if(config.GetBool("strict-anim-ival",0)): checkSz = self.controls.getAnim(0).getNumFrames() for i in range(1,self.controls.getNumAnims()): if(checkSz != self.controls.getAnim(i).getNumFrames()): self.notify.error("anim controls don't have the same number of frames!") elif(isinstance(controls, AnimControl)): self.controls = AnimControlCollection() self.controls.storeAnim(controls,"") else: self.notify.error("invalid input control(s) for AnimControlInterval") self.loopAnim = loop self.constrainedLoop = constrainedLoop self.playRate = playRate # If no name specified, use id as name if (name == None): name = id self.frameRate = self.controls.getAnim(0).getFrameRate() * abs(playRate) # Compute start and end frames. if startFrame != None: self.startFrame = startFrame elif startTime != None: self.startFrame = startTime * self.frameRate else: self.startFrame = 0 if endFrame != None: self.endFrame = endFrame elif endTime != None: self.endFrame = endTime * self.frameRate elif duration != None: if startTime == None: startTime = float(self.startFrame) / float(self.frameRate) endTime = startTime + duration self.endFrame = duration * self.frameRate else: # No end frame specified. Choose the maximum of all # of the controls' numbers of frames. numFrames = self.controls.getAnim(0).getNumFrames() self.endFrame = numFrames - 1 # Must we play the animation backwards? We play backwards if # either (or both) of the following is true: the playRate is # negative, or endFrame is before startFrame. self.reverse = (playRate < 0) if self.endFrame < self.startFrame: self.reverse = 1 t = self.endFrame self.endFrame = self.startFrame self.startFrame = t self.numFrames = self.endFrame - self.startFrame + 1 # Compute duration if no duration specified self.implicitDuration = 0 if duration == None: self.implicitDuration = 1 duration = float(self.numFrames) / self.frameRate # Initialize superclass Interval.Interval.__init__(self, name, duration) def getCurrentFrame(self): """Calculate the current frame playing in this interval. returns a float value between startFrame and endFrame, inclusive returns None if there are any problems """ retval = None if not self.isStopped(): framesPlayed = self.numFrames * self.currT retval = self.startFrame + framesPlayed return retval def privStep(self, t): frameCount = t * self.frameRate if self.constrainedLoop: frameCount = frameCount % self.numFrames if self.reverse: absFrame = self.endFrame - frameCount else: absFrame = self.startFrame + frameCount # Calc integer frame number intFrame = int(math.floor(absFrame + 0.0001)) # Pose anim # We use our pre-computed list of animControls for # efficiency's sake, rather than going through the relatively # expensive Actor interface every frame. # Each animControl might have a different number of frames. numFrames = self.controls.getAnim(0).getNumFrames() if self.loopAnim: frame = (intFrame % numFrames) + (absFrame - intFrame) else: frame = max(min(absFrame, numFrames - 1), 0) self.controls.poseAll(frame) self.state = CInterval.SStarted self.currT = t def privFinalize(self): if self.implicitDuration and not self.loopAnim: # As a special case, we ensure we end up posed to the last # frame of the animation if the original duration was # implicit. This is necessary only to guard against # possible roundoff error in computing the final frame # from the duration. We don't do this in the case of a # looping animation, however, because this would introduce # a hitch in the animation when it plays back-to-back with # the next cycle. if self.reverse: self.controls.poseAll(self.startFrame) else: self.controls.poseAll(self.endFrame) else: # Otherwise, the user-specified duration determines which # is our final frame. self.privStep(self.getDuration()) self.state = CInterval.SFinal self.intervalDone()
{ "repo_name": "chandler14362/panda3d", "path": "direct/src/interval/AnimControlInterval.py", "copies": "13", "size": "6933", "license": "bsd-3-clause", "hash": 637528143437308200, "line_mean": 36.8852459016, "line_max": 96, "alpha_frac": 0.6252704457, "autogenerated": false, "ratio": 4.424377791959158, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
"""AnimControlInterval module: contains the AnimControlInterval class""" __all__ = ['AnimControlInterval'] from pandac.PandaModules import * from direct.directnotify.DirectNotifyGlobal import * import Interval import math class AnimControlInterval(Interval.Interval): # create AnimControlInterval DirectNotify category notify = directNotify.newCategory('AnimControlInterval') # Name counter animNum = 1 # Class methods # Plays an animation. The subrange of the animation # to be played may be specified via frames (startFrame up to and # including endFrame) or seconds (startTime up to and including # endTime). If neither is specified, the default is the entire # range of the animation. # this class requires either an AnimControl, or an AnimControlCollection # (in which case, each anim control must be the same length) # The duration may be implicit or explicit. If it is omitted, it # is taken to be endTime - startTime. There's not much point in # specifying otherwise unless you also specify loop=1, which will # loop the animation over its frame range during the duration of # the interval. # Note: if loop == 0 and duration > anim duration then the # animation will play once and then hold its final pose for the # remainder of the interval. # loop = 1 implies a loop within the entire range of animation, # while constrainedLoop = 1 implies a loop within startFrame and # endFrame only. def __init__(self, controls, loop=0, constrainedLoop=0, duration=None, startTime=None, endTime=None, startFrame=None, endFrame=None, playRate=1.0, name=None): # Generate unique id id = 'AnimControl-%d' % (AnimControlInterval.animNum) AnimControlInterval.animNum += 1 # Record class specific variables if(isinstance(controls, AnimControlCollection)): self.controls = controls if(config.GetBool("strict-anim-ival",0)): checkSz = self.controls.getAnim(0).getNumFrames() for i in range(1,self.controls.getNumAnims()): if(checkSz != self.controls.getAnim(i).getNumFrames()): self.notify.error("anim controls don't have the same number of frames!") elif(isinstance(controls, AnimControl)): self.controls = AnimControlCollection() self.controls.storeAnim(controls,"") else: self.notify.error("invalid input control(s) for AnimControlInterval") self.loopAnim = loop self.constrainedLoop = constrainedLoop self.playRate = playRate # If no name specified, use id as name if (name == None): name = id self.frameRate = self.controls.getAnim(0).getFrameRate() * abs(playRate) # Compute start and end frames. if startFrame != None: self.startFrame = startFrame elif startTime != None: self.startFrame = startTime * self.frameRate else: self.startFrame = 0 if endFrame != None: self.endFrame = endFrame elif endTime != None: self.endFrame = endTime * self.frameRate elif duration != None: if startTime == None: startTime = float(self.startFrame) / float(self.frameRate) endTime = startTime + duration self.endFrame = duration * self.frameRate else: # No end frame specified. Choose the maximum of all # of the controls' numbers of frames. numFrames = self.controls.getAnim(0).getNumFrames() self.endFrame = numFrames - 1 # Must we play the animation backwards? We play backwards if # either (or both) of the following is true: the playRate is # negative, or endFrame is before startFrame. self.reverse = (playRate < 0) if self.endFrame < self.startFrame: self.reverse = 1 t = self.endFrame self.endFrame = self.startFrame self.startFrame = t self.numFrames = self.endFrame - self.startFrame + 1 # Compute duration if no duration specified self.implicitDuration = 0 if duration == None: self.implicitDuration = 1 duration = float(self.numFrames) / self.frameRate # Initialize superclass Interval.Interval.__init__(self, name, duration) def getCurrentFrame(self): """Calculate the current frame playing in this interval. returns a float value between startFrame and endFrame, inclusive returns None if there are any problems """ retval = None if not self.isStopped(): framesPlayed = self.numFrames * self.currT retval = self.startFrame + framesPlayed return retval def privStep(self, t): frameCount = t * self.frameRate if self.constrainedLoop: frameCount = frameCount % self.numFrames if self.reverse: absFrame = self.endFrame - frameCount else: absFrame = self.startFrame + frameCount # Calc integer frame number intFrame = int(math.floor(absFrame + 0.0001)) # Pose anim # We use our pre-computed list of animControls for # efficiency's sake, rather than going through the relatively # expensive Actor interface every frame. # Each animControl might have a different number of frames. numFrames = self.controls.getAnim(0).getNumFrames() if self.loopAnim: frame = (intFrame % numFrames) + (absFrame - intFrame) else: frame = max(min(absFrame, numFrames - 1), 0) self.controls.poseAll(frame) self.state = CInterval.SStarted self.currT = t def privFinalize(self): if self.implicitDuration and not self.loopAnim: # As a special case, we ensure we end up posed to the last # frame of the animation if the original duration was # implicit. This is necessary only to guard against # possible roundoff error in computing the final frame # from the duration. We don't do this in the case of a # looping animation, however, because this would introduce # a hitch in the animation when it plays back-to-back with # the next cycle. if self.reverse: self.controls.poseAll(self.startFrame) else: self.controls.poseAll(self.endFrame) else: # Otherwise, the user-specified duration determines which # is our final frame. self.privStep(self.getDuration()) self.state = CInterval.SFinal self.intervalDone()
{ "repo_name": "toontownfunserver/Panda3D-1.9.0", "path": "direct/interval/AnimControlInterval.py", "copies": "3", "size": "6984", "license": "bsd-3-clause", "hash": 7504903468495585000, "line_mean": 37.3736263736, "line_max": 96, "alpha_frac": 0.6178407789, "autogenerated": false, "ratio": 4.485549132947977, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6603389911847977, "avg_score": null, "num_lines": null }
""" An immutable dictionary This has been vendored from [python-frozendict](https://github.com/slezica/python-frozendict) and subsequently modified. """ import collections.abc class frozendict(collections.abc.Mapping): """ An immutable wrapper around dictionaries that implements the complete :py:class:`collections.Mapping` interface. It can be used as a drop-in replacement for dictionaries where immutability is desired. """ dict_cls = dict def __init__(self, *args, **kwargs): self._dict = self.dict_cls(*args, **kwargs) self._hash = None def __getitem__(self, key): return self._dict[key] def __contains__(self, key): return key in self._dict def copy(self, **add_or_replace): return self.__class__(self, **add_or_replace) def __iter__(self): return iter(self._dict) def __len__(self): return len(self._dict) def __repr__(self): return "<%s %r>" % (self.__class__.__name__, self._dict) def __hash__(self): if self._hash is None: h = 0 for key, value in self._dict.items(): h ^= hash((key, value)) self._hash = h return self._hash class FrozenOrderedDict(frozendict): """ A frozendict subclass that maintains key order """ dict_cls = collections.OrderedDict
{ "repo_name": "adamcharnock/lightbus", "path": "lightbus/utilities/frozendict.py", "copies": "1", "size": "1377", "license": "apache-2.0", "hash": 9176339919204213000, "line_mean": 24.9811320755, "line_max": 105, "alpha_frac": 0.602033406, "autogenerated": false, "ratio": 3.979768786127168, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.000561905622652246, "num_lines": 53 }
"""An immutable tree implementation that is backed by the filesystem.""" import datetime import logging import os from . import common class FilesystemTree(common.Tree): """An implementation of Tree backed by the filesystem.""" """Initializer. For safety reasons, only paths beginning with "repos/" are allowed. Args: repo_path: A subpath beginning with repos/ to consider to be the content of the tree. """ def __init__(self, repo_path, namespace='', access_key=None): super(FilesystemTree, self).__init__(namespace, access_key) assert repo_path.startswith('repos/') self.repo_path = repo_path def IsMutable(self): return False def GetFileContents(self, path): path = os.path.join(self.repo_path, path) with open(path) as fh: return fh.read() def GetFileSize(self, path): path = os.path.join(self.repo_path, path) return os.path.getsize(path) def GetFileLastModified(self, path): path = os.path.join(self.repo_path, path) mtime = os.path.getmtime(path) return datetime.datetime.fromtimestamp(mtime) def HasFile(self, path): path = os.path.join(self.repo_path, path) return os.path.isfile(path) def HasDirectory(self, path): path = os.path.join(self.repo_path, path) return os.path.isdir(path) def ListDirectory(self, path=None): result = [] path = path or '' path = os.path.join(self.repo_path, path) if not os.path.isdir(path): raise IOError() for (dirname, dnames, fnames) in os.walk(path): for fname in fnames: full_repo_path = os.path.join(dirname, fname) # Truncate repo_path off the beginning of full_repo_path: # full_repo_path = 'foo/bar/baz' # self.repo_path = 'foo' # item_path = 'bar/baz' item_path = full_repo_path[len(self.repo_path) + 1:] result.append(item_path) return result def GetFiles(self, path): result = [] for file_path in self.ListDirectory(path): result.append((file_path, self.GetFileContents(file_path), self.GetFileLastModified(file_path))) return result
{ "repo_name": "googlearchive/mimic", "path": "__mimic/filesystem_tree.py", "copies": "1", "size": "2167", "license": "apache-2.0", "hash": -2627820200982918000, "line_mean": 27.5131578947, "line_max": 79, "alpha_frac": 0.647900323, "autogenerated": false, "ratio": 3.5524590163934424, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47003593393934423, "avg_score": null, "num_lines": null }
#An implementation of a 2 neuron lpu that instantiates a Leaky and a Morrislecar #into a 1 edge/2node graph. Outputs to a .gefx file. Take from py notebooks. #matrix support import numpy as np np.set_printoptions(threshold = 'nan') #graph support import networkx as nx #input support import h5py def create_lpu_0(): #sets up neurons/networks G = nx.DiGraph() #sets up node connections in graph G.add_nodes_from([0,1]) G.node[0] = { 'name': 'neuron_0', 'selector':'/lpu_0/in/gpot/0', 'model': 'MorrisLecar_a', 'extern': True, 'public': True, 'spiking': False, 'V1': -1.2, 'V2': 18.0, 'V3': 2.0, 'V4': 30.0, 'V_l': -60.0, 'V_ca': 120.0, 'V_k': -84.0, 'G_l': 2.0, 'G_ca': 4.0, 'G_k': 8.0, 'phi': 0.04, 'offset': 0.0, 'initV': -50.0, 'initn': 0.03 } G.node[1] = { 'name': 'neuron_1', 'selector':'/lpu_0/out/gpot/0', 'model': 'MorrisLecar_a', 'extern': False, 'public': True, 'spiking': False, 'V1': -1.2, 'V2': 18.0, 'V3': 2.0, 'V4': 30.0, 'V_l': -60.0, 'V_ca': 120.0, 'V_k': -84.0, 'G_l': 2.0, 'G_ca': 4.0, 'G_k': 8.0, 'phi': 0.04, 'offset': 0.0, 'initV': -50.0, 'initn': 0.03 } #From input to output G.add_edge(0, 1, type='directed', attr_dict={ 'name': G.node[0]['name']+'-'+G.node[1]['name'], 'model' : 'power_gpot_gpot_sig', 'class' : 3, 'slope' : 0.8, 'threshold' : -45, 'power' : 10.0, 'saturation' : 30.0, 'delay' : 1.0, 'reverse' : -0.08, 'conductance' : True}) nx.write_gexf(G, 'simple_lpu_0.gexf.gz') def create_lpu_1(): #sets up neurons/networks G = nx.DiGraph() #sets up node connections in graph G.add_nodes_from([0,1]) G.node[0] = { 'name': 'port_in_gpot_0', 'model': 'port_in_gpot', 'selector': '/lpu_1/in/gpot/0', 'spiking': False, 'public': True, 'extern': False } #MorrisLecar updated G.node[1] = { 'model': 'MorrisLecar_a', 'name': 'neuron_1', 'extern': False, 'public': True, 'spiking': False, 'selector':'/lpu_1/out/gpot/0', 'V1': -1.2, 'V2': 18.0, 'V3': 2.0, 'V4': 30.0, 'V_l': -60.0, 'V_ca': 120.0, 'V_k': -84.0, 'G_l': 2.0, 'G_ca': 4.0, 'G_k': 8.0, 'phi': 0.04, 'offset': 0.0, 'initV': -50.0, 'initn': 0.03 } #From input port to output G.add_edge(0, 1, type='directed', attr_dict={ 'name': G.node[0]['name']+'-'+G.node[1]['name'], 'model' : 'power_gpot_gpot_sig', 'class' : 3, 'slope' : 0.8, 'threshold' : -45, 'power' : 10.0, 'saturation' : 30.0, 'delay' : 1.0, 'reverse' : -0.08, 'conductance' : True}) nx.write_gexf(G, 'simple_lpu_1.gexf.gz') #sets up input file #time step dt = 1e-4 #duration dur = 1.0 #number of datapoints Nt = int(dur/dt) #start and stop of input start = 0.3 stop = 0.6 #the current input I_max = 60 t = np.arange(0, dt*Nt, dt) I = np.zeros((Nt, 1), dtype=np.double) #inputs current at points indicated I[np.logical_and(t > start, t < stop)] = I_max with h5py.File('simple_input.h5', 'w') as f: f.create_dataset('array', (Nt, 1), dtype = np.double, data = I) create_lpu_0() create_lpu_1()
{ "repo_name": "cerrno/neurokernel", "path": "examples/testLPU_ports/data/testLPU.py", "copies": "1", "size": "4073", "license": "bsd-3-clause", "hash": 3733883008296280000, "line_mean": 22.9588235294, "line_max": 81, "alpha_frac": 0.4203289958, "autogenerated": false, "ratio": 2.8886524822695034, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38089814780695036, "avg_score": null, "num_lines": null }
"""An implementation of a binary search tree.""" class Node(object): """Create node to for use in a binary search tree.""" def __init__(self, value=None): """Create node to push into Doubly link list.""" self.value = value self.left_child = None self.right_child = None def _the_children(self): children = [] if self.left_child: children.append(self.left_child) if self.right_child: children.append(self.right_child) return children class BST(object): """The Binary search tree class.""" def __init__(self, iterable=None): """Initialize a binary search tree.""" self.root = None self._size = 0 if iterable and hasattr(iterable, "__iter__"): for i in iterable: self.insert(i) elif iterable: raise TypeError("Can't init with a non iterable.") def insert(self, value): """Insert value into the binary search tree.""" if self.root: self._insert(value, self.root) else: self.root = Node(value) self._size += 1 def _insert(self, value, node): if value == node.value: pass elif value > node.value: if node.right_child: self._insert(value, node.right_child) else: node.right_child = Node(value) self._size += 1 else: if node.left_child: self._insert(value, node.left_child) else: node.left_child = Node(value) self._size += 1 def search(self, value): """Return the node containing val.""" return self._search(value, self.root) def _search(self, value, node): if node.value == value: return node elif value > node.value: if node.right_child: return self._search(value, node.right_child) else: return None else: if node.left_child: return self._search(value, node.left_child) else: return None def size(self): """Return the size of the binary search tree.""" return self._size def depth(self): """Return the depth of the binary search tree.""" return self._depth(self.root) def _depth(self, node): """Helper for depth method.""" if node is None: return 0 else: return max(self._depth(node.left_child), self._depth(node.right_child)) + 1 def contains(self, value): """Return true if the val is contained in the BST, false otherwise.""" return self._contains(value, self.root) def _contains(self, value, node): if node.value == value: return True elif value > node.value: if node.right_child: return self._contains(value, node.right_child) else: return False else: if node.left_child: return self._contains(value, node.left_child) else: return False def balance(self): """Return negative number if left leaning, postive for right leaning, or zero for balanced.""" if self.root: right = self._depth(self.root.right_child) left = self._depth(self.root.left_child) return right - left return 0 def in_order_traversal(self): """Traverse a BST ih order.""" order = [] result = self._traversal(self.root, 'inorder') for val in result: order.append(val.value) return order def pre_order_traversal(self): """Traverse a BST ih order.""" order = [] result = self._traversal(self.root, 'pre') for val in result: order.append(val.value) return order def post_order_traversal(self): """Traverse a BST ih order.""" order = [] result = self._traversal(self.root, 'post') for val in result: order.append(val.value) return order def _traversal(self, node, function): if node is None: return if function == "pre": yield node if node.left_child: for val in self._traversal(node.left_child, function): yield val if function == "inorder": yield node if node.right_child: for val in self._traversal(node.right_child, function): yield val if function == "post": yield node def breadth_first_traversal(self): """Traverse a BST ih order.""" order = [] result = self._breadth_first_traversal(self.root) for val in result: order.append(val.value) return order def _breadth_first_traversal(self, node): if node is None: return node_list = [node] while node_list: current = node_list.pop(0) yield current if current._the_children(): for child in current._the_children(): node_list.append(child) def delete(self, val): """Delete a node while maintaining the integrity of the binary tree.""" node, parent = self.root, None while node is not None and val != node.value: parent = node if val > node.value: node = node.right_child else: node = node.left_child if node is None: return None replacement = None # If node has two children if node.left_child and node.right_child: replacement = self._delete(node) replacement.left_child = node.left_child replacement.right_child = node.right_child # If node has one child or no children elif node.left_child is None: replacement = node.right_child else: replacement = node.left_child # Replace node if node == self.root: self.root = replacement elif parent.left_child == node: parent.left_child = replacement else: parent.right_child = replacement self._size -= 1 return None def _delete(self, node): """Hidden method to remove the node and fix pointers to children.""" successor, parent = node.right_child, node while successor.left_child: parent = successor successor = successor.left_child # If there are no more left children if successor == parent.right_child: parent.right_child = successor.right_child else: parent.left_child = successor.right_child return successor if __name__ == "__main__": """Calculate the runtime for binary searches in the BST.""" import timeit value = [50, 45, 60, 58, 59, 55, 70, 75, 65, 20, 48, 49, 46, 10, 25] balanced = BST(value) unbalanced = BST(sorted(value)) bal = timeit.timeit( stmt="balanced.search(75)", setup="from __main__ import balanced", number=1000 ) * 1000 unbal = timeit.timeit( stmt="unbalanced.search(75)", setup="from __main__ import unbalanced", number=1000 ) * 1000 print("It takes {} microseconds to find 75 in a balanced tree, and {} microseconds to find 75 in an unbalanced tree".format(bal, unbal)) in_o = timeit.timeit( stmt="balanced.in_order_traversal()", setup="from __main__ import balanced", number=1000 ) * 1000 pre = timeit.timeit( stmt="balanced.pre_order_traversal()", setup="from __main__ import balanced", number=1000 ) * 1000 post = timeit.timeit( stmt="balanced.post_order_traversal()", setup="from __main__ import balanced", number=1000 ) * 1000 breadth = timeit.timeit( stmt="balanced.breadth_first_traversal()", setup="from __main__ import balanced", number=1000 ) * 1000 print("It takes {} microseconds to traverse tree in order\n It takes {} microseconds to traverse tree preorder\n It takes {} microseconds to traverse tree postorder\n It takes {} microseconds to traverse tree in breadth first\n ".format(in_o, pre, post, breadth))
{ "repo_name": "rwisecar/data-structures", "path": "src/bst.py", "copies": "1", "size": "8513", "license": "mit", "hash": 3473255483819633700, "line_mean": 30.5296296296, "line_max": 267, "alpha_frac": 0.5496299777, "autogenerated": false, "ratio": 4.235323383084577, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5284953360784577, "avg_score": null, "num_lines": null }
""" An implementation of a deep, recurrent Q-Network following https://gist.github.com/awjuliani/35d2ab3409fc818011b6519f0f1629df#file-deep-recurrent-q-network-ipynb. Adopted to play Pong, or at least to make an honest attempt at doing so, by taking cues from https://gist.github.com/karpathy/a4166c7fe253700972fcbc77e4ea32c5 """ import numpy as np import tensorflow as tf import random from tensorflow.contrib.layers import xavier_initializer as xi from tensorflow.contrib.layers import xavier_initializer_conv2d as xi_2d def process_capture(capture): """ General processing function, can be expanded. """ cropped = capture[35:195] # shape = [80, 80, 3] downsampled = cropped[::2, ::2] flattened = np.reshape(downsampled, [1, -1]) # shape = [1, 80 * 80 * 3] return flattened class ExperienceBuffer(object): """ Collects the agent's experiences to be used in training. """ def __init__(self, buffer_size): self.buffer_size = buffer_size self.buffer = list() def add_experience(self, experience, trace_length, experience_length): """ Adds an experience to the buffer. """ # Delete old experiences if buffer full held_after = len(self.buffer) + 1 if held_after >= self.buffer_size: self.buffer[0: held_after - self.buffer_size] = [] if experience_length >= trace_length: self.buffer.append(experience) def sample_experience(self, batch_size, trace_length): """ Samples experiences from the buffer for training. """ sampled_episodes = random.sample(self.buffer, batch_size) sampled_traces = list() for e in sampled_episodes: starting_point = np.random.randint(0, (e.shape[0] - trace_length) + 1) trace_pick = e[starting_point: starting_point + trace_length] sampled_traces.append(trace_pick) sampled_traces = np.array(sampled_traces) sampled_traces = np.reshape(sampled_traces, [batch_size * trace_length, -1]) return sampled_traces def update_target_graph(actor_tvars, target_tvars, tau): """ Updates the variables of the target graph using the variable values from the actor, following the DDQN update equation. """ op_holder = list() # .assign() is performed on target graph variables with discounted actor graph variable values for idx, variable in enumerate(target_tvars): op_holder.append( target_tvars[idx].assign( (variable.value() * tau) + ((1 - tau) * actor_tvars[idx].value()) ) ) return op_holder def perform_update(op_holder, sess): """ Executes the updates on the target network. """ for op in op_holder: sess.run(op) class MentorAgent(object): """ Agent network designed to learn via deep Q-learning. Both actor and mentor are instances of the same network class. """ def __init__(self, hidden_size, rnn_cell, filter_dims, filter_nums, strides, all_scope, action_num, learning_rate): self.hidden_size = hidden_size self.rnn_cell = rnn_cell self.filter_dims = filter_dims self.filter_nums = filter_nums self.strides = strides self.all_scope = all_scope self.action_num = action_num self.learning_rate = learning_rate self.dtype = tf.float32 # Define placeholders for input, training parameters, and training values self.scalar_input = tf.placeholder(shape=[None, 80 * 80 * 3], dtype=self.dtype, name='scalar_input') self.trace_length = tf.placeholder(dtype=tf.int32, name='train_duration') self.batch_size = tf.placeholder(dtype=tf.int32, name='batch_size') # Both below have shape=[batch_size * trace_len] self.target_q_holder = tf.placeholder(shape=[None], dtype=self.dtype, name='target_Q_values') self.action_holder = tf.placeholder(shape=[None], dtype=tf.int32, name='actions_taken') # Reshape the scalar input into image-shape cnn_input = tf.reshape(self.scalar_input, shape=[-1, 80, 80, 3]) # Filter output calculation: W1 = (W−F+2P)/S+1 72/4 # Define ConvNet layers for screen image analysis with tf.variable_scope(self.all_scope + '_cnn_1'): w_1 = tf.get_variable(name='weight', shape=[*self.filter_dims[0], 3, self.filter_nums[0]], initializer=xi_2d()) b_1 = tf.get_variable(name='bias', shape=[self.filter_nums[0]], initializer=tf.constant_initializer(0.1)) c_1 = tf.nn.conv2d(cnn_input, w_1, strides=[1, *self.strides[0], 1], padding='VALID', name='convolution') o_1 = tf.nn.relu(tf.nn.bias_add(c_1, b_1), name='output') # shape=[19, 19, 32] with tf.variable_scope(self.all_scope + '_cnn_2'): w_2 = tf.get_variable(name='weight', shape=[*self.filter_dims[1], self.filter_nums[0], self.filter_nums[1]], initializer=xi_2d()) b_2 = tf.get_variable(name='bias', shape=[self.filter_nums[1]], initializer=tf.constant_initializer(0.1)) c_2 = tf.nn.conv2d(o_1, w_2, strides=[1, *self.strides[1], 1], padding='VALID', name='convolution') o_2 = tf.nn.relu(tf.nn.bias_add(c_2, b_2), name='output') # shape=[8, 8, 64] with tf.variable_scope(self.all_scope + '_cnn_3'): w_3 = tf.get_variable(name='weight', shape=[*self.filter_dims[2], self.filter_nums[1], self.filter_nums[2]], initializer=xi_2d()) b_3 = tf.get_variable(name='bias', shape=[self.filter_nums[2]], initializer=tf.constant_initializer(0.1)) c_3 = tf.nn.conv2d(o_2, w_3, strides=[1, *self.strides[2], 1], padding='VALID', name='convolution') o_3 = tf.nn.relu(tf.nn.bias_add(c_3, b_3), name='output') # shape=[7, 7, 64] with tf.variable_scope(self.all_scope + '_cnn_out'): w_4 = tf.get_variable(name='weight', shape=[*self.filter_dims[3], self.filter_nums[2], self.filter_nums[3]], initializer=xi_2d()) b_4 = tf.get_variable(name='bias', shape=[self.filter_nums[3]], initializer=tf.constant_initializer(0.1)) c_4 = tf.nn.conv2d(o_3, w_4, strides=[1, *self.strides[3], 1], padding='VALID', name='convolution') cnn_out = tf.nn.relu(tf.nn.bias_add(c_4, b_4), name='output') # shape=[1, 1, 512] # Reshape ConvNet output to [batch_size, trace_len, hidden_size] to be fed into the RNN cnn_flat = tf.reshape(cnn_out, shape=[-1]) rnn_input = tf.reshape(cnn_flat, [self.batch_size, self.trace_length, self.hidden_size], name='RNN_input') # Initialize RNN and feed the input self.state_in = rnn_cell.zero_state(self.batch_size, tf.float32) self.rnn_outputs, self.final_state = tf.nn.dynamic_rnn(cell=self.rnn_cell, inputs=rnn_input, initial_state=self.state_in, scope=self.all_scope + '_rnn', dtype=self.dtype) # Concatenate RNN time steps rnn_2d = tf.reshape(self.rnn_outputs, shape=[-1, self.hidden_size]) # [batch_size * trace_len, hidden_size] # Split RNN output into advantage and value streams which are to guide the agent's policy with tf.variable_scope(self.all_scope + '_advantage_and_value'): a_w = tf.get_variable(name='advantage_weight', shape=[self.hidden_size / 2, self.action_num], dtype=self.dtype, initializer=xi()) v_w = tf.get_variable(name='value_weight', shape=[self.hidden_size / 2, 1], dtype=self.dtype, initializer=xi()) a_stream, v_stream = tf.split(rnn_2d, 2, axis=1) self.advantage = tf.matmul(a_stream, a_w, name='advantage') self.value = tf.matmul(v_stream, v_w, name='value') self.improve_vision = tf.gradients(self.advantage, cnn_input) # Predict the next action self.q_out = tf.add(self.value, tf.subtract( self.advantage, tf.reduce_mean(self.advantage, axis=1, keep_dims=True)), name='predicted_action_distribution') # shape=[batch_size * trace_len, num_actions] self.prediction = tf.argmax(self.q_out, axis=1, name='predicted_action') with tf.variable_scope(self.all_scope + 'loss'): # Obtain loss by measuring the difference between the prediction and the target Q-value actions_one_hot = tf.one_hot(self.action_holder, self.action_num, dtype=self.dtype) self.predicted_q = tf.reduce_sum(tf.multiply(self.q_out, actions_one_hot), axis=1, name='predicted_Q_values') # predicted_q and l2_loss have shape=[batch_size * trace_len] -> calculated per step self.l2_loss = tf.square(tf.subtract(self.predicted_q, self.target_q_holder), name='l2_loss') # Mask first half of the losses to only keep the 'important' values mask_drop = tf.zeros(shape=[self.batch_size, tf.cast(self.trace_length / 2, dtype=tf.int32)]) mask_keep = tf.ones(shape=[self.batch_size, tf.cast(self.trace_length / 2, dtype=tf.int32)]) mask = tf.concat([mask_drop, mask_keep], axis=1) # shape=[batch_size, train_duration] flat_mask = tf.reshape(mask, [-1]) self.loss = tf.reduce_mean(tf.multiply(self.l2_loss, flat_mask), name='total_loss') optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate) self.update_model = optimizer.minimize(self.loss)
{ "repo_name": "demelin/learning_reinforcement_learning", "path": "recurrent_deep_q_network/q_network.py", "copies": "1", "size": "9714", "license": "mit", "hash": 4361640127983002600, "line_mean": 55.1387283237, "line_max": 120, "alpha_frac": 0.6162479407, "autogenerated": false, "ratio": 3.405329593267882, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45215775339678815, "avg_score": null, "num_lines": null }
"""An implementation of a doubly linked list in Python.""" class Node(): """Instantiate a node.""" def __init__(self, value=None, nxt=None, previous=None): """.""" self.value = value self.next = nxt self.previous = previous class DbLinkedList(): """Instantiate a doubly linked list.""" def __init__(self, value=None): """.""" self.head = None self.tail = None self.length = 0 if value: self.push(value) def push(self, value=None): """Push value to the head of dll.""" new_node = Node(value, nxt=self.head) if self.length < 1: self.tail = new_node else: self.head.previous = new_node self.head = new_node self.length += 1 def append(self, value): """Append value to the tail of dll.""" new_node = Node(value, None, self.tail) if self.length < 1: self.head = new_node else: self.tail.next = new_node self.tail = new_node self.length += 1 def pop(self): """Pop first value off of the head of dll.""" if self.head: returned_value = self.head.value self.head = self.head.next self.head.previous = None self.length -= 1 return returned_value raise ValueError("Cannot pop from an empty list") def shift(self): """Remove and return the last value of the dll.""" if self.head: returned_value = self.tail.value self.tail = self.tail.previous self.tail.next = None self.length -= 1 return returned_value raise ValueError("Cannot shift from an empty list") def remove(self, value): """Remove the value from the dll.""" curr_node = self.head if not self.length: raise ValueError("Cannot remove from an empty list") else: if curr_node.value == value: self.pop() else: while curr_node is not None: if curr_node.value == value: curr_node.previous.next = curr_node.next curr_node.next.previous = curr_node.previous print("{} was removed".format(value)) return else: curr_node = curr_node.next raise ValueError("{} not in the list".format(value))
{ "repo_name": "ellezv/data_structures", "path": "src/dll.py", "copies": "1", "size": "2544", "license": "mit", "hash": 3400972026953004500, "line_mean": 30.0243902439, "line_max": 68, "alpha_frac": 0.5125786164, "autogenerated": false, "ratio": 4.393782383419689, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5406360999819688, "avg_score": null, "num_lines": null }
## An implementation of an additivelly homomorphic ## ECC El-Gamal scheme, used in Privex. from petlib.ec import EcGroup import pytest def params_gen(nid=713): """Generates the AHEG for an EC group nid""" G = EcGroup(nid) g = G.generator() o = G.order() return (G, g, o) def key_gen(params): """Generates a fresh key pair""" _, g, o = params priv = o.random() pub = priv * g return (pub, priv) def enc(params, pub, counter): """Encrypts the values of a small counter""" assert -2**8 < counter < 2**8 G, g, o = params k = o.random() a = k * g b = k * pub + counter * g return (a, b) def enc_side(params, pub, counter): """Encrypts the values of a small counter""" assert -2**8 < counter < 2**8 G, g, o = params k = o.random() a = k * g b = k * pub + counter * g return (a, b, k) def add(c1, c2): """Add two encrypted counters""" a1, b1 = c1 a2, b2 = c2 return (a1 + a2, b1 + b2) def mul(c1, val): """Multiplies an encrypted counter by a public value""" a1, b1 = c1 return (val*a1, val*b1) def randomize(params, pub, c1): """Rerandomize an encrypted counter""" zero = enc(params, pub, 0) return add(c1, zero) def make_table(params): """Make a decryption table""" _, g, o = params table = {} for i in range(-1000, 1000): table[i * g] = i return table def dec(params, table, priv, c1): """Decrypt an encrypted counter""" _, g, o = params a, b = c1 plain = b + (-priv * a) return table[plain] def test_AHEG(): params = params_gen() (pub, priv) = key_gen(params) table = make_table(params) # Check encryption and decryption one = enc(params, pub, 1) assert dec(params, table, priv, one) == 1 # Check addition tmp = add(one, one) two = randomize(params, pub, tmp) assert dec(params, table, priv, two) == 2 # Check multiplication tmp1 = mul(two, 2) four = randomize(params, pub, tmp1) assert dec(params, table, priv, four) == 4
{ "repo_name": "gdanezis/petlib", "path": "examples/AHEG.py", "copies": "1", "size": "2079", "license": "bsd-2-clause", "hash": -1868945703331276800, "line_mean": 22.1, "line_max": 59, "alpha_frac": 0.5738335738, "autogenerated": false, "ratio": 3.0174165457184325, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40912501195184325, "avg_score": null, "num_lines": null }
'''An implementation of an agent following the simple SIR model @author: Joe Schaul <joe.schaul@gmail.com> ''' from ComplexNetworkSim import NetworkAgent, Sim #states: SUSCEPTIBLE = 0 INFECTED = 1 RECOVERED = 2 class SIRSimple(NetworkAgent): """ an implementation of an agent following the simple SIR model """ INFECTION_PROB = 0.5 TIME = 1.0 def __init__(self, state, initialiser): NetworkAgent.__init__(self, state, initialiser) self.infection_probability = self.globalSharedParameters['infection_rate'] self.infection_end = eval(self.globalSharedParameters['inf_dur']) def Run(self): while True: if self.state == SUSCEPTIBLE: self.maybeBecomeInfected() yield Sim.hold, self, NetworkAgent.TIMESTEP_DEFAULT #wait a step elif self.state == INFECTED: yield Sim.hold, self, self.infection_end #wait end of infection self.state = RECOVERED yield Sim.passivate, self #remove agent from event queue def maybeBecomeInfected(self): infected_neighbours = self.getNeighbouringAgentsIter(state=INFECTED) for neighbour in infected_neighbours: if SIRSimple.r.random() < self.infection_probability: self.state = INFECTED break
{ "repo_name": "jschaul/ComplexNetworkSim", "path": "examples/SIR_model/agent_SIR.py", "copies": "1", "size": "1542", "license": "bsd-2-clause", "hash": 2760000590297408000, "line_mean": 29.5102040816, "line_max": 85, "alpha_frac": 0.5648508431, "autogenerated": false, "ratio": 4.057894736842106, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9946286697140752, "avg_score": 0.035291776560270924, "num_lines": 49 }
'''An implementation of a neural network with backpropagation and momentum in python. Backpropagation is a method of training neural networks by working backwards from the output of the training data to the input. In this implementation, a sigmoid function is used as the transfer function to compute outputs of successive layers. For testing, a simple XOR truth table is used train the network to behave as the logic gate. Generally, I found acceptable values emerge after around 10000 iterations or so. Ideally, different functions would be used to model consecutive layers of the neural network.''' import numpy class BackProp: numLayers = 0 _weights = [] shape = None def __init__ (self,size): self.numLayers = len(size) - 1 #decrement to remove input layer self.shape = size self._inputLayers = [] self._outputLayers = [] self._previousDelta = [] for(l1,l2) in zip(size[:-1],size[1:]): self._weights.append(numpy.random.normal(scale=0.1, size = (l2, l1+1))) self._previousDelta.append(numpy.zeros((l2,l1+1))) def run(self,input): inCases = input.shape[0] self._inputLayers = [] self._outputLayers = [] #for input layer for index in range(self.numLayers): if index == 0: layerInput = self._weights[0].dot(numpy.vstack([input.T,numpy.ones([1,inCases])])) else: layerInput = self._weights[index].dot(numpy.vstack([self._outputLayers[-1],numpy.ones([1,inCases])])) self._inputLayers.append(layerInput) self._outputLayers.append(self.SigmoidTransfer(layerInput)) return self._outputLayers[-1].T def TrainEpoch(self, input, target, rate = 0.2, momentum = 0.5): delta = [] lnCases = input.shape[0] self.run(input) #compute deltas for backpropagation for index in reversed(range(self.numLayers)): #compare output of current layer to outpt values if index == self.numLayers - 1: outputDelta = self._outputLayers[index] - target.T error = numpy.sum(outputDelta**2) delta.append(outputDelta * self.SigmoidTransfer(self._inputLayers[index],True)) #^^append difference between layer output and target else: #or compare to succesive layers delta_pullback = self._weights[index + 1].T.dot(delta[-1]) delta.append(delta_pullback[:-1,:] * self.SigmoidTransfer(self._inputLayers[index],True)) for index in range(self.numLayers): delta_index = self.numLayers - 1 - index if index == 0: iterlayerOutput = numpy.vstack([input.T, numpy.ones([1, lnCases])]) else: iterlayerOutput = numpy.vstack([self._outputLayers[index - 1],numpy.ones([1,self._outputLayers[index - 1].shape[1]])]) currentDelta = numpy.sum(iterlayerOutput[None,:,:].transpose(2,0,1) * delta[delta_index][None,:,:].transpose(2,1,0), axis = 0) actualDelta = rate*currentDelta + momentum * self._previousDelta[index] self._weights[index] -= actualDelta self._previousDelta[index] = actualDelta return error def SigmoidTransfer(self,x, derivative = False): if not derivative: return 1/(1+numpy.exp(-x)) else: out = self.SigmoidTransfer(x) return out*(1-out) backpObj = BackProp((2,2,1)) #Test -- training to behave as a XOR gate xortraininp = numpy.array([[0,0], [1,1], [0,1], [1,0]]) xortrainout = numpy.array([[0.05], [0.05], [0.95], [0.95]]) #note:Sigmoid function -- no precise digital outputs. maxinp = 100000 inperror = 1e-4 print("errors for 10000n iterations:") for i in range(maxinp +1): err = backpObj.TrainEpoch(xortraininp,xortrainout) if i%10000 == 0: print (err) if err<inperror: break op = backpObj.run(xortraininp) print ("output: {0}".format(op) )
{ "repo_name": "fawazn/PyNeural", "path": "BackProp.py", "copies": "1", "size": "3862", "license": "mit", "hash": 4880635344595064000, "line_mean": 42.3908045977, "line_max": 135, "alpha_frac": 0.6532884516, "autogenerated": false, "ratio": 3.552897884084637, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9567759674852825, "avg_score": 0.027685332166362417, "num_lines": 87 }
"""An implementation of a neural network without classes (just a module) """ import numpy import scipy.optimize import itertools def create_training_dict(X, y): """Take a set of input features and their labels and package them along with some useful quantities into a dictionary. This could be a training, validation, or test set. Args: X (numpy.ndarray): 2-D array of feature vectors (1 per row) y (numpy.ndarray): labels for each feature vector Returns: A dictionary containing ... X (numpy.ndarray): 2-D array of feature vectors (1 per row) y (numpy.ndarray): labels for each feature vector m (int): number of feature vectors (i.e. training examples) n (int): number of features per vector n_cat (int): number of categories (i.e. unique values in y) y1hot (numpy.ndarray) 2-D array of one-hot vectors (1 per row) for example if n_cat = 5, the label 3 -> [0, 0, 0, 1, 0] """ m, n = X.shape n_cat = len(numpy.unique(y)) y1hot = numpy.identity(n_cat)[y] Xmean = X.mean() Xstd = X.std() Xnorm = (X - Xmean) / Xstd return {'Xnorm': Xnorm, 'Xmean': Xmean, 'Xstd': Xstd, 'y': y, 'm': m, 'n': n, 'n_cat': n_cat, 'y1hot': y1hot} def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2,s3), ..." a, b = itertools.tee(iterable) next(b, None) return itertools.izip(a, b) def sigmoid(z): """Return element-wise sigmoid Args: z (numpy.ndarray): argument for sigmoid function Returns: g (numpy.ndarray): sigmoid function evaluated element-wise """ return 1.0 / (1.0 + numpy.exp(-z)) def sigmoid_gradient(z): """Return element-wise sigmoid gradient evaluated at z Args: z (numpy.ndarray): argument for sigmoid function Returns: g (numpy.ndarray): sigmoid function evaluated element-wise """ return sigmoid(z) * (1.0 - sigmoid(z)) def flatten_arrays(arrays): """Turn a list of 2-D arrays into a single 1-D array. Args: arrays (``list`` of numpy.ndarray): a list of 2-D arrays Returns: (numpy.ndarray): a flattened 1-D array """ return numpy.concatenate([a.flatten() for a in arrays]) def unflatten_array(flat_array, array_shapes): """Turn a single 1-D array into a list of 2-D arrays. Args: flat_array (numpy.ndarray): a flattened 1-D array array_shapes (``list`` of ``tuple``): 2-D array shapes Returns: arrays (``list`` of numpy.ndarray): a list of 2-D arrays """ i = 0 weight_arrays = [] for shape in array_shapes: j = i + shape[0] * shape[1] weight_arrays.append(flat_array[i:j].reshape(shape)) i = j return weight_arrays def initialize_random_weights(layer_sizes): """Initialize weight arrays to random values. We use the normalized initialization of Glorot and Bengio (2010). https://scholar.google.com/scholar?cluster=17889055433985220047&hl=en&as_sdt=0,22 """ weights = [] for si, sj in pairwise(layer_sizes): b = numpy.sqrt(6.0 / (si + sj)) weights.append( numpy.random.uniform(low=-b, high=b, size=(sj, si+1)) ) return weights def minimize(initial_weights, X, y1hot, lam=0.0, method='TNC', jac=True, tol=1.0e-3, options={'disp': True, 'maxiter': 2000}): """Calculate values of weights that minimize the cost function. Args: initial_weights (``list`` of numpy.ndarray): weights between each layer X (numpy.ndarray): 2-D array of feature vectors (1 per row) y1hot (numpy.ndarray): 2-D array of one-hot vectors (1 per row) lam (``float``): regularization parameter method (``str``): minimization method (see scipy.optimize.minimize docs) jac (``bool`` or ``callable``): gradient provided? (see scipy.optimize.minimize docs) tol (``float``): stopping criterion (see scipy.optimize.minimize docs) options (``dict``): method specific (see scipy.optimize.minimize docs) Returns: res (``OptimizeResult``): (see scipy.optimize.minimize docs) """ weight_shapes = [w.shape for w in initial_weights] flat_weights = flatten_arrays(initial_weights) res = scipy.optimize.minimize( compute_cost_and_grad, flat_weights, args=(X, y1hot, weight_shapes, lam), method=method, jac=jac, tol=tol, options=options, ) return res def compute_cost_and_grad( weights_flat, X, y1hot, weight_shapes, lam=0.0, cost_only=False): """Calculate cost function and its gradient with respect to weights. Args: weights_flat (numpy.ndarray): a flattened 1-D weight array X (numpy.ndarray): 2-D array of feature vectors (1 per row) y1hot (numpy.ndarray) 2-D array of one-hot vectors (1 per row) weight_shapes (``list`` of ``tuple``): 2-D array shapes lam (``float``): regularization parameter cost_only (``boolean``): if True return cost without gradient Returns: J (``float``): Cost with current weights weights_grad_flat (numpy.ndarray): d_J/d_weight """ # package flat weights into a list of arrays m = X.shape[0] weights = unflatten_array(weights_flat, weight_shapes) # feed forward aa, zz = feed_forward(X, weights) # calculate raw cost h = aa[-1] J = -( numpy.sum(y1hot * numpy.log(h)) + numpy.sum((1.0 - y1hot) * numpy.log(1.0 - h)) ) / m # add regularization for weight in weights: J += lam * numpy.sum(weight[:, 1:] * weight[:, 1:]) * 0.5 / m if cost_only: return J # gradient - back prop weights_grad_flat = flatten_arrays( back_propogation(weights, aa, zz, y1hot, lam=lam)) return J, weights_grad_flat def feed_forward(X, weights): """Perform a feed forward step. Note that the z variables will not have the bias columns included and that all but the final a variables will have the bias column included. Args: X (numpy.ndarray): 2-D array of feature vectors (1 per row) weights (``list`` of numpy.ndarray): weights between each layer Returns: aa (``list`` of numpy.ndarray): activation of nodes for each layer. The last item in the list is the hypothesis. zz (``list`` of numpy.ndarray): input into nodes for each layer. """ aa = [] zz = [] zz.append(None) # this is z1 (i.e. there is no z1) ai = X.copy() ai = numpy.c_[numpy.ones(ai.shape[0]), ai] # a1 is X + bias nodes aa.append(ai) for weight in weights: zi = ai.dot(weight.T) zz.append(zi) ai = sigmoid(zi) ai = numpy.c_[numpy.ones(ai.shape[0]), ai] # add bias column aa.append(ai) # remove bias column from last aa layer aa[-1] = aa[-1][:, 1:] return aa, zz def back_propogation(weights, aa, zz, y1hot, lam=0.0): """Perform a back propogation step Args: weights (``list`` of numpy.ndarray): weights between each layer aa (``list`` of numpy.ndarray): activation of nodes for each layer. The last item in the list is the hypothesis. zz (``list`` of numpy.ndarray): input into nodes for each layer. y1hot (numpy.ndarray) 2-D array of one-hot vectors (1 per row) lam (``float``): regularization parameter Returns: weights_grad (``list`` of numpy.ndarray): d_J/d_weight """ weights_grad = [] m = y1hot.shape[0] n_layers = len(weights) + 1 di_plus_1 = aa[-1] - y1hot i = n_layers - 2 while i > 0: ones_col = numpy.ones(zz[i].shape[0]) di = ( di_plus_1.dot(weights[i]) * sigmoid_gradient(numpy.c_[ones_col, zz[i]]) ) di = di[:, 1:] weights_grad.append(di_plus_1.T.dot(aa[i])) i -= 1 di_plus_1 = di.copy() weights_grad.append(di.T.dot(aa[0])) # we built it backwards weights_grad.reverse() # normalize by m weights_grad = [wg/m for wg in weights_grad] # add regularization (skip first columns) for i in range(n_layers-1): weights_grad[i][:, 1:] += lam/m * weights[i][:, 1:] return weights_grad
{ "repo_name": "galtay/neural_learner", "path": "nn.py", "copies": "1", "size": "8224", "license": "mit", "hash": 5919210168104909000, "line_mean": 29.3468634686, "line_max": 85, "alpha_frac": 0.6101653696, "autogenerated": false, "ratio": 3.4773784355179704, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45875438051179707, "avg_score": null, "num_lines": null }
"""An implementation of aNMM Model.""" import keras from keras.activations import softmax from keras.initializers import RandomUniform from matchzoo.engine.base_model import BaseModel from matchzoo.engine.param import Param from matchzoo.engine.param_table import ParamTable from matchzoo.engine import hyper_spaces class ANMM(BaseModel): """ ANMM Model. Examples: >>> model = ANMM() >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build() """ @classmethod def get_default_params(cls) -> ParamTable: """:return: model default parameters.""" params = super().get_default_params(with_embedding=True) params.add(Param( name='dropout_rate', value=0.1, desc="The dropout rate.", hyper_space=hyper_spaces.quniform(0, 1, 0.05) )) params.add(Param( name='num_layers', value=2, desc="Number of hidden layers in the MLP " "layer." )) params.add(Param( name='hidden_sizes', value=[30, 30], desc="Number of hidden size for each hidden" " layer" )) return params def build(self): """ Build model structure. aNMM model based on bin weighting and query term attentions """ # query is [batch_size, left_text_len] # doc is [batch_size, right_text_len, bin_num] query, doc = self._make_inputs() embedding = self._make_embedding_layer() q_embed = embedding(query) q_attention = keras.layers.Dense( 1, kernel_initializer=RandomUniform(), use_bias=False)(q_embed) q_text_len = self._params['input_shapes'][0][0] q_attention = keras.layers.Lambda( lambda x: softmax(x, axis=1), output_shape=(q_text_len,) )(q_attention) d_bin = keras.layers.Dropout( rate=self._params['dropout_rate'])(doc) for layer_id in range(self._params['num_layers'] - 1): d_bin = keras.layers.Dense( self._params['hidden_sizes'][layer_id], kernel_initializer=RandomUniform())(d_bin) d_bin = keras.layers.Activation('tanh')(d_bin) d_bin = keras.layers.Dense( self._params['hidden_sizes'][self._params['num_layers'] - 1])( d_bin) d_bin = keras.layers.Reshape((q_text_len,))(d_bin) q_attention = keras.layers.Reshape((q_text_len,))(q_attention) score = keras.layers.Dot(axes=[1, 1])([d_bin, q_attention]) x_out = self._make_output_layer()(score) self._backend = keras.Model(inputs=[query, doc], outputs=x_out)
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/models/anmm.py", "copies": "1", "size": "2720", "license": "apache-2.0", "hash": -7138631072933529000, "line_mean": 33.4303797468, "line_max": 75, "alpha_frac": 0.5794117647, "autogenerated": false, "ratio": 3.7414030261348006, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4820814790834801, "avg_score": null, "num_lines": null }
""" An implementation of an occupancy field that you can use to implement your particle filter's laser_update function """ import rospy from std_msgs.msg import Header, String from sensor_msgs.msg import LaserScan from geometry_msgs.msg import PoseStamped, PoseWithCovarianceStamped, PoseArray, Pose, Point, Quaternion from nav_msgs.srv import GetMap from copy import deepcopy import tf from tf import TransformListener from tf import TransformBroadcaster from tf.transformations import euler_from_quaternion, rotation_matrix, quaternion_from_matrix from random import gauss import math import time import numpy as np from numpy.random import random_sample from sklearn.neighbors import NearestNeighbors class OccupancyField(object): """ Stores an occupancy field for an input map. An occupancy field returns the distance to the closest obstacle for any coordinate in the map Attributes: map: the map to localize against (nav_msgs/OccupancyGrid) closest_occ: the distance for each entry in the OccupancyGrid to the closest obstacle """ def __init__(self, map): self.map = map # save this for later # build up a numpy array of the coordinates of each grid cell in the map X = np.zeros((self.map.info.width*self.map.info.height,2)) # while we're at it let's count the number of occupied cells total_occupied = 0 curr = 0 for i in range(self.map.info.width): for j in range(self.map.info.height): # occupancy grids are stored in row major order, if you go through this right, you might be able to use curr ind = i + j*self.map.info.width if self.map.data[ind] > 0: total_occupied += 1 X[curr,0] = float(i) X[curr,1] = float(j) curr += 1 # build up a numpy array of the coordinates of each occupied grid cell in the map O = np.zeros((total_occupied,2)) curr = 0 for i in range(self.map.info.width): for j in range(self.map.info.height): # occupancy grids are stored in row major order, if you go through this right, you might be able to use curr ind = i + j*self.map.info.width if self.map.data[ind] > 0: O[curr,0] = float(i) O[curr,1] = float(j) curr += 1 # use super fast scikit learn nearest neighbor algorithm nbrs = NearestNeighbors(n_neighbors=1,algorithm="ball_tree").fit(O) distances, indices = nbrs.kneighbors(X) self.closest_occ = {} curr = 0 for i in range(self.map.info.width): for j in range(self.map.info.height): ind = i + j*self.map.info.width self.closest_occ[ind] = distances[curr][0]*self.map.info.resolution curr += 1 def get_closest_obstacle_distance(self,x,y): """ Compute the closest obstacle to the specified (x,y) coordinate in the map. If the (x,y) coordinate is out of the map boundaries, nan will be returned. """ x_coord = int((x - self.map.info.origin.position.x)/self.map.info.resolution) y_coord = int((y - self.map.info.origin.position.y)/self.map.info.resolution) # check if we are in bounds if x_coord > self.map.info.width or x_coord < 0: return float('nan') if y_coord > self.map.info.height or y_coord < 0: return float('nan') ind = x_coord + y_coord*self.map.info.width if ind >= self.map.info.width*self.map.info.height or ind < 0: return float('nan') return self.closest_occ[ind]
{ "repo_name": "DakotaNelson/robo-games", "path": "ar_locating/scripts/occupancy_field.py", "copies": "1", "size": "3761", "license": "mit", "hash": 4873690552125065000, "line_mean": 40.8, "line_max": 124, "alpha_frac": 0.6240361606, "autogenerated": false, "ratio": 3.764764764764765, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48888009253647646, "avg_score": null, "num_lines": null }
"""An implementation of a priority queue using a dictionary in Python.""" class PriorityQueue(object): """That's it.""" def __init__(self): """Initialize a priority queue with default value as None.""" self._container = {} def insert(self, value, priority=0): """Insert tuple in priority queue.""" if priority > 0: raise ValueError('Priorities can only be negative, David.') self._container.setdefault(priority, []).append(value) def pop(self): """Remove and return the highest priority value from the queue.""" try: highest_priority = min([priority for priority in self._container]) highest_priority_value = self._container[highest_priority].pop(0) if not len(self._container[highest_priority]): self._container.pop(highest_priority) return highest_priority_value except ValueError: raise IndexError('Cannot pop from an empty priority queue!') def peek(self): """Return the highest priority value from the queue without removing it.""" try: highest_priority = min([priority for priority in self._container]) return self._container[highest_priority][0] except ValueError: raise IndexError('There is nothing to see there, David.')
{ "repo_name": "ellezv/data_structures", "path": "src/priority_queue.py", "copies": "1", "size": "1368", "license": "mit", "hash": -6587816417267415000, "line_mean": 39.2352941176, "line_max": 83, "alpha_frac": 0.6235380117, "autogenerated": false, "ratio": 4.920863309352518, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00035014005602240897, "num_lines": 34 }
"""An implementation of a queue in Python.""" from dll import DbLinkedList class Queue(object): """Create a queue which inherits from Double-linked List.""" def __init__(self, value=None, next=None, previous=None): """Initialize new queue from dll using composition.""" self._dblinkedlist = DbLinkedList() if value: self._dblinkedlist.append(value) self.head = self._dblinkedlist.head self.tail = self._dblinkedlist.tail self.length = self._dblinkedlist.length def enqueue(self, value): """Add value to the tail of the queue.""" self._dblinkedlist.append(value) self.head = self._dblinkedlist.head self.tail = self._dblinkedlist.tail self.length = self._dblinkedlist.length def dequeue(self): """Remove the first item in the queue and return value.""" try: dequeued_value = self._dblinkedlist.pop() self.head = self._dblinkedlist.head self.tail = self._dblinkedlist.tail self.length = self._dblinkedlist.length return dequeued_value except ValueError: raise ValueError("Cannot dequeue from an empty queue") def peek(self): """Return next value in the queue without dequeuing.""" try: return self._dblinkedlist.head.next.value except AttributeError: return None def size(self): """Return the size of the queue.""" return self.length
{ "repo_name": "ellezv/data_structures", "path": "src/queue.py", "copies": "1", "size": "1524", "license": "mit", "hash": 2904189733749178400, "line_mean": 32.8666666667, "line_max": 66, "alpha_frac": 0.6154855643, "autogenerated": false, "ratio": 4.39193083573487, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.550741640003487, "avg_score": null, "num_lines": null }
"""An implementation of ArcII Model.""" import typing import keras import matchzoo from matchzoo.engine.base_model import BaseModel from matchzoo.engine.param import Param from matchzoo.engine.param_table import ParamTable from matchzoo.engine import hyper_spaces class ArcII(BaseModel): """ ArcII Model. Examples: >>> model = ArcII() >>> model.params['embedding_output_dim'] = 300 >>> model.params['num_blocks'] = 2 >>> model.params['kernel_1d_count'] = 32 >>> model.params['kernel_1d_size'] = 3 >>> model.params['kernel_2d_count'] = [16, 32] >>> model.params['kernel_2d_size'] = [[3, 3], [3, 3]] >>> model.params['pool_2d_size'] = [[2, 2], [2, 2]] >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build() """ @classmethod def get_default_params(cls) -> ParamTable: """:return: model default parameters.""" params = super().get_default_params(with_embedding=True) params['optimizer'] = 'adam' opt_space = hyper_spaces.choice(['adam', 'rmsprop', 'adagrad']) params.get('optimizer').hyper_space = opt_space params.add(Param(name='num_blocks', value=1, desc="Number of 2D convolution blocks.")) params.add(Param(name='kernel_1d_count', value=32, desc="Kernel count of 1D convolution layer.")) params.add(Param(name='kernel_1d_size', value=3, desc="Kernel size of 1D convolution layer.")) params.add(Param(name='kernel_2d_count', value=[32], desc="Kernel count of 2D convolution layer in" "each block")) params.add(Param(name='kernel_2d_size', value=[[3, 3]], desc="Kernel size of 2D convolution layer in" " each block.")) params.add(Param(name='activation', value='relu', desc="Activation function.")) params.add(Param(name='pool_2d_size', value=[[2, 2]], desc="Size of pooling layer in each block.")) params.add(Param( name='padding', value='same', hyper_space=hyper_spaces.choice( ['same', 'valid']), desc="The padding mode in the convolution layer. It should be one" "of `same`, `valid`." )) params.add(Param( name='dropout_rate', value=0.0, hyper_space=hyper_spaces.quniform(low=0.0, high=0.8, q=0.01), desc="The dropout rate." )) return params def build(self): """ Build model structure. ArcII has the desirable property of letting two sentences meet before their own high-level representations mature. """ input_left, input_right = self._make_inputs() embedding = self._make_embedding_layer() embed_left = embedding(input_left) embed_right = embedding(input_right) # Phrase level representations conv_1d_left = keras.layers.Conv1D( self._params['kernel_1d_count'], self._params['kernel_1d_size'], padding=self._params['padding'] )(embed_left) conv_1d_right = keras.layers.Conv1D( self._params['kernel_1d_count'], self._params['kernel_1d_size'], padding=self._params['padding'] )(embed_right) # Interaction matching_layer = matchzoo.layers.MatchingLayer(matching_type='plus') embed_cross = matching_layer([conv_1d_left, conv_1d_right]) for i in range(self._params['num_blocks']): embed_cross = self._conv_pool_block( embed_cross, self._params['kernel_2d_count'][i], self._params['kernel_2d_size'][i], self._params['padding'], self._params['activation'], self._params['pool_2d_size'][i] ) embed_flat = keras.layers.Flatten()(embed_cross) x = keras.layers.Dropout(rate=self._params['dropout_rate'])(embed_flat) inputs = [input_left, input_right] x_out = self._make_output_layer()(x) self._backend = keras.Model(inputs=inputs, outputs=x_out) @classmethod def _conv_pool_block( cls, x, kernel_count: int, kernel_size: int, padding: str, activation: str, pool_size: int ) -> typing.Any: output = keras.layers.Conv2D(kernel_count, kernel_size, padding=padding, activation=activation)(x) output = keras.layers.MaxPooling2D(pool_size=pool_size)(output) return output
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/models/arcii.py", "copies": "1", "size": "4891", "license": "apache-2.0", "hash": 3888581681597291000, "line_mean": 36.9147286822, "line_max": 79, "alpha_frac": 0.5416070333, "autogenerated": false, "ratio": 4.002454991816694, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5044062025116693, "avg_score": null, "num_lines": null }
"""An implementation of ArcI Model.""" import typing import keras from matchzoo.engine.base_model import BaseModel from matchzoo.engine.param import Param from matchzoo.engine.param_table import ParamTable from matchzoo.engine import hyper_spaces class ArcI(BaseModel): """ ArcI Model. Examples: >>> model = ArcI() >>> model.params['num_blocks'] = 1 >>> model.params['left_filters'] = [32] >>> model.params['right_filters'] = [32] >>> model.params['left_kernel_sizes'] = [3] >>> model.params['right_kernel_sizes'] = [3] >>> model.params['left_pool_sizes'] = [2] >>> model.params['right_pool_sizes'] = [4] >>> model.params['conv_activation_func'] = 'relu' >>> model.params['mlp_num_layers'] = 1 >>> model.params['mlp_num_units'] = 64 >>> model.params['mlp_num_fan_out'] = 32 >>> model.params['mlp_activation_func'] = 'relu' >>> model.params['dropout_rate'] = 0.5 >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build() """ @classmethod def get_default_params(cls) -> ParamTable: """:return: model default parameters.""" params = super().get_default_params( with_embedding=True, with_multi_layer_perceptron=True ) params['optimizer'] = 'adam' params.add(Param(name='num_blocks', value=1, desc="Number of convolution blocks.")) params.add(Param(name='left_filters', value=[32], desc="The filter size of each convolution " "blocks for the left input.")) params.add(Param(name='left_kernel_sizes', value=[3], desc="The kernel size of each convolution " "blocks for the left input.")) params.add(Param(name='right_filters', value=[32], desc="The filter size of each convolution " "blocks for the right input.")) params.add(Param(name='right_kernel_sizes', value=[3], desc="The kernel size of each convolution " "blocks for the right input.")) params.add(Param(name='conv_activation_func', value='relu', desc="The activation function in the " "convolution layer.")) params.add(Param(name='left_pool_sizes', value=[2], desc="The pooling size of each convolution " "blocks for the left input.")) params.add(Param(name='right_pool_sizes', value=[2], desc="The pooling size of each convolution " "blocks for the right input.")) params.add(Param( name='padding', value='same', hyper_space=hyper_spaces.choice( ['same', 'valid', 'causal']), desc="The padding mode in the convolution layer. It should be one" "of `same`, `valid`, and `causal`." )) params.add(Param( 'dropout_rate', 0.0, hyper_space=hyper_spaces.quniform( low=0.0, high=0.8, q=0.01), desc="The dropout rate." )) return params def build(self): """ Build model structure. ArcI use Siamese arthitecture. """ input_left, input_right = self._make_inputs() embedding = self._make_embedding_layer() embed_left = embedding(input_left) embed_right = embedding(input_right) for i in range(self._params['num_blocks']): embed_left = self._conv_pool_block( embed_left, self._params['left_filters'][i], self._params['left_kernel_sizes'][i], self._params['padding'], self._params['conv_activation_func'], self._params['left_pool_sizes'][i] ) embed_right = self._conv_pool_block( embed_right, self._params['right_filters'][i], self._params['right_kernel_sizes'][i], self._params['padding'], self._params['conv_activation_func'], self._params['right_pool_sizes'][i] ) rep_left = keras.layers.Flatten()(embed_left) rep_right = keras.layers.Flatten()(embed_right) concat = keras.layers.Concatenate(axis=1)([rep_left, rep_right]) dropout = keras.layers.Dropout( rate=self._params['dropout_rate'])(concat) mlp = self._make_multi_layer_perceptron_layer()(dropout) inputs = [input_left, input_right] x_out = self._make_output_layer()(mlp) self._backend = keras.Model(inputs=inputs, outputs=x_out) def _conv_pool_block( self, input_: typing.Any, filters: int, kernel_size: int, padding: str, conv_activation_func: str, pool_size: int ) -> typing.Any: output = keras.layers.Conv1D( filters, kernel_size, padding=padding, activation=conv_activation_func )(input_) output = keras.layers.MaxPooling1D(pool_size=pool_size)(output) return output
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/models/arci.py", "copies": "1", "size": "5386", "license": "apache-2.0", "hash": 7616711493528991000, "line_mean": 37.4714285714, "line_max": 78, "alpha_frac": 0.5285926476, "autogenerated": false, "ratio": 4.13989239046887, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 140 }
"""An implementation of a simple event system""" import logging class Event: """Simple event class""" def __init__(self, name): self.__name__ = name self._handlers = [] self._temp_handlers = [] def add(self, handler): """ Add a handler to the event. The order in which handlers are added is also the execution order. """ if not handler in self._handlers: self._handlers.append(handler) def remove(self, handler): """remove handler from the event.""" try: self._handlers.remove(handler) except ValueError: pass def fire(self, *args): """Launch the event by calling all handlers with self as argument.""" # logging.debug('Firing event {}'.format(self.__name__)) for handler in self._handlers: try: handler(*args) except TypeError as e: logging.error(e, exc_info=True) # Distinct loop to allow adding temp_handlers during event for handler in self._temp_handlers: try: handler(*args) except TypeError as e: logging.error(e, exc_info=True) self._temp_handlers = [] # logging.debug('Finished event {}'.format(self.__name__)) def add_for_once(self, handler): """ Add a handler to the event, but remove it after the event has been fired. These temporary handlers are executed after the normal handlers. """ if not handler in self._temp_handlers: self._temp_handlers.append(handler)
{ "repo_name": "Chiel92/fate", "path": "fate/event.py", "copies": "1", "size": "1651", "license": "mit", "hash": -8464378374748048000, "line_mean": 30.75, "line_max": 81, "alpha_frac": 0.5645063598, "autogenerated": false, "ratio": 4.663841807909605, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5728348167709605, "avg_score": null, "num_lines": null }
"""An implementation of a simple graph in Python.""" class Graph(object): """A graph containing nodes and single-directional edges between them. g.nodes(): return a list of all nodes in the graph g.edges(): return a list of all edges in the graph g.add_node(n): adds a new node 'n' to the graph g.add_edge(n1, n2): adds a new edge to the graph connecting 'n1' and 'n2', if either n1 or n2 are not already present in the graph, they should be added. g.del_node(n): deletes the node 'n' from the graph, raises an error if no such node exists. g.del_edge(n1, n2): deletes the edge connecting 'n1' and 'n2' from the graph, raises an error if no such edge exists g.has_node(n): True if node 'n' is contained in the graph, False if not. g.neighbors(n): returns the list of all nodes connected to 'n' by edges, raises an error if n is not in g g.adjacent(n1, n2): returns True if there is an edge connecting n1 and n2, False if not, raises an error if either of the supplied nodes are not in g """ def __init__(self): """Initialize an empty graph.""" self._nodes = {} def nodes(self): """Return a list of nodes in the graph.""" return list(self._nodes) def edges(self): """Return a list of tuples with key and its list of edges.""" tup_lst = [] if self.nodes: for start in self._nodes: for end in self._nodes[start]: tup_lst.append((start, end)) return tup_lst def add_node(self, node): """Add a new node to the graph.""" if node in self._nodes.keys(): raise ValueError("Node already present in Graph.") else: self._nodes[node] = [] def add_edge(self, n1, n2): """Add a single-directional edge connecting n1 to n2.""" self._nodes.setdefault(n1, []) self._nodes.setdefault(n2, []) if n2 not in self._nodes[n1]: self._nodes[n1].append(n2) else: raise ValueError("This edge already exists.") def del_node(self, node): """Delete a given node from the graph.""" if node in self._nodes.keys(): del self._nodes[node] else: raise ValueError("This node is not in the graph") def del_edge(self, n1, n2): """Delete a given edge from the graph.""" if n1 in self._nodes.keys() and n2 in self._nodes[n1]: self._nodes[n1].remove(n2) else: raise ValueError("This edge does not exist.") def has_node(self, node): """Return true is node is in graph, false if not.""" return node in self._nodes def neighbors(self, node): """Return list of edges of the node given.""" if node in self._nodes.keys(): return self._nodes[node] raise ValueError("Node is not in graph.") def adjacent(self, n1, n2): """Return True if there is an edge connecting n1 to n2 False if not.""" if not self.has_node(n1) or not self.has_node(n2): raise KeyError if n2 in self._nodes[n1]: return True return False def depth_first_traversal(self, start, prev=None): """Return full depth-first traversal path of the graph.""" if start not in self._nodes.keys(): raise KeyError if prev is None: prev = [] if start in prev: return [] path_list = [start] nodes = self._nodes[start] prev.append(start) for node in nodes: path_list.extend(self.depth_first_traversal(node, prev)) return path_list def breadth_first_traversal(self, parent, path_list=None): """Return a list containing the nodes of the graph in order of breadth-first traversal.""" if path_list is None: path_list = [] if not isinstance(parent, list): path_list.append(parent) parent = [parent] children = [] for item in parent: for edge in self._nodes[item]: if edge not in path_list: children.append(edge) path_list.extend(children) if len(children) == 0: return path_list return self.breadth_first_traversal(children, path_list) if __name__ == "__main__": # pragma: no cover import timeit def fill_graph(graph): for i in range(100): graph.add_edge(i, i + 1) def fill_and_depth_trav(): g = Graph() fill_graph(g) g.depth_first_traversal(1) def fill_and_breadth_trav(): g = Graph() fill_graph(g) g.breadth_first_traversal(1) depth_trav_timed = timeit.repeat(stmt="fill_and_depth_trav()", setup="from __main__ import fill_and_depth_trav", number=1000, repeat=3) breadth_trav_timed = timeit.repeat(stmt="fill_and_breadth_trav()", setup="from __main__ import fill_and_breadth_trav", number=1000, repeat=3) average_depth_timed = float(sum(depth_trav_timed) / len(depth_trav_timed)) average_breadth_timed = float(sum(breadth_trav_timed) / len(breadth_trav_timed)) print("Depth traversal times:", depth_trav_timed) print("average:", average_depth_timed) print("Breadth traversal times:", breadth_trav_timed) print("average:", average_breadth_timed) print("This print statement was brought to you by Ben and Maelle. You're welcome.")
{ "repo_name": "ellezv/data_structures", "path": "src/simple_graph.py", "copies": "1", "size": "5497", "license": "mit", "hash": 1565175093637456600, "line_mean": 34.464516129, "line_max": 145, "alpha_frac": 0.5926869201, "autogenerated": false, "ratio": 3.7318397827562797, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.482452670285628, "avg_score": null, "num_lines": null }
"""An implementation of a state-driven autonomous robot.""" from importlib import import_module import time import mount import sensor MIN_VOLTAGE = 7.0 # Minimum allowable voltage for consistent behavior MOTOR_LEFT = 0 # Index of the left motor MOTOR_RIGHT = 1 # Index of the right motor TRIM_STRAIGHT = -10 # Trim setting for straight movement DEFAULT_SPEED = 70 # Slowest speed without stall (60/120 for batt/cable) TURN_SPEED = 10 # Added speed for the outside wheel when turning MAX_TURN_RATIO = 1.2 # Max ratio of outside wheel to inside wheel speeds ROTATING_DEGREES_PER_TICK = 10 # Degrees of robot rotation in one encoder tick TURNING_DEGREES_PER_TICK = 5 # Degrees of robot turn in one encoder tick class LowVoltageError(Exception): pass class Robot(object): """The Robot class. Set the robot in motion by initializing a Robot object and calling run(). The robot will run autonomously until a goal state is reached or some unrecoverable exception occurs. Or until you step on it. """ def __init__(self, driver_module='gopigo'): """Initialize the robot attributes. Args: driver - the name of the module containing all of the robot control commands. Default is the 'gopigo' module, which will normally be used for robot operation. However, a stub module can be substituted for testing purposes. This delayed import allows for development and testing without having to install all of the gopigo dependencies. """ self.driver = import_module(driver_module) self.distance_sensor = None self.state = None volt = self.volt if volt < MIN_VOLTAGE: raise LowVoltageError('{0}V is below min voltage'.format(volt)) # Initialize motor components self.driver.stop() self.speed = [0, 0] # [left, right motor] self.driver.set_speed(DEFAULT_SPEED) self.driver.trim_write(TRIM_STRAIGHT) self.left_encoder = 0 self.right_encoder = 0 def run(self): """Set the robot in motion. Execution is delegated to the current state. Returns whatever value is returned from the underlying state. """ if not self.state: # TODO: make the robot determine its state before proceding raise AttributeError('State attribute not set on Robot.') return self.state.run() @property def volt(self): """Return the current battery voltage.""" return self.driver.volt() @property def degrees_turned(self): """Return the net degrees of turn since last accessed. Positive values indicate a net right turn, and negative values indicate a net left turn. """ left_encoder = self.driver.enc_read(MOTOR_LEFT) right_encoder = self.driver.enc_read(MOTOR_RIGHT) diff_left = left_encoder - self.left_encoder diff_right = right_encoder - self.right_encoder degrees = (diff_left - diff_right) * TURNING_DEGREES_PER_TICK self.left_encoder = left_encoder self.right_encoder = right_encoder return degrees def dist(self, angle=0): """Take an return a distance sensor reading in the direction given.""" if not self.distance_sensor: raise ValueError('no sensor configured') return self.distance_sensor.sense(angle) def stop(self): self.distance_sensor.center() # Because OCD is a thing self.driver.stop() def fwd(self): self.driver.set_speed(DEFAULT_SPEED) self.driver.fwd() self.speed = [DEFAULT_SPEED, DEFAULT_SPEED] def rotate(self, degrees=0): """Rotate the robot in place the given number of degrees. Args: degrees - the number of degrees to rotate (-360 to 360). Positive degrees command a left-hand rotation, and negative degrees command a right-hand rotation. """ self.driver.stop() if degrees < 0: self.driver.enc_tgt(1, 0, abs(int(degrees / ROTATING_DEGREES_PER_TICK))) self.driver.right_rot() else: self.driver.enc_tgt(0, 1, int(degrees / ROTATING_DEGREES_PER_TICK)) self.driver.left_rot() def steer(self, steering_factor): """Adjust wheel speeds to adjust turning rate. Args: steering_factor - a multiple to scale TURN_SPEED, which computes the new speed of the outside wheel of the turn. Postive values result in a left turn, and negative values in a right turn. """ turn_wheel_speed = min([ int(DEFAULT_SPEED + abs(steering_factor) * TURN_SPEED), int(DEFAULT_SPEED * MAX_TURN_RATIO) ]) if steering_factor > 0: self.speed = [DEFAULT_SPEED, turn_wheel_speed] elif steering_factor < 0: self.speed = [turn_wheel_speed, DEFAULT_SPEED] else: self.speed = [DEFAULT_SPEED, DEFAULT_SPEED] self.driver.set_left_speed(self.speed[0]) self.driver.set_right_speed(self.speed[1])
{ "repo_name": "mattskone/robot_maze", "path": "src/robot.py", "copies": "1", "size": "4589", "license": "mit", "hash": -3732695261205155000, "line_mean": 28.6064516129, "line_max": 78, "alpha_frac": 0.7191109174, "autogenerated": false, "ratio": 3.2226123595505616, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44417232769505616, "avg_score": null, "num_lines": null }
"""An implementation of a state-driven autonomous robot.""" from importlib import import_module import time import mount import sensor MOTOR_LEFT = 0 # Index of the left motor MOTOR_RIGHT = 1 # Index of the right motor TRIM_STRAIGHT = -10 # Trim setting for straight movement DEFAULT_SPEED = 60 # Slowest speed without stall (60/120 for batt/cable) TURN_SPEED = 10 # Added speed for the outside wheel when turning MAX_TURN_RATIO = 1.2 # Max ratio of outside wheel to inside wheel speeds class Robot(object): """The Robot class. Set the robot in motion by initializing a Robot object and calling run(). The robot will run autonomously until a goal state is reached or some unrecoverable exception occurs. Or until you step on it. """ def __init__(self, driver_module='gopigo'): """Initialize the robot attributes. Args: driver - the name of the module containing all of the robot control commands. Default is the 'gopigo' module, which will normally be used for robot operation. However, a stub module can be substituted for testing purposes. This delayed import allows for development and testing without having to install all of the gopigo dependencies. """ self.driver = import_module(driver_module) self.sensor = None self.state = None # Initialize motor components self.driver.stop() self.speed = [0, 0] # [left, right motor] self.driver.set_speed(DEFAULT_SPEED) self.driver.trim_write(TRIM_STRAIGHT) def run(self): """Set the robot in motion. Execution is delegated to the current state. Returns whatever value is returned from the underlying state. """ if not self.state: # TODO: make the robot determine its state before proceding raise AttributeError('State attribute not set on Robot.') return self.state.run() def sense(self, *args, **kwargs): """Take an return a sensor reading.""" if not self.sensor: raise ValueError('no sensor configured') return self.sensor.sense(*args, **kwargs) def stop(self): self.driver.stop() def fwd(self): self.driver.set_speed(DEFAULT_SPEED) self.driver.fwd() self.speed = [DEFAULT_SPEED, DEFAULT_SPEED] def steer(self, steering_factor): """Adjust wheel speeds to adjust turning rate. Args: steering_factor - a multiple to scale TURN_SPEED, which computes the new speed of the outside wheel of the turn. Postive values result in a left turn, and negative values in a right turn. """ turn_wheel_speed = min([ int(DEFAULT_SPEED + abs(steering_factor) * TURN_SPEED), int(DEFAULT_SPEED * MAX_TURN_RATIO) ]) if steering_factor > 0: self.speed = [DEFAULT_SPEED, turn_wheel_speed] elif steering_factor < 0: self.speed = [turn_wheel_speed, DEFAULT_SPEED] else: self.speed = [DEFAULT_SPEED, DEFAULT_SPEED] print self.speed self.driver.set_left_speed(self.speed[0]) self.driver.set_right_speed(self.speed[1])
{ "repo_name": "RLGarner1/robot_maze", "path": "src/robot.py", "copies": "1", "size": "2912", "license": "mit", "hash": -1042701084828228000, "line_mean": 28.12, "line_max": 74, "alpha_frac": 0.7163461538, "autogenerated": false, "ratio": 3.316628701594533, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45329748553945326, "avg_score": null, "num_lines": null }
# An implementation of a Stockfighter server in Python 3 # https://github.com/fohristiwhirl/disorderBook # # By Stockfighter player Amtiskaw (a.k.a. Fohristiwhirl) # With help from Medecau and cite-reader # # License: BSD-2-Clause (https://opensource.org/licenses/BSD-2-Clause) # # --------------------------------------------------------------------------- # # Tests show that it is the front end (i.e. dealing with sending and receiving # http, and so on) that takes up most (90%) of the application's time. import json import optparse import threading import random import string try: from bottle import request, response, route, run except ImportError: from bottle_0_12_9 import request, response, route, run # copy in our repo import disorderBook_book import disorderBook_ws all_venues = dict() # dict: venue string ---> dict: stock string ---> OrderBook objects current_book_count = 0 auth = dict() # ---------------------------------------------------------------------------------------- BAD_JSON = {"ok": False, "error": "Incoming data was not valid JSON"} BOOK_ERROR = {"ok": False, "error": "Book limit exceeded! (See command line options)"} NO_AUTH_ERROR = {"ok": False, "error": "Server is in +authentication mode but no API key was received"} AUTH_FAILURE = {"ok": False, "error": "Unknown account or wrong API key"} AUTH_WEIRDFAIL = {"ok": False, "error": "Account of stored data had no associated API key (this is impossible)"} NO_SUCH_ORDER = {"ok": False, "error": "No such order for that Exchange + Symbol combo"} MISSING_FIELD = {"ok": False, "error": "Incoming POST was missing required field"} URL_MISMATCH = {"ok": False, "error": "Incoming POST data disagreed with request URL"} BAD_TYPE = {"ok": False, "error": "A value in the POST had the wrong type"} BAD_VALUE = {"ok": False, "error": "Illegal value (usually a non-positive number)"} DISABLED = {"ok": False, "error": "Disabled or not enabled. (See command line options)"} # ---------------------------------------------------------------------------------------- class TooManyBooks (Exception): pass class NoApiKey (Exception): pass def dict_from_exception(e): di = dict() di["ok"] = False di["error"] = str(e) return di def create_book_if_needed(venue, symbol): global current_book_count if venue not in all_venues: if opts.maxbooks > 0: if current_book_count + 1 > opts.maxbooks: raise TooManyBooks all_venues[venue] = dict() if symbol not in all_venues[venue]: if opts.maxbooks > 0: if current_book_count + 1 > opts.maxbooks: raise TooManyBooks all_venues[venue][symbol] = disorderBook_book.OrderBook(venue, symbol, opts.websockets) current_book_count += 1 def api_key_from_headers(headers): try: return headers.get('X-Starfighter-Authorization') except: try: return headers.get('X-Stockfighter-Authorization') except: raise NoApiKey # ---------------------------------------------------------------------------------------- # Handlers for the various URLs. Since this is a server that must keep going at all costs, # most things are wrapped in excessive try statements as a precaution. @route("/ob/api/heartbeat", "GET") def heartbeat(): return {"ok": True, "error": ""} @route("/ob/api/venues", "GET") def venue_list(): ret = dict() ret["ok"] = True ret["venues"] = [{"name": v + " Exchange", "venue": v, "state": "open"} for v in all_venues] return ret @route("/ob/api/venues/<venue>/heartbeat", "GET") def venue_heartbeat(venue): if venue in all_venues: return {"ok": True, "venue": venue} else: response.status = 404 return {"ok": False, "error": "Venue {} does not exist (create it by using it)".format(venue)} @route("/ob/api/venues/<venue>", "GET") @route("/ob/api/venues/<venue>/stocks", "GET") def stocklist(venue): if venue in all_venues: return {"ok": True, "symbols": [{"symbol": symbol, "name": symbol + " Inc"} for symbol in all_venues[venue]]} else: response.status = 404 return {"ok": False, "error": "Venue {} does not exist (create it by using it)".format(venue)} @route("/ob/api/venues/<venue>/stocks/<symbol>", "GET") def orderbook(venue, symbol): try: create_book_if_needed(venue, symbol) except TooManyBooks: response.status = 400 return BOOK_ERROR try: ret = all_venues[venue][symbol].get_book() assert(ret) return ret except Exception as e: response.status = 500 return dict_from_exception(e) @route("/ob/api/venues/<venue>/stocks/<symbol>/quote", "GET") def quote(venue, symbol): try: create_book_if_needed(venue, symbol) except TooManyBooks: response.status = 400 return BOOK_ERROR try: ret = all_venues[venue][symbol].get_quote() assert(ret) return ret except Exception as e: response.status = 500 return dict_from_exception(e) @route("/ob/api/venues/<venue>/stocks/<symbol>/orders/<id>", "GET") def status(venue, symbol, id): id = int(id) try: create_book_if_needed(venue, symbol) except TooManyBooks: response.status = 400 return BOOK_ERROR try: account = all_venues[venue][symbol].account_from_order_id(id) if not account: response.status = 404 return NO_SUCH_ORDER if auth: try: apikey = api_key_from_headers(request.headers) except NoApiKey: response.status = 401 return NO_AUTH_ERROR if account not in auth: response.status = 401 return AUTH_WEIRDFAIL if auth[account] != apikey: response.status = 401 return AUTH_FAILURE ret = all_venues[venue][symbol].get_status(id) assert(ret) return ret except Exception as e: response.status = 500 return dict_from_exception(e) @route("/ob/api/venues/<venue>/accounts/<account>/orders", "GET") def status_all_orders(venue, account): # This can return a stupid amount of data and is disabled by default... if not opts.excess: response.status = 403 return DISABLED try: if auth: try: apikey = api_key_from_headers(request.headers) except NoApiKey: response.status = 401 return NO_AUTH_ERROR if account not in auth: response.status = 401 return AUTH_FAILURE if auth[account] != apikey: response.status = 401 return AUTH_FAILURE orders = [] if venue in all_venues: for bk in all_venues[venue].values(): orders += bk.get_all_orders(account)["orders"] ret = dict() ret["ok"] = True ret["venue"] = venue ret["orders"] = orders return ret except Exception as e: response.status = 500 return dict_from_exception(e) @route("/ob/api/venues/<venue>/accounts/<account>/stocks/<symbol>/orders", "GET") def status_all_orders_one_stock(venue, account, symbol): # This can return a stupid amount of data and is disabled by default... if not opts.excess: response.status = 403 return DISABLED try: create_book_if_needed(venue, symbol) except TooManyBooks: response.status = 400 return BOOK_ERROR try: if auth: try: apikey = api_key_from_headers(request.headers) except NoApiKey: response.status = 401 return NO_AUTH_ERROR if account not in auth: response.status = 401 return AUTH_FAILURE if auth[account] != apikey: response.status = 401 return AUTH_FAILURE ret = all_venues[venue][symbol].get_all_orders(account) assert(ret) return ret except Exception as e: response.status = 500 return dict_from_exception(e) @route("/ob/api/venues/<venue>/stocks/<symbol>/orders/<id>", "DELETE") @route("/ob/api/venues/<venue>/stocks/<symbol>/orders/<id>/cancel", "POST") def cancel(venue, symbol, id): id = int(id) try: create_book_if_needed(venue, symbol) except TooManyBooks: response.status = 400 return BOOK_ERROR try: account = all_venues[venue][symbol].account_from_order_id(id) if not account: response.status = 404 return NO_SUCH_ORDER if auth: try: apikey = api_key_from_headers(request.headers) except NoApiKey: response.status = 401 return NO_AUTH_ERROR if account not in auth: response.status = 401 return AUTH_WEIRDFAIL if auth[account] != apikey: response.status = 401 return AUTH_FAILURE ret = all_venues[venue][symbol].cancel_order(id) assert(ret) return ret except Exception as e: response.status = 500 return dict_from_exception(e) @route("/ob/api/venues/<venue>/stocks/<symbol>/orders", "POST") def make_order(venue, symbol): try: data = str(request.body.read(), encoding="utf-8") data = json.loads(data) except: response.status = 400 return BAD_JSON try: # Thanks to cite-reader for the following bug-fix: # Match behavior of real Stockfighter: recognize both these forms if "stock" in data: symbol_in_data = data["stock"] elif "symbol" in data: symbol_in_data = data["symbol"] else: symbol_in_data = symbol # Note that official SF handles POSTs that lack venue and stock/symbol (using the URL instead) if "venue" in data: venue_in_data = data["venue"] else: venue_in_data = venue # Various types of faulty POST... if venue_in_data != venue or symbol_in_data != symbol: response.status = 400 return URL_MISMATCH try: create_book_if_needed(venue, symbol) except TooManyBooks: response.status = 400 return BOOK_ERROR if auth: try: account = data["account"] except KeyError: response.status = 400 return MISSING_FIELD try: apikey = api_key_from_headers(request.headers) except NoApiKey: response.status = 401 return NO_AUTH_ERROR if account not in auth: response.status = 401 return AUTH_FAILURE if auth[account] != apikey: response.status = 401 return AUTH_FAILURE try: ret = all_venues[venue][symbol].parse_order(data) except TypeError: response.status = 400 return BAD_TYPE except KeyError: response.status = 400 return MISSING_FIELD except ValueError: response.status = 400 return BAD_VALUE assert(ret) return ret except Exception as e: response.status = 500 return dict_from_exception(e) # This next isn't part of the official API. FIXME? Maybe should require authentication... @route("/ob/api/venues/<venue>/stocks/<symbol>/scores", "GET") def scores(venue, symbol): try: if venue not in all_venues or symbol not in all_venues[venue]: response.status = 404 return "<pre>No such venue/stock!</pre>" try: currentprice = all_venues[venue][symbol].quote["last"] except KeyError: return "<pre>No trading activity yet.</pre>" all_data = [] book_obj = all_venues[venue][symbol] for account, pos in book_obj.positions.items(): all_data.append([account, pos.cents, pos.shares, pos.minimum, pos.maximum, pos.cents + pos.shares * currentprice]) all_data = sorted(all_data, key = lambda x : x[5], reverse = True) table_header = "Account USD Shares Pos.min Pos.max NAV" result_lines = [] for datum in all_data: # When in "serious" (authentication) mode, don't show shares and cents if not auth: result_lines.append("{:<15} ${:<10} {:<10} {:<10} {:<10} ${:<12}".format( datum[0], datum[1] // 100, datum[2], datum[3], datum[4], datum[5] // 100)) else: result_lines.append("{:<15} [hidden] [hidden] {:<10} {:<10} ${:<12}".format( datum[0], datum[3], datum[4], datum[5] // 100)) res_string = "\n".join(result_lines) ret = "<pre>{} {}\nCurrent price: ${:.2f}\n\n{}\n{}\n\nStart time: {}\nCurrent time: {}</pre>".format( venue, symbol, currentprice / 100, table_header, res_string, book_obj.starttime, disorderBook_book.current_timestamp()) return ret except Exception as e: response.status = 500 return dict_from_exception(e) # The following is from elliottneilclark; it returns an official looking GM response; # it does show all current venues and stocks. @route("/gm/levels/<level>", "POST") def start_level(level): return { "account": ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)), "instanceId": random.randint(0, 99999999), "instructions": {}, "ok": True, "secondsPerTradingDay": 5, "venues": [ x for x in all_venues.keys() ], "tickers": [ item for sublist in all_venues.values() for item in sublist.keys() ], "balances": { "USD": 0 }, } @route("/", "GET") @route("/ob/api/", "GET") def home(): return """ <pre> disorderBook: unofficial Stockfighter server https://github.com/fohristiwhirl/disorderBook By Amtiskaw (Fohristiwhirl on GitHub) With help from cite-reader, Medecau and DanielVF Mad props to patio11 for the elegant fundamental design! Also inspired by eu90h's Mockfighter "patio11 used go for a good reason" -- Medecau </pre> """ # ---------------------------------------------------------------------------------------- def create_auth_records(): global auth global opts with open(opts.accounts_file) as infile: auth = json.load(infile) def main(): global opts opt_parser = optparse.OptionParser() opt_parser.add_option( "-b", "--maxbooks", dest = "maxbooks", type = "int", help = "Maximum number of books (exchange/ticker combos) [default: %default]") opt_parser.set_defaults(maxbooks = 100) opt_parser.add_option( "-v", "--venue", dest = "default_venue", type = "str", help = "Default venue; always exists [default: %default]") opt_parser.set_defaults(default_venue = "TESTEX") opt_parser.add_option( "-s", "--symbol", "--stock", dest = "default_symbol", type = "str", help = "Default symbol; always exists on default venue [default: %default]") opt_parser.set_defaults(default_symbol = "FOOBAR") opt_parser.add_option( "-a", "--accounts", dest = "accounts_file", type = "str", help = "File containing JSON dict of account names mapped to their API keys [default: none]") opt_parser.set_defaults(accounts_file = "") opt_parser.add_option( "-p", "--port", dest = "port", type = "int", help = "Port [default: %default]") opt_parser.set_defaults(port = 8000) opt_parser.add_option( "-e", "--extra", "--excess", dest = "excess", action = "store_true", help = "Enable commands that can return excessive responses (all orders on venue)") opt_parser.set_defaults(excess = False) opt_parser.add_option( "-w", "--ws", "--websocket", "--websockets", dest = "websockets", action = "store_true", help = "Enable websockets") opt_parser.set_defaults(websockets = False) opt_parser.add_option( "--wsport", "--ws_port", dest = "ws_port", type = "int", help = "WebSocket Port [default: %default]") opt_parser.set_defaults(ws_port = 8001) opts, __ = opt_parser.parse_args() create_book_if_needed(opts.default_venue, opts.default_symbol) if opts.accounts_file: create_auth_records() print("disorderBook starting up on port {}".format(opts.port)) if opts.websockets: print("WebSockets on port {}".format(opts.ws_port)) if not auth: print("\n -----> Warning: running WITHOUT AUTHENTICATION! <-----\n") if opts.websockets: ws_thread = threading.Thread(target = disorderBook_ws.start_websockets, args = (opts.ws_port, )) ws_thread.start() run(host = "127.0.0.1", port = opts.port) if __name__ == "__main__": main()
{ "repo_name": "fohristiwhirl/disorderBook", "path": "disorderBook_main.py", "copies": "1", "size": "17553", "license": "mit", "hash": 8298988983891583000, "line_mean": 28.4020100503, "line_max": 139, "alpha_frac": 0.5650316185, "autogenerated": false, "ratio": 3.804291287386216, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9844581802600403, "avg_score": 0.004948220657162474, "num_lines": 597 }
"""An implementation of a struct parser which is fast and convenient.""" import struct format_string_map = dict( uint64_t="Q", int64_t="q", uint32_t="I", uint16_t="H", int32_t="i", int16_t="h", ) class BaseParser(object): _format_string = "" _fields = [] _name = "Unknown" _defaults = [] __slots__ = ("_data", "_fields", "_name", "_format_string", "_defaults") def __init__(self, data=None, **kwargs): if data is None: self._data = self._defaults[:] else: self._data = list( struct.unpack_from(self._format_string, data)) if kwargs: for k, v in kwargs.iteritems(): setattr(self, k, v) def __str__(self): result = ["Struct %s" % self._name] for field, data in zip(self._fields, self._data): result.append(" %s: %s" % (field, data)) return "\n".join(result) def Pack(self): return struct.pack(self._format_string, *self._data) @classmethod def sizeof(cls): return struct.calcsize(cls._format_string) def CreateStruct(struct_name, definition): fields = [] format_string = ["<"] defaults = [] for line in definition.splitlines(): line = line.strip(" ;") components = line.split() if len(components) >= 2: type_format_char = format_string_map.get(components[0]) name = components[1] if type_format_char is None: raise RuntimeError("Invalid definition %r" % line) try: if components[2] != "=": raise RuntimeError("Invalid definition %r" % line) defaults.append(int(components[3], 0)) except IndexError: defaults.append(0) format_string.append(type_format_char) fields.append(name) properties = dict( _format_string="".join(format_string), _fields=fields, _defaults=defaults, _name=struct_name) # Make accessors for all fields. for i, field in enumerate(fields): def setx(self, value, i=i): self._data[i] = value def getx(self, i=i): return self._data[i] properties[field] = property(getx, setx) return type(struct_name, (BaseParser,), properties)
{ "repo_name": "blschatz/aff4", "path": "pyaff4/pyaff4/struct_parser.py", "copies": "1", "size": "2374", "license": "apache-2.0", "hash": 8702808516373636000, "line_mean": 25.9772727273, "line_max": 76, "alpha_frac": 0.5395956192, "autogenerated": false, "ratio": 3.8352180936995155, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48748137128995156, "avg_score": null, "num_lines": null }
"""An implementation of a top-down, recursive descent, Backus-Naur form (BNF) parser and a finite-state, BNF grammar supporting n-ary branching structures.""" __authors__ = ['Aaron Levine', 'Zachary Yocum'] __emails__ = ['aclevine@brandeis.edu', 'zyocum@brandeis.edu'] import random from argparse import ArgumentParser from re import match, sub from string import strip START = '<START>' class BNFGrammar(object): """A Backus-Naur form (BNF) grammar capable of generating sentences.""" def __init__(self, rules): super(BNFGrammar, self).__init__() self.rules = rules self.root = self.rules[START] def generate(self, delimiter=' '): """Returns a sentence licensed by the grammar as a string.""" return delimiter.join(filter(None, self.traverse(self.root))) def traverse(self, tree): """Traverse the tree to generate a sentence licensed by the grammar.""" output = [] if tree.attributes.has_key('terminal'): # Terminal output.append(tree.attributes['terminal']) if tree.attributes.has_key('rule'): # Rule output.extend(self.traverse(self.rules[tree.attributes['rule']])) if tree.attributes.has_key('one-of'): # Disjunction child = random.choice(tree.children) output.extend(self.traverse(child)) if tree.attributes.has_key('all-of'): # Conjunction for child in tree.children: output.extend(self.traverse(child)) if tree.attributes.has_key('repeat'): # Repetition n = random.choice(tree.attributes['repeat']) for i in range(n): for child in tree.children: output.extend(self.traverse(child)) return output class BNFParser(object): """A top-down, recursive descent, Backus-Naur form (BNF) parser. Given a string containing a BNF grammar, a BNFParser instance parses the string to construct a finite-state grammar (FSG) stored in an n-ary tree.""" def __init__(self, text, repeat_max=3): super(BNFParser, self).__init__() self.text = self.normalize_text(text) self.repeat_max = repeat_max self.rules = self.compile_rules() self.parse() def compile_rules(self): """Builds a rules dictionary of A -> B key-value pairs. The left-hand-side keys (A) are rule name strings and the right-hand-side rules values (B) are rule expansion strings. The rules conform to BNF such that A is a non-terminal that expands to an expansion B that is composed of terminals, non-terminals, and operators.""" rules = dict([split_on('=', rule) for rule in split_on(';', self.text)]) for rule in rules: rules[rule] = self.normalize_rule(rules[rule]) return rules def normalize_text(self, text): """Normalizes raw BNF by removing comments and extraneous whitespace.""" sub_patterns = [ (r'//.+', ''), # remove comments (r'\n', ''), # removes newlines (r'\s+', ' ') # normalize whitespace ] for pattern, substitution in sub_patterns: text = sub(pattern, substitution, text) return text def normalize_rule(self, rule): """Normalizes raw BNF rules (i.e., the right-hand side of a rule) in preparation for parsing by removing extraneous whitespace and wrapping terminals and rule expansions with parentheses.""" substitutions = [ (r'\s*\|\s*', '|'), # remove whitespace before and after | (r'([^()\[\]|*+\s]+)', r'(\1)'), # wrap terminals/rules with () (r'([\])]+)\s+([\])]+)', r'\1\2'), # remove extraneous whitespace (r'([\[(]+)\s+([\[(]+)', r'\1\2'), (r'\]', r'])'), # ensure wrapping of non-terminals and optionals (r'\[', r'(['), (r'>', r'>)'), (r'<', r'(<'), ] for pattern, substitution in substitutions: rule = sub(pattern, substitution, rule) return rule def tokenize(self, rule): """Tokenizes normalized Backus-Naur Form (BNF) content.""" operators = '()[]|+* ' token_list = [] token = '' for character in rule: if character in operators: if token: token_list.append(token) token_list.append(character) token = '' else: token += character if token: token_list.append(token) return token_list def parse(self): """Convert BNF to an n-ary tree via a recursive-descent parse.""" # Instantiate a stack to keep track of each nested level stack = Stack() for lhs, rhs in self.rules.iteritems(): # Instantiate a tree to store the rule expansion root = Tree({'all-of' : None}) stack.push(root) current = root # Iterate over all tokens in the right-hand side for token in self.tokenize('(' + rhs + ')'): if token == '(': # We need to go deeper temp = Tree({'all-of' : None}) current.children.append(temp) temp.parent = current stack.push(temp) current = temp elif token == ')': # Kick back up a level stack.pop() current = stack[-1] elif token == '[': # Repeat once or not at all temp = Tree({'repeat': [0, 1]}) current.children.append(temp) temp.parent = current stack.push(temp) current = temp elif token == ']': # Kick back up a level stack.pop() current = stack[-1] elif token == '|': # Disjunction stack[-1].attributes = {'one-of' : None} current = stack[-1] elif token == ' ': # Conjunction if current.children: child = current.children.pop() temp = Tree({'all-of' : None}) temp.parent = current current.children.append(temp) child.parent = temp temp.children.append(child) current = temp elif token == '*': # Repeat zero or more times child = current.children[-1] temp = Tree({'repeat': range(0, self.repeat_max+1)}) if child.children: temp.children = [child.children.pop()] child.children.append(temp) temp.parent = child else: temp.children = [child] temp.parent = current current.children.pop() current.children.append(temp) elif token == '+': # Repeat one or more times child = current.children[-1] temp = Tree({'repeat': range(1, self.repeat_max+1)}) if child.children: temp.children = [child.children.pop()] child.children.append(temp) temp.parent = child else: temp.children = [child] temp.parent = current current.children.pop() current.children.append(temp) elif match(r'<.+>', token): # Rule expansion current.children.append(Tree({'rule' : token})) else: # Terminal current.children.append(Tree({'terminal' : token})) self.rules[lhs] = root return root class Stack(list): """A simple stack wrapping the built-in list.""" def __init__(self): super(Stack, self).__init__() def push(self, item): """Push an item onto the stack.""" self.append(item) def is_empty(self): """Returns True if the stack is empty and False otherwise.""" return not self class Tree(object): """An n-ary tree capable of storing a finite-state grammar (FSG).""" def __init__(self, attributes={}): super(Tree, self).__init__() self.attributes = attributes self.parent = None self.children = [] def pprint(tree, i=0): """A method for displaying n-ary trees in human-readable form.""" print '\t' * i + str(tree.attributes) for child in tree.children: pprint(child, i+1) def split_on(delimiter, text): """Split text based on a delimiter.""" return filter(None, map(strip, text.split(delimiter))) if __name__ == "__main__": # Setup commandline argument parser parser = ArgumentParser() parser.add_argument( '-g', '--grammar', required=True, help='path to BNF grammar file' ) parser.add_argument( '-n', '--number', default=1, type=int, help='number of sentences to generate' ) parser.add_argument( '-r', '--repeat-max', default=2, type=int, help="maximum number of '*' and '+' expansions" ) args = parser.parse_args() # Read the specified file's contents with open(args.grammar, 'r') as file: contents = file.read() # Instantiate parser and grammar parser = BNFParser(contents, args.repeat_max) grammar = BNFGrammar(parser.rules) # Generate and print sentences for i in range(args.number): print grammar.generate()
{ "repo_name": "zyocum/bnf_parser", "path": "bnfparse.py", "copies": "1", "size": "10079", "license": "mit", "hash": -2132109570978392800, "line_mean": 38.8418972332, "line_max": 80, "alpha_frac": 0.5163210636, "autogenerated": false, "ratio": 4.481547354379725, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5497868417979724, "avg_score": null, "num_lines": null }
"""An implementation of a trie.""" from collections import OrderedDict class TrieNode(object): """Create node to for use in a trie tree.""" def __init__(self, value=None): """Create node to push into Doubly link list.""" self.value = value self.children = OrderedDict() class Trie(object): """An implementation of a trie tree. insert(self, string): will insert the input string into the trie. If character in the input string is already present, it will be ignored. contains(self, string): will return True if the string is in the trie, False if not. size(self): will return the total number of words contained within the trie. 0 if empty. remove(self, string): will remove the given string from the trie. If the word does not exist, will raise an appropriate exception. traversal(self, start): Perform a full depth-first traversal of the graph beginning at start. The argument start should be a string, which may or may not be the beginning of a string or strings contained in the Trie. """ def __init__(self): """Initialize a trie tree.""" self.root = TrieNode() self._size = 0 def insert(self, string): """Insert a string into the trie.""" if not isinstance(string, str): raise TypeError("Word must be a string") string = string.lower() current = self.root for letter in string: if letter in current.children: current = current.children[letter] else: current.children[letter] = TrieNode(letter) current = current.children[letter] if '$' not in current.children: current.children['$'] = string self._size += 1 def contains(self, string): """Return true if string is in trie.""" if not isinstance(string, str): raise TypeError("Word must be a string") current = self.root for letter in string: if letter in current.children: current = current.children[letter] else: return False try: if current.children['$']: return True except KeyError: raise KeyError("That word has not been inserted") def size(self): """Return the number of words contained in the trie.""" return self._size def remove(self, string): """Return the string from the trie if it exists.""" if not isinstance(string, str): raise TypeError("Word must be a string") current = self.root last_bifurcated_node = None value_at_last_bifurcation = None for letter in string: if letter in current.children: if len(current.children) > 1: last_bifurcated_node = current value_at_last_bifurcation = letter current = current.children[letter] if '$' in current.children and len(current.children) == 1: if last_bifurcated_node: del last_bifurcated_node.children[value_at_last_bifurcation] self._size -= 1 else: del self.root.children[string[:1]] elif len(current.children) > 1: del current.children['$'] else: raise KeyError('Word is not in trie') def traversal(self, start=None): """Return a list of all the words in the subtree starting at start.""" current = self.root if start: for letter in start: if letter in current.children: current = current.children[letter] else: return result = self._traversal(current, True) for val in result: yield val.value def _traversal(self, node, first=False): if not first: yield node for child in node.children: if child == '$': continue for val in self._traversal(node.children[child]): yield val
{ "repo_name": "rwisecar/data-structures", "path": "src/trie.py", "copies": "1", "size": "4131", "license": "mit", "hash": 4846799489019826000, "line_mean": 35.2368421053, "line_max": 220, "alpha_frac": 0.5770999758, "autogenerated": false, "ratio": 4.5696902654867255, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5646790241286725, "avg_score": null, "num_lines": null }
"""An implementation of Attention Layer for Bimpm model.""" import tensorflow as tf from keras import backend as K from keras.engine import Layer class AttentionLayer(Layer): """ Layer that compute attention for BiMPM model. For detailed information, see Bilateral Multi-Perspective Matching for Natural Language Sentences, section 3.2. Reference: https://github.com/zhiguowang/BiMPM/blob/master/src/layer_utils.py#L145-L196 Examples: >>> import matchzoo as mz >>> layer = mz.contrib.layers.AttentionLayer(att_dim=50) >>> layer.compute_output_shape([(32, 10, 100), (32, 40, 100)]) (32, 10, 40) """ def __init__(self, att_dim: int, att_type: str = 'default', dropout_rate: float = 0.0): """ class: `AttentionLayer` constructor. :param att_dim: int :param att_type: int """ super(AttentionLayer, self).__init__() self._att_dim = att_dim self._att_type = att_type self._dropout_rate = dropout_rate @property def att_dim(self): """Get the attention dimension.""" return self._att_dim @property def att_type(self): """Get the attention type.""" return self._att_type def build(self, input_shapes): """ Build the layer. :param input_shapes: input_shape_lt, input_shape_rt """ if not isinstance(input_shapes, list): raise ValueError('A attention layer should be called ' 'on a list of inputs.') hidden_dim_lt = input_shapes[0][2] hidden_dim_rt = input_shapes[1][2] self.attn_w1 = self.add_weight(name='attn_w1', shape=(hidden_dim_lt, self._att_dim), initializer='uniform', trainable=True) if hidden_dim_lt == hidden_dim_rt: self.attn_w2 = self.attn_w1 else: self.attn_w2 = self.add_weight(name='attn_w2', shape=(hidden_dim_rt, self._att_dim), initializer='uniform', trainable=True) # diagonal_W: (1, 1, a) self.diagonal_W = self.add_weight(name='diagonal_W', shape=(1, 1, self._att_dim), initializer='uniform', trainable=True) self.built = True def call(self, x: list, **kwargs): """ Calculate attention. :param x: [reps_lt, reps_rt] :return attn_prob: [b, s_lt, s_rt] """ if not isinstance(x, list): raise ValueError('A attention layer should be called ' 'on a list of inputs.') reps_lt, reps_rt = x attn_w1 = self.attn_w1 attn_w1 = tf.expand_dims(tf.expand_dims(attn_w1, axis=0), axis=0) # => [1, 1, d, a] reps_lt = tf.expand_dims(reps_lt, axis=-1) attn_reps_lt = tf.reduce_sum(reps_lt * attn_w1, axis=2) # => [b, s_lt, d, -1] attn_w2 = self.attn_w2 attn_w2 = tf.expand_dims(tf.expand_dims(attn_w2, axis=0), axis=0) # => [1, 1, d, a] reps_rt = tf.expand_dims(reps_rt, axis=-1) attn_reps_rt = tf.reduce_sum(reps_rt * attn_w2, axis=2) # [b, s_rt, d, -1] attn_reps_lt = tf.tanh(attn_reps_lt) # [b, s_lt, a] attn_reps_rt = tf.tanh(attn_reps_rt) # [b, s_rt, a] # diagonal_W attn_reps_lt = attn_reps_lt * self.diagonal_W # [b, s_lt, a] attn_reps_rt = tf.transpose(attn_reps_rt, (0, 2, 1)) # => [b, a, s_rt] attn_value = K.batch_dot(attn_reps_lt, attn_reps_rt) # [b, s_lt, s_rt] # Softmax operation attn_prob = tf.nn.softmax(attn_value) # [b, s_lt, s_rt] # TODO(tjf) remove diagonal or not for normalization # if remove_diagonal: attn_value = attn_value * diagonal if len(x) == 4: mask_lt, mask_rt = x[2], x[3] attn_prob *= tf.expand_dims(mask_lt, axis=2) attn_prob *= tf.expand_dims(mask_rt, axis=1) return attn_prob def compute_output_shape(self, input_shapes): """Calculate the layer output shape.""" if not isinstance(input_shapes, list): raise ValueError('A attention layer should be called ' 'on a list of inputs.') input_shape_lt, input_shape_rt = input_shapes[0], input_shapes[1] return input_shape_lt[0], input_shape_lt[1], input_shape_rt[1]
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/contrib/layers/attention_layer.py", "copies": "1", "size": "4960", "license": "apache-2.0", "hash": 8161447889173273000, "line_mean": 33.4444444444, "line_max": 83, "alpha_frac": 0.49375, "autogenerated": false, "ratio": 3.525230987917555, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45189809879175546, "avg_score": null, "num_lines": null }
"""An implementation of CDSSM (CLSM) model.""" import typing import keras from keras.models import Model from matchzoo.engine.base_model import BaseModel from matchzoo.engine.param import Param from matchzoo.engine.param_table import ParamTable from matchzoo import preprocessors from matchzoo.utils import TensorType class CDSSM(BaseModel): """ CDSSM Model implementation. Learning Semantic Representations Using Convolutional Neural Networks for Web Search. (2014a) A Latent Semantic Model with Convolutional-Pooling Structure for Information Retrieval. (2014b) Examples: >>> model = CDSSM() >>> model.params['optimizer'] = 'adam' >>> model.params['filters'] = 32 >>> model.params['kernel_size'] = 3 >>> model.params['conv_activation_func'] = 'relu' >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build() """ @classmethod def get_default_params(cls) -> ParamTable: """:return: model default parameters.""" # set :attr:`with_multi_layer_perceptron` to False to support # user-defined variable dense layer units params = super().get_default_params(with_multi_layer_perceptron=True) params.add(Param(name='filters', value=32, desc="Number of filters in the 1D convolution " "layer.")) params.add(Param(name='kernel_size', value=3, desc="Number of kernel size in the 1D " "convolution layer.")) params.add(Param(name='strides', value=1, desc="Strides in the 1D convolution layer.")) params.add(Param(name='padding', value='same', desc="The padding mode in the convolution " "layer. It should be one of `same`, " "`valid`, ""and `causal`.")) params.add(Param(name='conv_activation_func', value='relu', desc="Activation function in the convolution" " layer.")) params.add(Param(name='w_initializer', value='glorot_normal')) params.add(Param(name='b_initializer', value='zeros')) params.add(Param(name='dropout_rate', value=0.3, desc="The dropout rate.")) return params def _create_base_network(self) -> typing.Callable: """ Apply conv and maxpooling operation towards to each letter-ngram. The input shape is `fixed_text_length`*`number of letter-ngram`, as described in the paper, `n` is 3, `number of letter-trigram` is about 30,000 according to their observation. :return: Wrapped Keras `Layer` as CDSSM network, tensor in tensor out. """ def _wrapper(x: TensorType): # Apply 1d convolutional on each word_ngram (lt). # Input shape: (batch_size, num_tri_letters, 90000) # Sequence of num_tri_letters vectors of 90000d vectors. x = keras.layers.Conv1D( filters=self._params['filters'], kernel_size=self._params['kernel_size'], strides=self._params['strides'], padding=self._params['padding'], activation=self._params['conv_activation_func'], kernel_initializer=self._params['w_initializer'], bias_initializer=self._params['b_initializer'])(x) # Apply max pooling by take max at each dimension across # all word_trigram features. x = keras.layers.Dropout(self._params['dropout_rate'])(x) x = keras.layers.GlobalMaxPool1D()(x) # Apply a none-linear transformation use a tanh layer. x = self._make_multi_layer_perceptron_layer()(x) return x return _wrapper def build(self): """ Build model structure. CDSSM use Siamese architecture. """ base_network = self._create_base_network() # Left input and right input. input_left, input_right = self._make_inputs() # Process left & right input. x = [base_network(input_left), base_network(input_right)] # Dot product with cosine similarity. x = keras.layers.Dot(axes=[1, 1], normalize=True)(x) x_out = self._make_output_layer()(x) self._backend = Model(inputs=[input_left, input_right], outputs=x_out) @classmethod def get_default_preprocessor(cls): """:return: Default preprocessor.""" return preprocessors.CDSSMPreprocessor() def guess_and_fill_missing_params(self, verbose: int = 1): """ Guess and fill missing parameters in :attr:`params`. Use this method to automatically fill-in hyper parameters. This involves some guessing so the parameter it fills could be wrong. For example, the default task is `Ranking`, and if we do not set it to `Classification` manually for data packs prepared for classification, then the shape of the model output and the data will mismatch. :param verbose: Verbosity. """ self._params.get('input_shapes').set_default([(10, 30), (10, 30)], verbose) super().guess_and_fill_missing_params(verbose)
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/models/cdssm.py", "copies": "1", "size": "5450", "license": "apache-2.0", "hash": -1313027946593110500, "line_mean": 40.2878787879, "line_max": 78, "alpha_frac": 0.587706422, "autogenerated": false, "ratio": 4.251170046801872, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5338876468801872, "avg_score": null, "num_lines": null }
"""An implementation of Common Lisp's FORMAT.""" from __future__ import with_statement import sys from cStringIO import StringIO from math import log10 import re import unicodedata from bindings import bindings from charpos import CharposStream from prettyprinter import PrettyPrinter import printervars __all__ = ["Formatter", "format"] class FormatError(StandardError): def __init__(self, control, *args): self.control = control self.args = args def __str__(self): return format(None, self.control, *self.args) class FormatParseError(FormatError): offset = 2 def __init__(self, control, index, message, *args): super(FormatParseError, self).__init__("~?~%~V@T\"~A\"~%~V@T^", message, args, self.offset, control, index + self.offset) class UpAndOut(Exception): pass class UpUpAndOut(Exception): pass class Arguments(object): """A container for format arguments. Essentially a read-only list, but with random-access, bi-directional iterators.""" def __init__(self, args, outer=None): self.args = args self.outer = outer self.len = len(self.args) self.cur = 0 self.empty = (self.len == 0) def __len__(self): return self.len def __getitem__(self, key): return self.args[key] def __iter__(self): return self def next(self): if self.empty: raise StopIteration arg = self.args[self.cur] self.cur += 1 self.empty = (self.cur == self.len) return arg def prev(self): if self.cur == 0: raise StopIteration self.cur -= 1 self.empty = False return self.args[self.cur] def peek(self, n=0): return self.args[self.cur + n] def goto(self, n): if n < 0 or n >= self.len: raise IndexError("index %d is out of bounds" % n) self.cur = n self.empty = False @property def remaining(self): return self.len - self.cur class Modifiers(object): colon = frozenset([":"]) atsign = frozenset(["@"]) both = frozenset([":@"]) all = colon | atsign | both class Directive(object): """Base class for all format directives. The control-string parser creates instances of (subclasses of) this class, which produce appropriately formatted output via their format methods.""" variable_parameter = object() remaining_parameter = object() modifiers_allowed = None parameters_allowed = 0 need_charpos = False need_prettyprinter = False def __init__(self, params, colon, atsign, control="", start=0, end=0, parent=None): if (colon or atsign) and self.modifiers_allowed is None: raise FormatError("neither colon nor at-sign allowed " "for this directive") elif (colon and atsign) and ":@" not in self.modifiers_allowed: raise FormatError("cannot specify both colon and at-sign") elif colon and ":" not in self.modifiers_allowed: raise FormatError("colon not allowed for this directive") elif atsign and "@" not in self.modifiers_allowed: raise FormatError("at-sign not allowed for this directive") if len(params) > self.parameters_allowed: raise FormatError("no~@[ more than ~D~] parameter~:P allowed " "for this directive", self.parameters_allowed) self.params = params; self.colon = colon; self.atsign = atsign self.control = control; self.start = start; self.end = end self.parent = parent def __str__(self): return self.control[self.start:self.end] def __len__(self): return self.end - self.start def format(self, stream, args): """Output zero or more arguments to stream.""" pass def param(self, n, args, default=None): if n < len(self.params): p = self.params[n] if p is Directive.variable_parameter: p = args.next() elif p is Directive.remaining_parameter: p = args.remaining return p if p is not None else default else: return default def governor(self, cls): """If an instance of cls appears anywhere in the chain of parents from this instance to the root, return that instance, or None otherwise.""" parent = self.parent while parent: if isinstance(parent, cls): return parent parent = parent.parent return None class DelimitedDirective(Directive): """Delimited directives, such as conditional expressions and justifications, are composed of an opening delimiter, zero or more clauses separated by a separator, and a closing delimiter. Subclasses should define a class attribute, delimiter, that specifies the class of the closing delimiter. Instances will have that attribute set to the instance of that class actually encountered.""" delimiter = None def __init__(self, *args): super(DelimitedDirective, self).__init__(*args) self.clauses = [[]] self.separators = [] def append(self, x): if isinstance(x, Separator): self.separators.append(x) self.clauses.append([]) elif isinstance(x, self.delimiter): self.delimiter = x self.delimited() else: self.clauses[len(self.separators)].append(x) self.end = x.end if isinstance(x, Directive) else (self.end + len(x)) def delimited(self): """Called when the complete directive, including the delimiter, has been parsed.""" self.need_prettyprinter = any([x.need_prettyprinter \ for c in self.clauses \ for x in c \ if isinstance(x, Directive)]) self.need_charpos = self.need_prettyprinter or \ any([x.need_charpos \ for c in self.clauses \ for x in c \ if isinstance(x, Directive)]) # Basic Output ascii_control_chars = { 0: ("^@", "nul"), 1: ("^A", "soh"), 2: ("^B", "stx"), 3: ("^C", "etx"), 4: ("^D", "eot"), 5: ("^E", "enq"), 6: ("^F", "ack"), 7: ("^G", "bel"), 8: ("^H", "bs"), 9: ("\t", "ht"), 10: ("\n", "nl"), 11: ("^K", "vt"), 12: ("^L", "np"), 13: ("^M", "cr"), 14: ("^N", "so"), 15: ("^O", "si"), 16: ("^P", "dle"), 17: ("^Q", "dc1"), 18: ("^R", "dc2"), 19: ("^S", "dc3"), 20: ("^T", "dc4"), 21: ("^U", "nak"), 22: ("^V", "syn"), 23: ("^W", "etb"), 24: ("^X", "can"), 25: ("^Y", "em"), 26: ("^Z", "sub"), 27: ("^[", "esc"), 28: ("^\\", "fs"), 29: ("^]", "gs"), 30: ("^^", "rs"), 31: ("^_", "us"), 127: ("^?", "del") } python_escapes = { "\\": "\\", "\'": "\'", "\a": "a", "\b": "b", "\f": "f", "\n": "n", "\r": "r", "\t": "t", "\v": "v" } class Character(Directive): modifiers_allowed = Modifiers.all def format(self, stream, args): char = unicode(args.next()) if len(char) != 1: raise TypeError("expected single character") if self.atsign: if char in python_escapes: stream.write('"\\%s"' % python_escapes[char]) else: try: stream.write('u"\\N{%s}"' % unicodedata.name(char)) except ValueError: stream.write(repr(char)) else: if unicodedata.category(char).startswith("C"): try: stream.write(unicodedata.name(char)) except ValueError: code = ord(char) if code in ascii_control_chars: i = 1 if self.colon else 0 stream.write(ascii_control_chars[code][i]) else: raise FormatError("unprintable character") else: stream.write(char) class ConstantChar(Directive): """Directives that produce strings consisting of some number of copies of a constant character may, if the parameter is not V or #, be optimized by producing the strings directly, rather than a Directive instance.""" modifiers_allowed = None parameters_allowed = 1 def __new__(cls, params, colon, atsign, *args): if colon or atsign: raise FormatError("neither colon nor at-sign allowed " "for this directive") if not params: return cls.character elif params and isinstance(params[0], int): return cls.character * params[0] else: return super(ConstantChar, cls).__new__(cls, params, colon, atsign, *args) def format(self, stream, args): stream.write(self.character * self.param(0, args, 1)) class Newline(ConstantChar): character = "\n" class FreshLine(Directive): need_charpos = True def format(self, stream, args): n = self.param(0, args, 1) if n > 0: try: stream.fresh_line() n -= 1 while n > 0: stream.terpri() n -= 1 except AttributeError: stream.write("\n" * n) class Page(ConstantChar): character = "\f" class Tilde(ConstantChar): character = "~" # Radix Control digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" def convert(n, radix): """Yield the digits of the non-negative integer n in the given radix.""" def le_digits(n, radix): while n > 0: yield digits[n % radix] n /= radix if radix < 2 or radix > 36: raise ValueError("radix out of range") return reversed(tuple(le_digits(n, radix))) roman_numerals = ["M", 2, "D", 5, "C", 2, "L", 5, "X", 2, "V", 5, "I"] def roman_int(n, oldstyle=False): """Yield the Roman numeral representation of n. This routine is a straightforward translation of the code from section 69 of TeX82, where it is prefaced by the following comment: Readers who like puzzles might enjoy trying to figure out how this tricky code works; therefore no explanation will be given. Notice that 1990 yields MCMXC, not MXM. The only substantive change to the algorithm is the addition of the old-style flag.""" if n < 1 or n > (4999 if oldstyle else 3999): raise ValueError("integer cannot be expressed as Roman numerals") # j & k are mysterious indices into roman_numerals; # u & v are mysterious numbers j = 0; v = 1000 while True: while n >= v: yield roman_numerals[j]; n -= v if n <= 0: return # nonpositive input produces no output k = j + 2; u = v / roman_numerals[k - 1] if roman_numerals[k - 1] == 2: k += 2; u /= roman_numerals[k - 1] if n + u >= v and not oldstyle: yield roman_numerals[k]; n += u else: j += 2; v /= roman_numerals[j - 1] # English ordinal & cardinal conversion code contributed by Richard M. # Kreuter <kreuter@progn.net>. cardinals = ["zero", "one", "two" , "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] ordinals = ["zeroth", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth", "sixteenth", "seventeenth", "eighteenth", "nineteenth"] tenstems = ["", "ten", "twent", "thirt", "fourt", "fift", "sixt", "sevent", "eight", "ninet"] ten_cubes = ["", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion"] def itoe(n, ordinal): if n < 0: s = "negative " n = abs(n) else: s = "" if ordinal: table = ordinals osuff = "th" tsuff0 = "ieth" else: table = cardinals osuff = "" tsuff0 = "y" tsuff1 = "y" if n < 1000: if n >= 100: return s + "%s hundred" % itoc(n/100) + \ (osuff if n % 100 == 0 else (" " + itoe(n % 100, ordinal))) else: if n < 20: return s + table[n] else: ones = n % 10 return s + tenstems[n/10] + \ (tsuff0 if ones == 0 else (tsuff1 + "-" + table[ones])) v = int(log10(n)) / 3 u = 1000 ** v while v >= 0: q = n / u if q != 0: s += itoe(q, ordinal and n < 1000) if v >= len(ten_cubes): s += " times ten to the %s power plus" % (itoo(3*v)) elif ten_cubes[v]: s += " " + ten_cubes[v] n %= u if n == 0: if v > 0: s += osuff else: if n >= 100 and v < len(ten_cubes): s += "," s += " " v -= 1 u /= 1000 return s def itoo(n): return itoe(n, True) def itoc(n): return itoe(n, False) class Numeric(Directive): """Base class for numeric (radix control) directives.""" modifiers_allowed = Modifiers.all parameters_allowed = 4 def format(self, stream, args): def commafy(s, commachar, comma_interval): """Add commachars between groups of comma_interval digits.""" first = len(s) % comma_interval a = [s[0:first]] if first > 0 else [] for i in range(first, len(s), comma_interval): a.append(s[i:i + comma_interval]) return commachar.join(a) i = 0 if self.radix: radix = self.radix else: radix = int(self.param(0, args, 0)); i += 1 mincol = int(self.param(i, args, 0)); i += 1 padchar = str(self.param(i, args, " ")); i += 1 commachar = str(self.param(i, args, ",")); i += 1 comma_interval = int(self.param(i, args, 3)); i += 1 n = args.next() s = self.convert(abs(n), radix) sign = ("+" if n >= 0 else "-") if self.atsign else \ ("-" if n < 0 else "") if self.colon: if padchar == "0" and mincol > len(s) + len(sign): # We pad with zeros first so that they can be commafied, # too (cf. CLiki Issue FORMAT-RADIX-COMMACHAR). But in # order to figure out how many to add, we need to solve a # little constraint problem. def col(n): return n + (n-1)/comma_interval + len(sign) width = -1 for i in range(len(s), mincol): if col(i) == mincol: # exact fit width = i break elif col(i) > mincol: # too big width = i - 1 break assert width > 0, "couldn't find a width" s = s.rjust(width, padchar) # If we're printing a sign, and the width that we chose # above is a multiple of comma_interval, we'll need (at # most one) extra space to get up to mincol. padchar = " " s = commafy(s, commachar, comma_interval) with bindings(printervars, print_escape=False, print_radix=False, print_base=radix, print_readably=False): stream.write((sign + s).rjust(mincol, padchar)) class Radix(Numeric): parameters_allowed = 5 radix = None def __init__(self, *args): super(Radix, self).__init__(*args) if not self.params: self.format = self.old_roman if self.colon and self.atsign \ else self.roman if self.atsign \ else self.ordinal if self.colon \ else self.cardinal def convert(self, n, radix): return "".join(convert(n, radix)) def roman(self, stream, args): stream.write("".join(roman_int(args.next()))) def old_roman(self, stream, args): stream.write("".join(roman_int(args.next(), True))) def ordinal(self, stream, args): stream.write(itoo(args.next())) def cardinal(self, stream, args): stream.write(itoc(args.next())) class Decimal(Numeric): radix = 10 def convert(self, n, radix): return "%d" % n octal_digits = ["000", "001", "010", "011", "100", "101", "110", "111"] class Binary(Numeric): radix = 2 def convert(self, n, radix): return "".join(octal_digits[int(digit)] \ for digit in "%o" % n).lstrip("0") class Octal(Numeric): radix = 8 def convert(self, n, radix): return "%o" % n class Hexadecimal(Numeric): radix = 16 def convert(self, n, radix): return "%X" % n # Printer Operations class Padded(Directive): modifiers_allowed = Modifiers.all parameters_allowed = 4 need_prettyprinter = True def format(self, stream, args): def pad(s): mincol = self.param(0, args, 0) colinc = self.param(1, args, 1) minpad = self.param(2, args, 0) padchar = self.param(3, args, " ") # The string methods l/rjust don't support a colinc or minpad. if colinc != 1: raise FormatError("colinc parameter must be 1") if minpad != 0: raise FormatError("minpad parameter must be 0") return s.rjust(mincol, padchar) if self.atsign else \ s.ljust(mincol, padchar) arg = args.next() stream.pprint("[]" if self.colon and arg is None \ else pad(format(None, "~W", arg)) if self.params \ else arg) class Aesthetic(Padded): def format(self, stream, args): with bindings(printervars, print_escape=None): super(Aesthetic, self).format(stream, args) class Standard(Padded): def format(self, stream, args): with bindings(printervars, print_escape=True): super(Standard, self).format(stream, args) class Write(Directive): modifiers_allowed = Modifiers.all need_prettyprinter = True def __init__(self, *args): super(Write, self).__init__(*args) if self.colon or self.atsign: self.bindings = {} if self.colon: self.bindings["print_pretty"] = True if self.atsign: self.bindings["print_level"] = None self.bindings["print_length"] = None self.format = self.format_with_bindings def format(self, stream, args): stream.pprint(args.next()) def format_with_bindings(self, stream, args): with bindings(printervars, **self.bindings): stream.pprint(args.next()) # Pretty Printer Operations class ConditionalNewline(Directive): modifiers_allowed = Modifiers.all need_prettyprinter = True def format(self, stream, args): stream.newline(mandatory=(self.colon and self.atsign), fill=self.colon) def fill_paragraph(body, blanks=re.compile(r"(\s+)")): """Insert a ~:_ after each group of blanks immediately contained in the body. This makes it easy to achieve the equivalent of paragraph filling.""" for x in body: if isinstance(x, basestring): for (i, s) in enumerate(blanks.split(x)): if i % 2 == 0: if s: yield s else: yield s yield ConditionalNewline([], True, False) else: yield x class LogicalBlock(DelimitedDirective): # Note: instances of this class are never created directly; the # delimiter method of the Justification class changes the class # of instances delimited with "~:>". need_prettyprinter = True def delimited(self): super(LogicalBlock, self).delimited() # Note: with the colon modifier, the prefix & suffix default to # square, not round brackets; this is Python, not Lisp. self.prefix = "[" if self.colon else "" self.suffix = "]" if self.colon else "" if len(self.clauses) == 0: self.body = [] elif len(self.clauses) == 1: (self.body,) = self.clauses elif len(self.clauses) == 2: ((self.prefix,), self.body) = self.clauses elif len(self.clauses) == 3: ((self.prefix,), self.body, (self.suffix,)) = self.clauses else: raise FormatError("too many segments for ~~<...~~:>") self.per_line = self.separators and self.separators[0].atsign if self.delimiter.atsign: self.body = fill_paragraph(self.body) def format(self, stream, args): with stream.logical_block(None, prefix=str(self.prefix), per_line=self.per_line, suffix=str(self.suffix)): try: apply_directives(stream, self.body, args if self.atsign \ else Arguments(args.next())) except UpAndOut: pass class Indentation(Directive): modifiers_allowed = Modifiers.colon parameters_allowed = 1 need_prettyprinter = True def format(self, stream, args): stream.indent(offset=int(self.param(0, args, 0)), relative=self.colon) # Layout Control class Tabulate(Directive): modifiers_allowed = Modifiers.all parameters_allowed = 2 need_charpos = True def format(self, stream, args): def ceiling(a, b): q, r = divmod(a, b) return (q + 1) if r else q def output_spaces(stream, n): stream.write(" " * n) if self.colon: raise FormatError("~A not yet supported", self) elif self.atsign: # relative tabulation colrel = int(self.param(0, args, 1)) colinc = int(self.param(1, args, 1)) try: cur = stream.charpos output_spaces(stream, colinc * ceiling(cur + colrel, colinc) - cur) except AttributeError: output_spaces(stream, colrel) else: # absolute tabulation colnum = int(self.param(0, args, 1)) colinc = int(self.param(1, args, 1)) try: cur = stream.charpos if cur < colnum: output_spaces(stream, colnum - cur) elif colinc > 0: output_spaces(stream, colinc - ((cur - colnum) % colinc)) except AttributeError: stream.write(" ") class EndJustification(Directive): modifiers_allowed = Modifiers.all class Justification(DelimitedDirective): modifiers_allowed = Modifiers.all delimiter = EndJustification def delimited(self): if self.delimiter.colon: # Blame Dick Waters. self.__class__ = LogicalBlock self.delimited() else: super(Justification, self).delimited() def format(self, stream, args): raise FormatError("justification not yet supported") # Control-Flow Operations class GoTo(Directive): modifiers_allowed = Modifiers.all parameters_allowed = 1 def format(self, stream, args): if self.atsign: args.goto(self.param(0, args, 0)) else: ignore = args.prev if self.colon else args.next for i in range(self.param(0, args, 1)): ignore() class EndConditional(Directive): pass class Conditional(DelimitedDirective): modifiers_allowed = Modifiers.all parameters_allowed = 1 delimiter = EndConditional def delimited(self): super(Conditional, self).delimited() if self.colon: if len(self.clauses) != 2: raise FormatError("must specify exactly two sections") elif self.atsign: if len(self.clauses) != 1: raise FormatError("can only specify one section") else: if len(self.separators) > 1 and \ any([s.colon for s in self.separators[0:-1]]): raise FormatError("only the last ~~; may have a colon") def format(self, stream, args): if self.colon: # "~:[ALTERNATIVE~;CONSEQUENT~] selects the ALTERNATIVE control # string if arg is false, and selects the CONSEQUENT control # string otherwise." apply_directives(stream, self.clauses[1 if args.next() else 0], args) elif self.atsign: # "~@[CONSEQUENT~] tests the argument. If it is true, then # the argument is not used up by the ~[ command but remains # as the next one to be processed, and the one clause # CONSEQUENT is processed. If the arg is false, then the # argument is used up, and the clause is not processed." if args.peek(): apply_directives(stream, self.clauses[0], args) else: args.next() else: try: n = self.param(0, args) if n is None: n = args.next() apply_directives(stream, self.clauses[n], args) except IndexError: if self.separators[-1].colon: # "If the last ~; used to separate clauses is ~:; # instead, then the last clause is an 'else' clause # that is performed if no other clause is selected." apply_directives(stream, self.clauses[-1], args) class EndIteration(Directive): modifiers_allowed = Modifiers.colon class Iteration(DelimitedDirective): modifiers_allowed = Modifiers.all parameters_allowed = 1 delimiter = EndIteration def append(self, x): if isinstance(x, Separator): raise FormatError("~~; not permitted in ~~{...~~}") super(Iteration, self).append(x) def delimited(self): body = self.clauses[0] self.need_prettyprinter = not body or \ any([x.need_prettyprinter for x in body if isinstance(x, Directive)]) self.need_charpos = self.need_prettyprinter or \ any([x.need_charpos for x in body if isinstance(x, Directive)]) self.prepared = body and prepare_directives(body) def format(self, stream, args): max = self.param(0, args, -1) body = self.prepared or \ prepare_directives(parse_control_string(args.next())) args = args if self.atsign else Arguments(args.next()) next = (lambda args: Arguments(args.next(), args)) if self.colon \ else None write = stream.write i = 0 while not args.empty or (i == 0 and self.delimiter.colon): if i == max: break i += 1 try: iargs = next(args) if next else args fast_apply_directives(stream, write, body, iargs) except UpAndOut: continue except UpUpAndOut: break class Recursive(Directive): modifiers_allowed = Modifiers.atsign need_charpos = True need_prettyprinter = True def format(self, stream, args): apply_directives(stream, parse_control_string(args.next()), args if self.atsign else Arguments(args.next())) # Miscellaneous Operations class EndCaseConversion(Directive): pass class CaseConversion(DelimitedDirective): modifiers_allowed = Modifiers.all delimiter = EndCaseConversion def delimited(self): super(CaseConversion, self).delimited() self.body = self.clauses[0] def format(self, stream, args): stringstream = StringIO() try: Formatter(self.body)(stringstream, args) s = stringstream.getvalue() finally: stringstream.close() stream.write(s.upper() if self.colon and self.atsign \ else s.title() if self.colon \ else s.capitalize() if self.atsign \ else s.lower()) class Plural(Directive): modifiers_allowed = Modifiers.all def __init__(self, *args): def prev(args): return args.peek(-1) def next(args): return args.next() def y(arg): return "y" if arg == 1 else "ies" def s(arg): return "" if arg == 1 else "s" super(Plural, self).__init__(*args) self.arg = prev if self.colon else next self.suffix = y if self.atsign else s def format(self, stream, args): stream.write(self.suffix(self.arg(args))) # Miscellaneous Pseudo-Operations class Separator(Directive): modifiers_allowed = Modifiers.colon | Modifiers.atsign class Escape(Directive): modifiers_allowed = Modifiers.colon parameters_allowed = 3 def __init__(self, *args): super(Escape, self).__init__(*args) if self.colon: iteration = self.governor(Iteration) if not (iteration and iteration.colon): raise FormatError("can't have ~~:^ outside of a " "~~:{...~~} construct") self.exception = UpUpAndOut if self.colon else UpAndOut if len(self.params) == 0: self.format = self.check_remaining_outer if self.colon \ else self.check_remaining else: self.format = self.check_params def check_remaining(self, stream, args): if args.empty: raise UpAndOut() def check_remaining_outer(self, stream, args): if args.outer.empty: raise UpUpAndOut() def check_params(self, stream, args): # This could be split up, too. (param1, param2, param3) = (self.param(i, args) for i in range(3)) if (param3 is not None and param1 <= param2 and param2 <= param3) or \ (param2 is not None and param1 == param2) or \ (param1 is not None and param1 == 0): raise self.exception() format_directives = dict() def register_directive(char, cls): assert len(char) == 1, "only single-character directives allowed" assert issubclass(cls, Directive), "invalid format directive class" format_directives[char.upper()] = format_directives[char.lower()] = cls map(lambda x: register_directive(*x), { "C": Character, "%": Newline, "&": FreshLine, "|": Page, "~": Tilde, "R": Radix, "D": Decimal, "B": Binary, "O": Octal, "X": Hexadecimal, "A": Aesthetic, "S": Standard, "W": Write, "_": ConditionalNewline, "I": Indentation, "T": Tabulate, "<": Justification, ">": EndJustification, "*": GoTo, "[": Conditional, "]": EndConditional, "{": Iteration, "}": EndIteration, "?": Recursive, "(": CaseConversion, ")": EndCaseConversion, "P": Plural, ";": Separator, "^": Escape, }.items()) def parse_control_string(control, start=0, parent=None): """Yield a list of strings and Directive instances corresponding to the given control string.""" assert isinstance(control, basestring), "control string must be a string" assert start >= 0, "can't start parsing from end" i = start end = len(control) while i < end: tilde = control.find("~", i) if tilde == -1: yield control[i:end] break elif tilde > i: yield control[i:tilde] i = tilde + 1 params = [] while i < end: # empty parameter if control[i] == ",": params.append(None) i += 1 continue # numeric parameter mark = i if control[i] in "+-": i += 1 while i < end and control[i].isdigit(): i += 1 if i > mark: params.append(int(control[mark:i])) if control[i] == ",": i += 1 continue # character parameter if control[i] == "'": params.append(control[i+1]) i += 2 if control[i] == ",": i += 1 continue # "variable" parameter if control[i] in "Vv": params.append(Directive.variable_parameter) i += 1 if control[i] == ",": i += 1 continue # "remaining" parameter if control[i] == "#": params.append(Directive.remaining_parameter) i += 1 if control[i] == ",": i += 1 continue break colon = atsign = False while i < end: if control[i] == ":": i += 1 if colon: raise FormatParseError(control, i, "too many colons") colon = True elif control[i] == "@": i += 1 if atsign: raise FormatParseError(control, i, "too many at-signs") atsign = True else: break char = control[i] i += 1 try: d = format_directives[char](params, colon, atsign, control, tilde, i, parent) except FormatError, e: raise FormatParseError(control, i, e.control, *e.args) except KeyError: raise FormatParseError(control, i, "unknown format directive") if isinstance(d, DelimitedDirective): for x in parse_control_string(control, i, d): try: d.append(x) except FormatError, e: if isinstance(x, Directive) and x is not d.delimiter: i += x.start raise FormatParseError(control, i, e.control, *e.args) i = d.end yield d if parent and d is parent.delimiter: return class Formatter(object): def __init__(self, control): if isinstance(control, basestring): self.directives = tuple(parse_control_string(control)) elif isinstance(control, (tuple, list)): self.directives = control self.need_prettyprinter = any([x.need_prettyprinter \ for x in self.directives \ if isinstance(x, Directive)]) self.need_charpos = self.need_prettyprinter or \ any([x.need_charpos \ for x in self.directives \ if isinstance(x, Directive)]) def __call__(self, stream, *args): if not isinstance(stream, PrettyPrinter) and self.need_prettyprinter: stream = PrettyPrinter(stream) elif not isinstance(stream, CharposStream) and self.need_charpos: stream = CharposStream(stream) if len(args) == 1 and isinstance(args[0], Arguments): args = args[0] else: args = Arguments(args) apply_directives(stream, self.directives, args) return args def prepare_directives(directives): return [(x, True) if isinstance(x, basestring) else (x.format, False) \ for x in directives] def fast_apply_directives(stream, write, directives, args): """Apply a list of prepared directives.""" for (x, string) in directives: if string: write(x) else: x(stream, args) def apply_directives(stream, directives, args): write = stream.write for x in directives: if isinstance(x, basestring): write(x) else: x.format(stream, args) def format(destination, control, *args): if destination is None: stream = StringIO() elif destination is True: stream = sys.stdout else: stream = destination f = control if isinstance(control, Formatter) else Formatter(control) try: f(stream, *args) except UpAndOut: pass if destination is None: str = stream.getvalue() stream.close() return str
{ "repo_name": "plotnick/prettyprinter", "path": "format.py", "copies": "1", "size": "37184", "license": "mit", "hash": -7743765008277030000, "line_mean": 33.145087236, "line_max": 81, "alpha_frac": 0.5354991394, "autogenerated": false, "ratio": 4.011218985976267, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5046718125376267, "avg_score": null, "num_lines": null }
"""An implementation of conlleval.pl https://www.clips.uantwerpen.be/conll2000/chunking/output.html Input is a conll file with the rightmost columns being gold and predicted tags in that order. Sentences are separated by a blank line. Some parts of the perl script are not replicated (this doesn't generate a latex table) but there are other improvements like it supports files in the `IOBES` format. The script produces the same output as conlleval.pl for BIO and IOB tagged file. When running on IOBES files it will produce the same F1 scores as if you converted the file to BIO and run conlleval.pl however the accuracy will be slightly different IOBES accuracy will always equal to or lower than BIO score. This difference is because if the error is on a B-, I-, or O token then the error will be in both IOBES and BIO. In the conversion from IOBES to BIO then S- is converted to B- and E- to I- if the IOBES was correct then they will be converted and will still be correct. If the token was wrong in that is said it was O or something then it will be wrong after the conversion too. If it was wrong in that the S- was tagged as B- or the E- was an I- (this is possible and a common error) then when the gold is changed these will become correct. So it is only possible that the conversion will make some answers correct. It won't make anything that was correct wrong. """ import sys import argparse from itertools import chain from eight_mile.utils import to_chunks, per_entity_f1, conlleval_output, read_conll_sentences def _read_conll_file(f, delim): """Read a golds and predictions out of a conll file. :param f: `file` The open file object. :param delim: `str` The symbol that separates columns in the file. :returns: `Tuple[List[List[str]], List[List[str]]]` The golds and the predictions. They are aligned lists and each element is a List of strings that are the list of tags. Note: the file should contain lines with items separated by $delimiter characters (default space). The final two items should contain the correct tag and the guessed tag in that order. Sentences should be separated from each other by empty lines. """ golds = [] preds = [] for lines in read_conll_sentences(f, delim=delim): golds.append([l[-2] for l in lines]) preds.append([l[-1] for l in lines]) return golds, preds def _get_accuracy(golds, preds): """Calculate the token level accuracy. :param golds: `List[List[str]]` The list of golds of each example. :param preds: `List[List[str]]` The list of predictions of each example. :returns: `Tuple[float, int]` The Accuracy and the total number of tokens. """ total = 0 correct = 0 for g, p in zip(chain(*golds), chain(*preds)): if g == p: correct += 1 total += 1 return correct / float(total) * 100, total def _get_entities(golds, preds, span_type="iobes", verbose=False): """ Convert the tags into sets of entities. :param golds: `List[List[str]]` The list of gold tags. :param preds: `List[List[str]]` The list of predicted tags. :param span_type: `str` The span labeling scheme used. :param verbose: `bool` Should warnings be printed when an illegal transistion is found. """ golds = [set(to_chunks(g, span_type, verbose)) for g in golds] preds = [set(to_chunks(p, span_type, verbose)) for p in preds] return golds, preds def main(): """Use as a cli tool like conlleval.pl""" usage = "usage: %(prog)s [--span_type {bio,iobes,iob}] [-d delimiterTag] [-v] < file" parser = argparse.ArgumentParser( description="Calculate Span level F1 from the CoNLL-2000 shared task.", usage=usage ) parser.add_argument( "--span_type", default="iobes", choices={"iobes", "iob", "bio"}, help="What tag annotation scheme is this file using.", ) parser.add_argument("--delimiterTag", "-d", help="The separator between items in the file.") parser.add_argument( "--verbose", "-v", action="store_true", help="Output warnings when there is an illegal transition." ) args = parser.parse_args() golds, preds = _read_conll_file(sys.stdin, args.delimiterTag) acc, tokens = _get_accuracy(golds, preds) golds, preds = _get_entities(golds, preds, args.span_type, args.verbose) metrics = per_entity_f1(golds, preds) metrics["acc"] = acc metrics["tokens"] = tokens print(conlleval_output(metrics)) if __name__ == "__main__": main()
{ "repo_name": "dpressel/baseline", "path": "layers/eight_mile/conlleval.py", "copies": "1", "size": "4594", "license": "apache-2.0", "hash": -235970400084821540, "line_mean": 38.947826087, "line_max": 107, "alpha_frac": 0.6850239443, "autogenerated": false, "ratio": 3.634493670886076, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9813872084730215, "avg_score": 0.001129106091172165, "num_lines": 115 }
# An implementation of Dartmouth BASIC (1964) from ply import * keywords = ( 'LET','READ','DATA','PRINT','GOTO','IF','THEN','FOR','NEXT','TO','STEP', 'END','STOP','DEF','GOSUB','DIM','REM','RETURN','RUN','LIST','NEW', ) tokens = keywords + ( 'EQUALS','PLUS','MINUS','TIMES','DIVIDE','POWER', 'LPAREN','RPAREN','LT','LE','GT','GE','NE', 'COMMA','SEMI', 'INTEGER','FLOAT', 'STRING', 'ID','NEWLINE' ) t_ignore = ' \t' def t_REM(t): r'REM .*' return t def t_ID(t): r'[A-Z][A-Z0-9]*' if t.value in keywords: t.type = t.value return t t_EQUALS = r'=' t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_POWER = r'\^' t_DIVIDE = r'/' t_LPAREN = r'\(' t_RPAREN = r'\)' t_LT = r'<' t_LE = r'<=' t_GT = r'>' t_GE = r'>=' t_NE = r'<>' t_COMMA = r'\,' t_SEMI = r';' t_INTEGER = r'\d+' t_FLOAT = r'((\d*\.\d+)(E[\+-]?\d+)?|([1-9]\d*E[\+-]?\d+))' t_STRING = r'\".*?\"' def t_NEWLINE(t): r'\n' t.lexer.lineno += 1 return t def t_error(t): print("Illegal character %s" % t.value[0]) t.lexer.skip(1) lex.lex(debug=0)
{ "repo_name": "eepalms/gem5-newcache", "path": "ext/ply/example/BASIC/basiclex.py", "copies": "166", "size": "1177", "license": "bsd-3-clause", "hash": -7429442759498911000, "line_mean": 14.9054054054, "line_max": 76, "alpha_frac": 0.4545454545, "autogenerated": false, "ratio": 2.3777777777777778, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0524806162679187, "num_lines": 74 }
# An implementation of Dartmouth BASIC (1964) # from ply import * import basiclex tokens = basiclex.tokens precedence = ( ('left', 'PLUS','MINUS'), ('left', 'TIMES','DIVIDE'), ('left', 'POWER'), ('right','UMINUS') ) #### A BASIC program is a series of statements. We represent the program as a #### dictionary of tuples indexed by line number. def p_program(p): '''program : program statement | statement''' if len(p) == 2 and p[1]: p[0] = { } line,stat = p[1] p[0][line] = stat elif len(p) ==3: p[0] = p[1] if not p[0]: p[0] = { } if p[2]: line,stat = p[2] p[0][line] = stat #### This catch-all rule is used for any catastrophic errors. In this case, #### we simply return nothing def p_program_error(p): '''program : error''' p[0] = None p.parser.error = 1 #### Format of all BASIC statements. def p_statement(p): '''statement : INTEGER command NEWLINE''' if isinstance(p[2],str): print("%s %s %s" % (p[2],"AT LINE", p[1])) p[0] = None p.parser.error = 1 else: lineno = int(p[1]) p[0] = (lineno,p[2]) #### Interactive statements. def p_statement_interactive(p): '''statement : RUN NEWLINE | LIST NEWLINE | NEW NEWLINE''' p[0] = (0, (p[1],0)) #### Blank line number def p_statement_blank(p): '''statement : INTEGER NEWLINE''' p[0] = (0,('BLANK',int(p[1]))) #### Error handling for malformed statements def p_statement_bad(p): '''statement : INTEGER error NEWLINE''' print("MALFORMED STATEMENT AT LINE %s" % p[1]) p[0] = None p.parser.error = 1 #### Blank line def p_statement_newline(p): '''statement : NEWLINE''' p[0] = None #### LET statement def p_command_let(p): '''command : LET variable EQUALS expr''' p[0] = ('LET',p[2],p[4]) def p_command_let_bad(p): '''command : LET variable EQUALS error''' p[0] = "BAD EXPRESSION IN LET" #### READ statement def p_command_read(p): '''command : READ varlist''' p[0] = ('READ',p[2]) def p_command_read_bad(p): '''command : READ error''' p[0] = "MALFORMED VARIABLE LIST IN READ" #### DATA statement def p_command_data(p): '''command : DATA numlist''' p[0] = ('DATA',p[2]) def p_command_data_bad(p): '''command : DATA error''' p[0] = "MALFORMED NUMBER LIST IN DATA" #### PRINT statement def p_command_print(p): '''command : PRINT plist optend''' p[0] = ('PRINT',p[2],p[3]) def p_command_print_bad(p): '''command : PRINT error''' p[0] = "MALFORMED PRINT STATEMENT" #### Optional ending on PRINT. Either a comma (,) or semicolon (;) def p_optend(p): '''optend : COMMA | SEMI |''' if len(p) == 2: p[0] = p[1] else: p[0] = None #### PRINT statement with no arguments def p_command_print_empty(p): '''command : PRINT''' p[0] = ('PRINT',[],None) #### GOTO statement def p_command_goto(p): '''command : GOTO INTEGER''' p[0] = ('GOTO',int(p[2])) def p_command_goto_bad(p): '''command : GOTO error''' p[0] = "INVALID LINE NUMBER IN GOTO" #### IF-THEN statement def p_command_if(p): '''command : IF relexpr THEN INTEGER''' p[0] = ('IF',p[2],int(p[4])) def p_command_if_bad(p): '''command : IF error THEN INTEGER''' p[0] = "BAD RELATIONAL EXPRESSION" def p_command_if_bad2(p): '''command : IF relexpr THEN error''' p[0] = "INVALID LINE NUMBER IN THEN" #### FOR statement def p_command_for(p): '''command : FOR ID EQUALS expr TO expr optstep''' p[0] = ('FOR',p[2],p[4],p[6],p[7]) def p_command_for_bad_initial(p): '''command : FOR ID EQUALS error TO expr optstep''' p[0] = "BAD INITIAL VALUE IN FOR STATEMENT" def p_command_for_bad_final(p): '''command : FOR ID EQUALS expr TO error optstep''' p[0] = "BAD FINAL VALUE IN FOR STATEMENT" def p_command_for_bad_step(p): '''command : FOR ID EQUALS expr TO expr STEP error''' p[0] = "MALFORMED STEP IN FOR STATEMENT" #### Optional STEP qualifier on FOR statement def p_optstep(p): '''optstep : STEP expr | empty''' if len(p) == 3: p[0] = p[2] else: p[0] = None #### NEXT statement def p_command_next(p): '''command : NEXT ID''' p[0] = ('NEXT',p[2]) def p_command_next_bad(p): '''command : NEXT error''' p[0] = "MALFORMED NEXT" #### END statement def p_command_end(p): '''command : END''' p[0] = ('END',) #### REM statement def p_command_rem(p): '''command : REM''' p[0] = ('REM',p[1]) #### STOP statement def p_command_stop(p): '''command : STOP''' p[0] = ('STOP',) #### DEF statement def p_command_def(p): '''command : DEF ID LPAREN ID RPAREN EQUALS expr''' p[0] = ('FUNC',p[2],p[4],p[7]) def p_command_def_bad_rhs(p): '''command : DEF ID LPAREN ID RPAREN EQUALS error''' p[0] = "BAD EXPRESSION IN DEF STATEMENT" def p_command_def_bad_arg(p): '''command : DEF ID LPAREN error RPAREN EQUALS expr''' p[0] = "BAD ARGUMENT IN DEF STATEMENT" #### GOSUB statement def p_command_gosub(p): '''command : GOSUB INTEGER''' p[0] = ('GOSUB',int(p[2])) def p_command_gosub_bad(p): '''command : GOSUB error''' p[0] = "INVALID LINE NUMBER IN GOSUB" #### RETURN statement def p_command_return(p): '''command : RETURN''' p[0] = ('RETURN',) #### DIM statement def p_command_dim(p): '''command : DIM dimlist''' p[0] = ('DIM',p[2]) def p_command_dim_bad(p): '''command : DIM error''' p[0] = "MALFORMED VARIABLE LIST IN DIM" #### List of variables supplied to DIM statement def p_dimlist(p): '''dimlist : dimlist COMMA dimitem | dimitem''' if len(p) == 4: p[0] = p[1] p[0].append(p[3]) else: p[0] = [p[1]] #### DIM items def p_dimitem_single(p): '''dimitem : ID LPAREN INTEGER RPAREN''' p[0] = (p[1],eval(p[3]),0) def p_dimitem_double(p): '''dimitem : ID LPAREN INTEGER COMMA INTEGER RPAREN''' p[0] = (p[1],eval(p[3]),eval(p[5])) #### Arithmetic expressions def p_expr_binary(p): '''expr : expr PLUS expr | expr MINUS expr | expr TIMES expr | expr DIVIDE expr | expr POWER expr''' p[0] = ('BINOP',p[2],p[1],p[3]) def p_expr_number(p): '''expr : INTEGER | FLOAT''' p[0] = ('NUM',eval(p[1])) def p_expr_variable(p): '''expr : variable''' p[0] = ('VAR',p[1]) def p_expr_group(p): '''expr : LPAREN expr RPAREN''' p[0] = ('GROUP',p[2]) def p_expr_unary(p): '''expr : MINUS expr %prec UMINUS''' p[0] = ('UNARY','-',p[2]) #### Relational expressions def p_relexpr(p): '''relexpr : expr LT expr | expr LE expr | expr GT expr | expr GE expr | expr EQUALS expr | expr NE expr''' p[0] = ('RELOP',p[2],p[1],p[3]) #### Variables def p_variable(p): '''variable : ID | ID LPAREN expr RPAREN | ID LPAREN expr COMMA expr RPAREN''' if len(p) == 2: p[0] = (p[1],None,None) elif len(p) == 5: p[0] = (p[1],p[3],None) else: p[0] = (p[1],p[3],p[5]) #### Builds a list of variable targets as a Python list def p_varlist(p): '''varlist : varlist COMMA variable | variable''' if len(p) > 2: p[0] = p[1] p[0].append(p[3]) else: p[0] = [p[1]] #### Builds a list of numbers as a Python list def p_numlist(p): '''numlist : numlist COMMA number | number''' if len(p) > 2: p[0] = p[1] p[0].append(p[3]) else: p[0] = [p[1]] #### A number. May be an integer or a float def p_number(p): '''number : INTEGER | FLOAT''' p[0] = eval(p[1]) #### A signed number. def p_number_signed(p): '''number : MINUS INTEGER | MINUS FLOAT''' p[0] = eval("-"+p[2]) #### List of targets for a print statement #### Returns a list of tuples (label,expr) def p_plist(p): '''plist : plist COMMA pitem | pitem''' if len(p) > 3: p[0] = p[1] p[0].append(p[3]) else: p[0] = [p[1]] def p_item_string(p): '''pitem : STRING''' p[0] = (p[1][1:-1],None) def p_item_string_expr(p): '''pitem : STRING expr''' p[0] = (p[1][1:-1],p[2]) def p_item_expr(p): '''pitem : expr''' p[0] = ("",p[1]) #### Empty def p_empty(p): '''empty : ''' #### Catastrophic error handler def p_error(p): if not p: print("SYNTAX ERROR AT EOF") bparser = yacc.yacc() def parse(data,debug=0): bparser.error = 0 p = bparser.parse(data,debug=debug) if bparser.error: return None return p
{ "repo_name": "Dexhub/MTX", "path": "ext/ply/example/BASIC/basparse.py", "copies": "166", "size": "8899", "license": "bsd-3-clause", "hash": 22320524706773372, "line_mean": 19.9882075472, "line_max": 78, "alpha_frac": 0.5289358355, "autogenerated": false, "ratio": 2.8883479389808504, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
# An implementation of Dartmouth BASIC (1964) # from ply import * import basiclex tokens = basiclex.tokens precedence = ( ('left', 'PLUS', 'MINUS'), ('left', 'TIMES', 'DIVIDE'), ('left', 'POWER'), ('right', 'UMINUS') ) # A BASIC program is a series of statements. We represent the program as a # dictionary of tuples indexed by line number. def p_program(p): '''program : program statement | statement''' if len(p) == 2 and p[1]: p[0] = {} line, stat = p[1] p[0][line] = stat elif len(p) == 3: p[0] = p[1] if not p[0]: p[0] = {} if p[2]: line, stat = p[2] p[0][line] = stat # This catch-all rule is used for any catastrophic errors. In this case, # we simply return nothing def p_program_error(p): '''program : error''' p[0] = None p.parser.error = 1 # Format of all BASIC statements. def p_statement(p): '''statement : INTEGER command NEWLINE''' if isinstance(p[2], str): print("%s %s %s" % (p[2], "AT LINE", p[1])) p[0] = None p.parser.error = 1 else: lineno = int(p[1]) p[0] = (lineno, p[2]) # Interactive statements. def p_statement_interactive(p): '''statement : RUN NEWLINE | LIST NEWLINE | NEW NEWLINE''' p[0] = (0, (p[1], 0)) # Blank line number def p_statement_blank(p): '''statement : INTEGER NEWLINE''' p[0] = (0, ('BLANK', int(p[1]))) # Error handling for malformed statements def p_statement_bad(p): '''statement : INTEGER error NEWLINE''' print("MALFORMED STATEMENT AT LINE %s" % p[1]) p[0] = None p.parser.error = 1 # Blank line def p_statement_newline(p): '''statement : NEWLINE''' p[0] = None # LET statement def p_command_let(p): '''command : LET variable EQUALS expr''' p[0] = ('LET', p[2], p[4]) def p_command_let_bad(p): '''command : LET variable EQUALS error''' p[0] = "BAD EXPRESSION IN LET" # READ statement def p_command_read(p): '''command : READ varlist''' p[0] = ('READ', p[2]) def p_command_read_bad(p): '''command : READ error''' p[0] = "MALFORMED VARIABLE LIST IN READ" # DATA statement def p_command_data(p): '''command : DATA numlist''' p[0] = ('DATA', p[2]) def p_command_data_bad(p): '''command : DATA error''' p[0] = "MALFORMED NUMBER LIST IN DATA" # PRINT statement def p_command_print(p): '''command : PRINT plist optend''' p[0] = ('PRINT', p[2], p[3]) def p_command_print_bad(p): '''command : PRINT error''' p[0] = "MALFORMED PRINT STATEMENT" # Optional ending on PRINT. Either a comma (,) or semicolon (;) def p_optend(p): '''optend : COMMA | SEMI |''' if len(p) == 2: p[0] = p[1] else: p[0] = None # PRINT statement with no arguments def p_command_print_empty(p): '''command : PRINT''' p[0] = ('PRINT', [], None) # GOTO statement def p_command_goto(p): '''command : GOTO INTEGER''' p[0] = ('GOTO', int(p[2])) def p_command_goto_bad(p): '''command : GOTO error''' p[0] = "INVALID LINE NUMBER IN GOTO" # IF-THEN statement def p_command_if(p): '''command : IF relexpr THEN INTEGER''' p[0] = ('IF', p[2], int(p[4])) def p_command_if_bad(p): '''command : IF error THEN INTEGER''' p[0] = "BAD RELATIONAL EXPRESSION" def p_command_if_bad2(p): '''command : IF relexpr THEN error''' p[0] = "INVALID LINE NUMBER IN THEN" # FOR statement def p_command_for(p): '''command : FOR ID EQUALS expr TO expr optstep''' p[0] = ('FOR', p[2], p[4], p[6], p[7]) def p_command_for_bad_initial(p): '''command : FOR ID EQUALS error TO expr optstep''' p[0] = "BAD INITIAL VALUE IN FOR STATEMENT" def p_command_for_bad_final(p): '''command : FOR ID EQUALS expr TO error optstep''' p[0] = "BAD FINAL VALUE IN FOR STATEMENT" def p_command_for_bad_step(p): '''command : FOR ID EQUALS expr TO expr STEP error''' p[0] = "MALFORMED STEP IN FOR STATEMENT" # Optional STEP qualifier on FOR statement def p_optstep(p): '''optstep : STEP expr | empty''' if len(p) == 3: p[0] = p[2] else: p[0] = None # NEXT statement def p_command_next(p): '''command : NEXT ID''' p[0] = ('NEXT', p[2]) def p_command_next_bad(p): '''command : NEXT error''' p[0] = "MALFORMED NEXT" # END statement def p_command_end(p): '''command : END''' p[0] = ('END',) # REM statement def p_command_rem(p): '''command : REM''' p[0] = ('REM', p[1]) # STOP statement def p_command_stop(p): '''command : STOP''' p[0] = ('STOP',) # DEF statement def p_command_def(p): '''command : DEF ID LPAREN ID RPAREN EQUALS expr''' p[0] = ('FUNC', p[2], p[4], p[7]) def p_command_def_bad_rhs(p): '''command : DEF ID LPAREN ID RPAREN EQUALS error''' p[0] = "BAD EXPRESSION IN DEF STATEMENT" def p_command_def_bad_arg(p): '''command : DEF ID LPAREN error RPAREN EQUALS expr''' p[0] = "BAD ARGUMENT IN DEF STATEMENT" # GOSUB statement def p_command_gosub(p): '''command : GOSUB INTEGER''' p[0] = ('GOSUB', int(p[2])) def p_command_gosub_bad(p): '''command : GOSUB error''' p[0] = "INVALID LINE NUMBER IN GOSUB" # RETURN statement def p_command_return(p): '''command : RETURN''' p[0] = ('RETURN',) # DIM statement def p_command_dim(p): '''command : DIM dimlist''' p[0] = ('DIM', p[2]) def p_command_dim_bad(p): '''command : DIM error''' p[0] = "MALFORMED VARIABLE LIST IN DIM" # List of variables supplied to DIM statement def p_dimlist(p): '''dimlist : dimlist COMMA dimitem | dimitem''' if len(p) == 4: p[0] = p[1] p[0].append(p[3]) else: p[0] = [p[1]] # DIM items def p_dimitem_single(p): '''dimitem : ID LPAREN INTEGER RPAREN''' p[0] = (p[1], eval(p[3]), 0) def p_dimitem_double(p): '''dimitem : ID LPAREN INTEGER COMMA INTEGER RPAREN''' p[0] = (p[1], eval(p[3]), eval(p[5])) # Arithmetic expressions def p_expr_binary(p): '''expr : expr PLUS expr | expr MINUS expr | expr TIMES expr | expr DIVIDE expr | expr POWER expr''' p[0] = ('BINOP', p[2], p[1], p[3]) def p_expr_number(p): '''expr : INTEGER | FLOAT''' p[0] = ('NUM', eval(p[1])) def p_expr_variable(p): '''expr : variable''' p[0] = ('VAR', p[1]) def p_expr_group(p): '''expr : LPAREN expr RPAREN''' p[0] = ('GROUP', p[2]) def p_expr_unary(p): '''expr : MINUS expr %prec UMINUS''' p[0] = ('UNARY', '-', p[2]) # Relational expressions def p_relexpr(p): '''relexpr : expr LT expr | expr LE expr | expr GT expr | expr GE expr | expr EQUALS expr | expr NE expr''' p[0] = ('RELOP', p[2], p[1], p[3]) # Variables def p_variable(p): '''variable : ID | ID LPAREN expr RPAREN | ID LPAREN expr COMMA expr RPAREN''' if len(p) == 2: p[0] = (p[1], None, None) elif len(p) == 5: p[0] = (p[1], p[3], None) else: p[0] = (p[1], p[3], p[5]) # Builds a list of variable targets as a Python list def p_varlist(p): '''varlist : varlist COMMA variable | variable''' if len(p) > 2: p[0] = p[1] p[0].append(p[3]) else: p[0] = [p[1]] # Builds a list of numbers as a Python list def p_numlist(p): '''numlist : numlist COMMA number | number''' if len(p) > 2: p[0] = p[1] p[0].append(p[3]) else: p[0] = [p[1]] # A number. May be an integer or a float def p_number(p): '''number : INTEGER | FLOAT''' p[0] = eval(p[1]) # A signed number. def p_number_signed(p): '''number : MINUS INTEGER | MINUS FLOAT''' p[0] = eval("-" + p[2]) # List of targets for a print statement # Returns a list of tuples (label,expr) def p_plist(p): '''plist : plist COMMA pitem | pitem''' if len(p) > 3: p[0] = p[1] p[0].append(p[3]) else: p[0] = [p[1]] def p_item_string(p): '''pitem : STRING''' p[0] = (p[1][1:-1], None) def p_item_string_expr(p): '''pitem : STRING expr''' p[0] = (p[1][1:-1], p[2]) def p_item_expr(p): '''pitem : expr''' p[0] = ("", p[1]) # Empty def p_empty(p): '''empty : ''' # Catastrophic error handler def p_error(p): if not p: print("SYNTAX ERROR AT EOF") bparser = yacc.yacc() def parse(data, debug=0): bparser.error = 0 p = bparser.parse(data, debug=debug) if bparser.error: return None return p
{ "repo_name": "cloudera/hue", "path": "desktop/core/ext-py/ply-3.11/example/BASIC/basparse.py", "copies": "9", "size": "8850", "license": "apache-2.0", "hash": -816632391361357700, "line_mean": 17.6708860759, "line_max": 75, "alpha_frac": 0.5318644068, "autogenerated": false, "ratio": 2.872444011684518, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7904308418484518, "avg_score": null, "num_lines": null }
# An implementation of Dartmouth BASIC (1964) # import sys sys.path.insert(0,"../..") if sys.version_info[0] >= 3: raw_input = input import basiclex import basparse import basinterp # If a filename has been specified, we try to run it. # If a runtime error occurs, we bail out and enter # interactive mode below if len(sys.argv) == 2: data = open(sys.argv[1]).read() prog = basparse.parse(data) if not prog: raise SystemExit b = basinterp.BasicInterpreter(prog) try: b.run() raise SystemExit except RuntimeError: pass else: b = basinterp.BasicInterpreter({}) # Interactive mode. This incrementally adds/deletes statements # from the program stored in the BasicInterpreter object. In # addition, special commands 'NEW','LIST',and 'RUN' are added. # Specifying a line number with no code deletes that line from # the program. while 1: try: line = raw_input("[BASIC] ") except EOFError: raise SystemExit if not line: continue line += "\n" prog = basparse.parse(line) if not prog: continue keys = list(prog) if keys[0] > 0: b.add_statements(prog) else: stat = prog[keys[0]] if stat[0] == 'RUN': try: b.run() except RuntimeError: pass elif stat[0] == 'LIST': b.list() elif stat[0] == 'BLANK': b.del_line(stat[1]) elif stat[0] == 'NEW': b.new()
{ "repo_name": "KuroeKurose/gem5", "path": "ext/ply/example/BASIC/basic.py", "copies": "166", "size": "1533", "license": "bsd-3-clause", "hash": -8141337596046289000, "line_mean": 20.5915492958, "line_max": 63, "alpha_frac": 0.5792563601, "autogenerated": false, "ratio": 3.6070588235294117, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
# An implementation of Dartmouth BASIC (1964) # import sys sys.path.insert(0, "../..") if sys.version_info[0] >= 3: raw_input = input import logging logging.basicConfig( level=logging.INFO, filename="parselog.txt", filemode="w" ) log = logging.getLogger() import basiclex import basparse import basinterp # If a filename has been specified, we try to run it. # If a runtime error occurs, we bail out and enter # interactive mode below if len(sys.argv) == 2: data = open(sys.argv[1]).read() prog = basparse.parse(data, debug=log) if not prog: raise SystemExit b = basinterp.BasicInterpreter(prog) try: b.run() raise SystemExit except RuntimeError: pass else: b = basinterp.BasicInterpreter({}) # Interactive mode. This incrementally adds/deletes statements # from the program stored in the BasicInterpreter object. In # addition, special commands 'NEW','LIST',and 'RUN' are added. # Specifying a line number with no code deletes that line from # the program. while 1: try: line = raw_input("[BASIC] ") except EOFError: raise SystemExit if not line: continue line += "\n" prog = basparse.parse(line, debug=log) if not prog: continue keys = list(prog) if keys[0] > 0: b.add_statements(prog) else: stat = prog[keys[0]] if stat[0] == 'RUN': try: b.run() except RuntimeError: pass elif stat[0] == 'LIST': b.list() elif stat[0] == 'BLANK': b.del_line(stat[1]) elif stat[0] == 'NEW': b.new()
{ "repo_name": "todaychi/hue", "path": "desktop/core/ext-py/ply-3.9/example/BASIC/basiclog.py", "copies": "10", "size": "1679", "license": "apache-2.0", "hash": -5176870297474578000, "line_mean": 22, "line_max": 63, "alpha_frac": 0.5944014294, "autogenerated": false, "ratio": 3.564755838641189, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.003431372549019608, "num_lines": 73 }
"""An implementation of Decaying Dropout Layer.""" import tensorflow as tf from keras import backend as K from keras.engine import Layer class DecayingDropoutLayer(Layer): """ Layer that processes dropout with exponential decayed keep rate during training. :param initial_keep_rate: the initial keep rate of decaying dropout. :param decay_interval: the decay interval of decaying dropout. :param decay_rate: the decay rate of decaying dropout. :param noise_shape: a 1D integer tensor representing the shape of the binary dropout mask that will be multiplied with the input. :param seed: a python integer to use as random seed. :param kwargs: standard layer keyword arguments. Examples: >>> import matchzoo as mz >>> layer = mz.contrib.layers.DecayingDropoutLayer( ... initial_keep_rate=1.0, ... decay_interval=10000, ... decay_rate=0.977, ... ) >>> num_batch, num_dim =5, 10 >>> layer.build([num_batch, num_dim]) """ def __init__(self, initial_keep_rate: float = 1.0, decay_interval: int = 10000, decay_rate: float = 0.977, noise_shape=None, seed=None, **kwargs): """:class: 'DecayingDropoutLayer' constructor.""" super(DecayingDropoutLayer, self).__init__(**kwargs) self._iterations = None self._initial_keep_rate = initial_keep_rate self._decay_interval = decay_interval self._decay_rate = min(1.0, max(0.0, decay_rate)) self._noise_shape = noise_shape self._seed = seed def _get_noise_shape(self, inputs): if self._noise_shape is None: return self._noise_shape symbolic_shape = tf.shape(inputs) noise_shape = [symbolic_shape[axis] if shape is None else shape for axis, shape in enumerate(self._noise_shape)] return tuple(noise_shape) def build(self, input_shape): """ Build the layer. :param input_shape: the shape of the input tensor, for DecayingDropoutLayer we need one input tensor. """ self._iterations = self.add_weight(name='iterations', shape=(1,), dtype=K.floatx(), initializer='zeros', trainable=False) super(DecayingDropoutLayer, self).build(input_shape) def call(self, inputs, training=None): """ The computation logic of DecayingDropoutLayer. :param inputs: an input tensor. """ noise_shape = self._get_noise_shape(inputs) t = tf.cast(self._iterations, K.floatx()) + 1 p = t / float(self._decay_interval) keep_rate = self._initial_keep_rate * tf.pow(self._decay_rate, p) def dropped_inputs(): update_op = self._iterations.assign_add([1]) with tf.control_dependencies([update_op]): return tf.nn.dropout(inputs, 1 - keep_rate[0], noise_shape, seed=self._seed) return K.in_train_phase(dropped_inputs, inputs, training=training) def get_config(self): """Get the config dict of DecayingDropoutLayer.""" config = {'initial_keep_rate': self._initial_keep_rate, 'decay_interval': self._decay_interval, 'decay_rate': self._decay_rate, 'noise_shape': self._noise_shape, 'seed': self._seed} base_config = super(DecayingDropoutLayer, self).get_config() return dict(list(base_config.items()) + list(config.items()))
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/contrib/layers/decaying_dropout_layer.py", "copies": "1", "size": "3805", "license": "apache-2.0", "hash": 3174055692180741600, "line_mean": 37.4343434343, "line_max": 75, "alpha_frac": 0.5684625493, "autogenerated": false, "ratio": 4.223085460599334, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5291548009899334, "avg_score": null, "num_lines": null }
"""An implementation of DRMM Model.""" import typing import keras import keras.backend as K import tensorflow as tf from matchzoo.engine.base_model import BaseModel from matchzoo.engine.param import Param from matchzoo.engine.param_table import ParamTable class DRMM(BaseModel): """ DRMM Model. Examples: >>> model = DRMM() >>> model.params['mlp_num_layers'] = 1 >>> model.params['mlp_num_units'] = 5 >>> model.params['mlp_num_fan_out'] = 1 >>> model.params['mlp_activation_func'] = 'tanh' >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build() >>> model.compile() """ @classmethod def get_default_params(cls) -> ParamTable: """:return: model default parameters.""" params = super().get_default_params(with_embedding=True, with_multi_layer_perceptron=True) params.add(Param(name='mask_value', value=-1, desc="The value to be masked from inputs.")) params['optimizer'] = 'adam' params['input_shapes'] = [(5,), (5, 30,)] return params def build(self): """Build model structure.""" # Scalar dimensions referenced here: # B = batch size (number of sequences) # D = embedding size # L = `input_left` sequence length # R = `input_right` sequence length # H = histogram size # K = size of top-k # Left input and right input. # query: shape = [B, L] # doc: shape = [B, L, H] # Note here, the doc is the matching histogram between original query # and original document. query = keras.layers.Input( name='text_left', shape=self._params['input_shapes'][0] ) match_hist = keras.layers.Input( name='match_histogram', shape=self._params['input_shapes'][1] ) embedding = self._make_embedding_layer() # Process left input. # shape = [B, L, D] embed_query = embedding(query) # shape = [B, L] atten_mask = tf.not_equal(query, self._params['mask_value']) # shape = [B, L] atten_mask = tf.cast(atten_mask, K.floatx()) # shape = [B, L, D] atten_mask = tf.expand_dims(atten_mask, axis=2) # shape = [B, L, D] attention_probs = self.attention_layer(embed_query, atten_mask) # Process right input. # shape = [B, L, 1] dense_output = self._make_multi_layer_perceptron_layer()(match_hist) # shape = [B, 1, 1] dot_score = keras.layers.Dot(axes=[1, 1])( [attention_probs, dense_output]) flatten_score = keras.layers.Flatten()(dot_score) x_out = self._make_output_layer()(flatten_score) self._backend = keras.Model(inputs=[query, match_hist], outputs=x_out) @classmethod def attention_layer(cls, attention_input: typing.Any, attention_mask: typing.Any = None ) -> keras.layers.Layer: """ Performs attention on the input. :param attention_input: The input tensor for attention layer. :param attention_mask: A tensor to mask the invalid values. :return: The masked output tensor. """ # shape = [B, L, 1] dense_input = keras.layers.Dense(1, use_bias=False)(attention_input) if attention_mask is not None: # Since attention_mask is 1.0 for positions we want to attend and # 0.0 for masked positions, this operation will create a tensor # which is 0.0 for positions we want to attend and -10000.0 for # masked positions. # shape = [B, L, 1] dense_input = keras.layers.Lambda( lambda x: x + (1.0 - attention_mask) * -10000.0, name="attention_mask" )(dense_input) # shape = [B, L, 1] attention_probs = keras.layers.Lambda( lambda x: tf.nn.softmax(x, axis=1), output_shape=lambda s: (s[0], s[1], s[2]), name="attention_probs" )(dense_input) return attention_probs
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/models/drmm.py", "copies": "1", "size": "4248", "license": "apache-2.0", "hash": -914664458887159400, "line_mean": 34.1074380165, "line_max": 78, "alpha_frac": 0.5550847458, "autogenerated": false, "ratio": 3.8132854578096946, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9868370203609695, "avg_score": 0, "num_lines": 121 }
"""An implementation of DRMMTKS Model.""" import typing import keras import tensorflow as tf from matchzoo.engine.base_model import BaseModel from matchzoo.engine.param import Param from matchzoo.engine.param_table import ParamTable from matchzoo.engine import hyper_spaces class DRMMTKS(BaseModel): """ DRMMTKS Model. Examples: >>> model = DRMMTKS() >>> model.params['embedding_input_dim'] = 10000 >>> model.params['embedding_output_dim'] = 100 >>> model.params['top_k'] = 20 >>> model.params['mlp_num_layers'] = 1 >>> model.params['mlp_num_units'] = 5 >>> model.params['mlp_num_fan_out'] = 1 >>> model.params['mlp_activation_func'] = 'tanh' >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build() """ @classmethod def get_default_params(cls) -> ParamTable: """:return: model default parameters.""" params = super().get_default_params( with_embedding=True, with_multi_layer_perceptron=True ) params.add(Param(name='mask_value', value=-1, desc="The value to be masked from inputs.")) params['input_shapes'] = [(5,), (300,)] params.add(Param( 'top_k', value=10, hyper_space=hyper_spaces.quniform(low=2, high=100), desc="Size of top-k pooling layer." )) return params def build(self): """Build model structure.""" # Scalar dimensions referenced here: # B = batch size (number of sequences) # D = embedding size # L = `input_left` sequence length # R = `input_right` sequence length # K = size of top-k # Left input and right input. # shape = [B, L] # shape = [B, R] query, doc = self._make_inputs() embedding = self._make_embedding_layer() # Process left input. # shape = [B, L, D] embed_query = embedding(query) # shape = [B, R, D] embed_doc = embedding(doc) # shape = [B, L] atten_mask = tf.not_equal(query, self._params['mask_value']) # shape = [B, L] atten_mask = tf.cast(atten_mask, keras.backend.floatx()) # shape = [B, L, 1] atten_mask = tf.expand_dims(atten_mask, axis=2) # shape = [B, L, 1] attention_probs = self.attention_layer(embed_query, atten_mask) # Matching histogram of top-k # shape = [B, L, R] matching_matrix = keras.layers.Dot(axes=[2, 2], normalize=True)( [embed_query, embed_doc]) # shape = [B, L, K] effective_top_k = min(self._params['top_k'], self.params['input_shapes'][0][0], self.params['input_shapes'][1][0]) matching_topk = keras.layers.Lambda( lambda x: tf.nn.top_k(x, k=effective_top_k, sorted=True)[0] )(matching_matrix) # Process right input. # shape = [B, L, 1] dense_output = self._make_multi_layer_perceptron_layer()(matching_topk) # shape = [B, 1, 1] dot_score = keras.layers.Dot(axes=[1, 1])( [attention_probs, dense_output]) flatten_score = keras.layers.Flatten()(dot_score) x_out = self._make_output_layer()(flatten_score) self._backend = keras.Model(inputs=[query, doc], outputs=x_out) @classmethod def attention_layer(cls, attention_input: typing.Any, attention_mask: typing.Any = None ) -> keras.layers.Layer: """ Performs attention on the input. :param attention_input: The input tensor for attention layer. :param attention_mask: A tensor to mask the invalid values. :return: The masked output tensor. """ # shape = [B, L, 1] dense_input = keras.layers.Dense(1, use_bias=False)(attention_input) if attention_mask is not None: # Since attention_mask is 1.0 for positions we want to attend and # 0.0 for masked positions, this operation will create a tensor # which is 0.0 for positions we want to attend and -10000.0 for # masked positions. # shape = [B, L, 1] dense_input = keras.layers.Lambda( lambda x: x + (1.0 - attention_mask) * -10000.0, name="attention_mask" )(dense_input) # shape = [B, L, 1] attention_probs = keras.layers.Lambda( lambda x: tf.nn.softmax(x, axis=1), output_shape=lambda s: (s[0], s[1], s[2]), name="attention_probs" )(dense_input) return attention_probs
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/models/drmmtks.py", "copies": "1", "size": "4766", "license": "apache-2.0", "hash": 1068782582329549000, "line_mean": 34.5671641791, "line_max": 79, "alpha_frac": 0.5497272346, "autogenerated": false, "ratio": 3.6974398758727696, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.974716711047277, "avg_score": 0, "num_lines": 134 }
"""An implementation of DSSM, Deep Structured Semantic Model.""" from keras.models import Model from keras.layers import Input, Dot from matchzoo.engine.param_table import ParamTable from matchzoo.engine.base_model import BaseModel from matchzoo import preprocessors class DSSM(BaseModel): """ Deep structured semantic model. Examples: >>> model = DSSM() >>> model.params['mlp_num_layers'] = 3 >>> model.params['mlp_num_units'] = 300 >>> model.params['mlp_num_fan_out'] = 128 >>> model.params['mlp_activation_func'] = 'relu' >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build() """ @classmethod def get_default_params(cls) -> ParamTable: """:return: model default parameters.""" params = super().get_default_params(with_multi_layer_perceptron=True) return params def build(self): """ Build model structure. DSSM use Siamese arthitecture. """ dim_triletter = self._params['input_shapes'][0][0] input_shape = (dim_triletter,) base_network = self._make_multi_layer_perceptron_layer() # Left input and right input. input_left = Input(name='text_left', shape=input_shape) input_right = Input(name='text_right', shape=input_shape) # Process left & right input. x = [base_network(input_left), base_network(input_right)] # Dot product with cosine similarity. x = Dot(axes=[1, 1], normalize=True)(x) x_out = self._make_output_layer()(x) self._backend = Model( inputs=[input_left, input_right], outputs=x_out) @classmethod def get_default_preprocessor(cls): """:return: Default preprocessor.""" return preprocessors.DSSMPreprocessor()
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/models/dssm.py", "copies": "1", "size": "1847", "license": "apache-2.0", "hash": 3212837813646784000, "line_mean": 31.9821428571, "line_max": 77, "alpha_frac": 0.6128857607, "autogenerated": false, "ratio": 3.7540650406504064, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9866950801350406, "avg_score": 0, "num_lines": 56 }
"""An implementation of EncodingModule for DIIN model.""" import tensorflow as tf from keras import backend as K from keras.engine import Layer from matchzoo.contrib.layers import DecayingDropoutLayer class EncodingLayer(Layer): """ Apply a self-attention layer and a semantic composite fuse gate to compute the encoding result of one tensor. :param initial_keep_rate: the initial_keep_rate parameter of DecayingDropoutLayer. :param decay_interval: the decay_interval parameter of DecayingDropoutLayer. :param decay_rate: the decay_rate parameter of DecayingDropoutLayer. :param kwargs: standard layer keyword arguments. Example: >>> import matchzoo as mz >>> layer = mz.contrib.layers.EncodingLayer(1.0, 10000, 0.977) >>> num_batch, left_len, num_dim = 5, 32, 10 >>> layer.build([num_batch, left_len, num_dim]) """ def __init__(self, initial_keep_rate: float, decay_interval: int, decay_rate: float, **kwargs): """:class: 'EncodingLayer' constructor.""" super(EncodingLayer, self).__init__(**kwargs) self._initial_keep_rate = initial_keep_rate self._decay_interval = decay_interval self._decay_rate = decay_rate self._w_itr_att = None self._w1 = None self._w2 = None self._w3 = None self._b1 = None self._b2 = None self._b3 = None def build(self, input_shape): """ Build the layer. :param input_shape: the shape of the input tensor, for EncodingLayer we need one input tensor. """ d = input_shape[-1] self._w_itr_att = self.add_weight( name='w_itr_att', shape=(3 * d,), initializer='glorot_uniform') self._w1 = self.add_weight( name='w1', shape=(2 * d, d,), initializer='glorot_uniform') self._w2 = self.add_weight( name='w2', shape=(2 * d, d,), initializer='glorot_uniform') self._w3 = self.add_weight( name='w3', shape=(2 * d, d,), initializer='glorot_uniform') self._b1 = self.add_weight( name='b1', shape=(d,), initializer='zeros') self._b2 = self.add_weight( name='b2', shape=(d,), initializer='zeros') self._b3 = self.add_weight( name='b3', shape=(d,), initializer='zeros') super(EncodingLayer, self).build(input_shape) def call(self, inputs, **kwargs): """ The computation logic of EncodingLayer. :param inputs: an input tensor. """ # Scalar dimensions referenced here: # b = batch size # p = inputs.shape()[1] # d = inputs.shape()[2] # The input shape is [b, p, d] # shape = [b, 1, p, d] x = tf.expand_dims(inputs, 1) * 0 # shape = [b, 1, d, p] x = tf.transpose(x, (0, 1, 3, 2)) # shape = [b, p, d, p] mid = x + tf.expand_dims(inputs, -1) # shape = [b, p, d, p] up = tf.transpose(mid, (0, 3, 2, 1)) # shape = [b, p, 3d, p] inputs_concat = tf.concat([up, mid, up * mid], axis=2) # Self-attention layer. # shape = [b, p, p] A = K.dot(self._w_itr_att, inputs_concat) # shape = [b, p, p] SA = tf.nn.softmax(A, axis=2) # shape = [b, p, d] itr_attn = K.batch_dot(SA, inputs) # Semantic composite fuse gate. # shape = [b, p, 2d] inputs_attn_concat = tf.concat([inputs, itr_attn], axis=2) concat_dropout = DecayingDropoutLayer( initial_keep_rate=self._initial_keep_rate, decay_interval=self._decay_interval, decay_rate=self._decay_rate )(inputs_attn_concat) # shape = [b, p, d] z = tf.tanh(K.dot(concat_dropout, self._w1) + self._b1) # shape = [b, p, d] r = tf.sigmoid(K.dot(concat_dropout, self._w2) + self._b2) # shape = [b, p, d] f = tf.sigmoid(K.dot(concat_dropout, self._w3) + self._b3) # shape = [b, p, d] encoding = r * inputs + f * z return encoding
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/contrib/layers/semantic_composite_layer.py", "copies": "1", "size": "4198", "license": "apache-2.0", "hash": 5283100430458227000, "line_mean": 33.694214876, "line_max": 75, "alpha_frac": 0.5454978561, "autogenerated": false, "ratio": 3.429738562091503, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9475236418191504, "avg_score": 0, "num_lines": 121 }
"""An implementation of gates that act on qubits. Gates are unitary operators that act on the space of qubits. Medium Term Todo: * Optimize Gate._apply_operators_Qubit to remove the creation of many intermediate Qubit objects. * Add commutation relationships to all operators and use this in gate_sort. * Fix gate_sort and gate_simp. * Get multi-target UGates plotting properly. * Get UGate to work with either sympy/numpy matrices and output either format. This should also use the matrix slots. """ from __future__ import print_function, division from itertools import chain import random from sympy import Add, I, Integer, Matrix, Mul, Pow, sqrt, Tuple from sympy.core.numbers import Number from sympy.core.compatibility import is_sequence, u, unicode, xrange from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.operator import (UnitaryOperator, Operator, HermitianOperator) from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye from sympy.physics.quantum.matrixcache import matrix_cache from sympy.physics.quantum.dagger import Dagger from sympy.matrices.matrices import MatrixBase from sympy.utilities import default_sort_key __all__ = [ 'Gate', 'CGate', 'UGate', 'OneQubitGate', 'TwoQubitGate', 'IdentityGate', 'HadamardGate', 'XGate', 'YGate', 'ZGate', 'TGate', 'PhaseGate', 'SwapGate', 'CNotGate', # Aliased gate names 'CNOT', 'SWAP', 'H', 'X', 'Y', 'Z', 'T', 'S', 'Phase', 'normalized', 'gate_sort', 'gate_simp', 'random_circuit', 'CPHASE', 'CGateS', ] #----------------------------------------------------------------------------- # Gate Super-Classes #----------------------------------------------------------------------------- _normalized = True def _max(*args, **kwargs): if "key" not in kwargs: kwargs["key"] = default_sort_key return max(*args, **kwargs) def _min(*args, **kwargs): if "key" not in kwargs: kwargs["key"] = default_sort_key return min(*args, **kwargs) def normalized(normalize): """Set flag controlling normalization of Hadamard gates by 1/sqrt(2). This is a global setting that can be used to simplify the look of various expressions, by leaving off the leading 1/sqrt(2) of the Hadamard gate. Parameters ---------- normalize : bool Should the Hadamard gate include the 1/sqrt(2) normalization factor? When True, the Hadamard gate will have the 1/sqrt(2). When False, the Hadamard gate will not have this factor. """ global _normalized _normalized = normalize def _validate_targets_controls(tandc): tandc = list(tandc) # Check for integers for bit in tandc: if not bit.is_Integer and not bit.is_Symbol: raise TypeError('Integer expected, got: %r' % tandc[bit]) # Detect duplicates if len(list(set(tandc))) != len(tandc): raise QuantumError( 'Target/control qubits in a gate cannot be duplicated' ) class Gate(UnitaryOperator): """Non-controlled unitary gate operator that acts on qubits. This is a general abstract gate that needs to be subclassed to do anything useful. Parameters ---------- label : tuple, int A list of the target qubits (as ints) that the gate will apply to. Examples -------- """ _label_separator = ',' gate_name = u('G') gate_name_latex = u('G') #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): args = Tuple(*UnitaryOperator._eval_args(args)) _validate_targets_controls(args) return args @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def nqubits(self): """The total number of qubits this gate acts on. For controlled gate subclasses this includes both target and control qubits, so that, for examples the CNOT gate acts on 2 qubits. """ return len(self.targets) @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(self.targets) + 1 @property def targets(self): """A tuple of target qubits.""" return self.label @property def gate_name_plot(self): return r'$%s$' % self.gate_name_latex #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): """The matrix rep. of the target part of the gate. Parameters ---------- format : str The format string ('sympy','numpy', etc.) """ raise NotImplementedError( 'get_target_matrix is not implemented in Gate.') #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_IntQubit(self, qubits, **options): """Redirect an apply from IntQubit to Qubit""" return self._apply_operator_Qubit(qubits, **options) def _apply_operator_Qubit(self, qubits, **options): """Apply this gate to a Qubit.""" # Check number of qubits this gate acts on. if qubits.nqubits < self.min_qubits: raise QuantumError( 'Gate needs a minimum of %r qubits to act on, got: %r' % (self.min_qubits, qubits.nqubits) ) # If the controls are not met, just return if isinstance(self, CGate): if not self.eval_controls(qubits): return qubits targets = self.targets target_matrix = self.get_target_matrix(format='sympy') # Find which column of the target matrix this applies to. column_index = 0 n = 1 for target in targets: column_index += n*qubits[target] n = n << 1 column = target_matrix[:, int(column_index)] # Now apply each column element to the qubit. result = 0 for index in range(column.rows): # TODO: This can be optimized to reduce the number of Qubit # creations. We should simply manipulate the raw list of qubit # values and then build the new Qubit object once. # Make a copy of the incoming qubits. new_qubit = qubits.__class__(*qubits.args) # Flip the bits that need to be flipped. for bit in range(len(targets)): if new_qubit[targets[bit]] != (index >> bit) & 1: new_qubit = new_qubit.flip(targets[bit]) # The value in that row and column times the flipped-bit qubit # is the result for that part. result += column[index]*new_qubit return result #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): format = options.get('format', 'sympy') nqubits = options.get('nqubits', 0) if nqubits == 0: raise QuantumError( 'The number of qubits must be given as nqubits.') # Make sure we have enough qubits for the gate. if nqubits < self.min_qubits: raise QuantumError( 'The number of qubits %r is too small for the gate.' % nqubits ) target_matrix = self.get_target_matrix(format) targets = self.targets if isinstance(self, CGate): controls = self.controls else: controls = [] m = represent_zbasis( controls, targets, target_matrix, nqubits, format ) return m #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _sympystr(self, printer, *args): label = self._print_label(printer, *args) return '%s(%s)' % (self.gate_name, label) def _pretty(self, printer, *args): a = stringPict(unicode(self.gate_name)) b = self._print_label_pretty(printer, *args) return self._print_subscript_pretty(a, b) def _latex(self, printer, *args): label = self._print_label(printer, *args) return '%s_{%s}' % (self.gate_name_latex, label) def plot_gate(self, axes, gate_idx, gate_grid, wire_grid): raise NotImplementedError('plot_gate is not implemented.') class CGate(Gate): """A general unitary gate with control qubits. A general control gate applies a target gate to a set of targets if all of the control qubits have a particular values (set by ``CGate.control_value``). Parameters ---------- label : tuple The label in this case has the form (controls, gate), where controls is a tuple/list of control qubits (as ints) and gate is a ``Gate`` instance that is the target operator. Examples -------- """ gate_name = u('C') gate_name_latex = u('C') # The values this class controls for. control_value = Integer(1) simplify_cgate=False #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): # _eval_args has the right logic for the controls argument. controls = args[0] gate = args[1] if not is_sequence(controls): controls = (controls,) controls = UnitaryOperator._eval_args(controls) _validate_targets_controls(chain(controls, gate.targets)) return (Tuple(*controls), gate) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def nqubits(self): """The total number of qubits this gate acts on. For controlled gate subclasses this includes both target and control qubits, so that, for examples the CNOT gate acts on 2 qubits. """ return len(self.targets) + len(self.controls) @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(_max(self.controls), _max(self.targets)) + 1 @property def targets(self): """A tuple of target qubits.""" return self.gate.targets @property def controls(self): """A tuple of control qubits.""" return tuple(self.label[0]) @property def gate(self): """The non-controlled gate that will be applied to the targets.""" return self.label[1] #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): return self.gate.get_target_matrix(format) def eval_controls(self, qubit): """Return True/False to indicate if the controls are satisfied.""" return all(qubit[bit] == self.control_value for bit in self.controls) def decompose(self, **options): """Decompose the controlled gate into CNOT and single qubits gates.""" if len(self.controls) == 1: c = self.controls[0] t = self.gate.targets[0] if isinstance(self.gate, YGate): g1 = PhaseGate(t) g2 = CNotGate(c, t) g3 = PhaseGate(t) g4 = ZGate(t) return g1*g2*g3*g4 if isinstance(self.gate, ZGate): g1 = HadamardGate(t) g2 = CNotGate(c, t) g3 = HadamardGate(t) return g1*g2*g3 else: return self #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _print_label(self, printer, *args): controls = self._print_sequence(self.controls, ',', printer, *args) gate = printer._print(self.gate, *args) return '(%s),%s' % (controls, gate) def _pretty(self, printer, *args): controls = self._print_sequence_pretty( self.controls, ',', printer, *args) gate = printer._print(self.gate) gate_name = stringPict(unicode(self.gate_name)) first = self._print_subscript_pretty(gate_name, controls) gate = self._print_parens_pretty(gate) final = prettyForm(*first.right((gate))) return final def _latex(self, printer, *args): controls = self._print_sequence(self.controls, ',', printer, *args) gate = printer._print(self.gate, *args) return r'%s_{%s}{\left(%s\right)}' % \ (self.gate_name_latex, controls, gate) def plot_gate(self, circ_plot, gate_idx): """ Plot the controlled gate. If *simplify_cgate* is true, simplify C-X and C-Z gates into their more familiar forms. """ min_wire = int(_min(chain(self.controls, self.targets))) max_wire = int(_max(chain(self.controls, self.targets))) circ_plot.control_line(gate_idx, min_wire, max_wire) for c in self.controls: circ_plot.control_point(gate_idx, int(c)) if self.simplify_cgate: if self.gate.gate_name == u('X'): self.gate.plot_gate_plus(circ_plot, gate_idx) elif self.gate.gate_name == u('Z'): circ_plot.control_point(gate_idx, self.targets[0]) else: self.gate.plot_gate(circ_plot, gate_idx) else: self.gate.plot_gate(circ_plot, gate_idx) #------------------------------------------------------------------------- # Miscellaneous #------------------------------------------------------------------------- def _eval_dagger(self): if isinstance(self.gate, HermitianOperator): return self else: return Gate._eval_dagger(self) def _eval_inverse(self): if isinstance(self.gate, HermitianOperator): return self else: return Gate._eval_inverse(self) def _eval_power(self, exp): if isinstance(self.gate, HermitianOperator): if exp == -1: return Gate._eval_power(self, exp) elif abs(exp) % 2 == 0: return self*(Gate._eval_inverse(self)) else: return self else: return Gate._eval_power(self, exp) class CGateS(CGate): """Version of CGate that allows gate simplifications. I.e. cnot looks like an oplus, cphase has dots, etc. """ simplify_cgate=True class UGate(Gate): """General gate specified by a set of targets and a target matrix. Parameters ---------- label : tuple A tuple of the form (targets, U), where targets is a tuple of the target qubits and U is a unitary matrix with dimension of len(targets). """ gate_name = u('U') gate_name_latex = u('U') #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): targets = args[0] if not is_sequence(targets): targets = (targets,) targets = Gate._eval_args(targets) _validate_targets_controls(targets) mat = args[1] if not isinstance(mat, MatrixBase): raise TypeError('Matrix expected, got: %r' % mat) dim = 2**len(targets) if not all(dim == shape for shape in mat.shape): raise IndexError( 'Number of targets must match the matrix size: %r %r' % (targets, mat) ) return (targets, mat) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args[0]) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def targets(self): """A tuple of target qubits.""" return tuple(self.label[0]) #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): """The matrix rep. of the target part of the gate. Parameters ---------- format : str The format string ('sympy','numpy', etc.) """ return self.label[1] #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _pretty(self, printer, *args): targets = self._print_sequence_pretty( self.targets, ',', printer, *args) gate_name = stringPict(unicode(self.gate_name)) return self._print_subscript_pretty(gate_name, targets) def _latex(self, printer, *args): targets = self._print_sequence(self.targets, ',', printer, *args) return r'%s_{%s}' % (self.gate_name_latex, targets) def plot_gate(self, circ_plot, gate_idx): circ_plot.one_qubit_box( self.gate_name_plot, gate_idx, int(self.targets[0]) ) class OneQubitGate(Gate): """A single qubit unitary gate base class.""" nqubits = Integer(1) def plot_gate(self, circ_plot, gate_idx): circ_plot.one_qubit_box( self.gate_name_plot, gate_idx, int(self.targets[0]) ) def _eval_commutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(0) return Operator._eval_commutator(self, other, **hints) def _eval_anticommutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(2)*self*other return Operator._eval_anticommutator(self, other, **hints) class TwoQubitGate(Gate): """A two qubit unitary gate base class.""" nqubits = Integer(2) #----------------------------------------------------------------------------- # Single Qubit Gates #----------------------------------------------------------------------------- class IdentityGate(OneQubitGate): """The single qubit identity gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u('1') gate_name_latex = u('1') def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('eye2', format) def _eval_commutator(self, other, **hints): return Integer(0) def _eval_anticommutator(self, other, **hints): return Integer(2)*other class HadamardGate(HermitianOperator, OneQubitGate): """The single qubit Hadamard gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- >>> from sympy import sqrt >>> from sympy.physics.quantum.qubit import Qubit >>> from sympy.physics.quantum.gate import HadamardGate >>> from sympy.physics.quantum.qapply import qapply >>> qapply(HadamardGate(0)*Qubit('1')) sqrt(2)*|0>/2 - sqrt(2)*|1>/2 >>> # Hadamard on bell state, applied on 2 qubits. >>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11')) >>> qapply(HadamardGate(0)*HadamardGate(1)*psi) sqrt(2)*|00>/2 + sqrt(2)*|11>/2 """ gate_name = u('H') gate_name_latex = u('H') def get_target_matrix(self, format='sympy'): if _normalized: return matrix_cache.get_matrix('H', format) else: return matrix_cache.get_matrix('Hsqrt2', format) def _eval_commutator_XGate(self, other, **hints): return I*sqrt(2)*YGate(self.targets[0]) def _eval_commutator_YGate(self, other, **hints): return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0])) def _eval_commutator_ZGate(self, other, **hints): return -I*sqrt(2)*YGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return sqrt(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) def _eval_anticommutator_ZGate(self, other, **hints): return sqrt(2)*IdentityGate(self.targets[0]) class XGate(HermitianOperator, OneQubitGate): """The single qubit X, or NOT, gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u('X') gate_name_latex = u('X') def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('X', format) def plot_gate(self, circ_plot, gate_idx): OneQubitGate.plot_gate(self,circ_plot,gate_idx) def plot_gate_plus(self, circ_plot, gate_idx): circ_plot.not_point( gate_idx, int(self.label[0]) ) def _eval_commutator_YGate(self, other, **hints): return Integer(2)*I*ZGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) def _eval_anticommutator_ZGate(self, other, **hints): return Integer(0) class YGate(HermitianOperator, OneQubitGate): """The single qubit Y gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u('Y') gate_name_latex = u('Y') def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Y', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(2)*I*XGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_ZGate(self, other, **hints): return Integer(0) class ZGate(HermitianOperator, OneQubitGate): """The single qubit Z gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u('Z') gate_name_latex = u('Z') def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Z', format) def _eval_commutator_XGate(self, other, **hints): return Integer(2)*I*YGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) class PhaseGate(OneQubitGate): """The single qubit phase, or S, gate. This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and does nothing if the state is ``|0>``. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u('S') gate_name_latex = u('S') def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('S', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(0) def _eval_commutator_TGate(self, other, **hints): return Integer(0) class TGate(OneQubitGate): """The single qubit pi/8 gate. This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and does nothing if the state is ``|0>``. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u('T') gate_name_latex = u('T') def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('T', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(0) def _eval_commutator_PhaseGate(self, other, **hints): return Integer(0) # Aliases for gate names. H = HadamardGate X = XGate Y = YGate Z = ZGate T = TGate Phase = S = PhaseGate #----------------------------------------------------------------------------- # 2 Qubit Gates #----------------------------------------------------------------------------- class CNotGate(HermitianOperator, CGate, TwoQubitGate): """Two qubit controlled-NOT. This gate performs the NOT or X gate on the target qubit if the control qubits all have the value 1. Parameters ---------- label : tuple A tuple of the form (control, target). Examples -------- >>> from sympy.physics.quantum.gate import CNOT >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import Qubit >>> c = CNOT(1,0) >>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left |11> """ gate_name = 'CNOT' gate_name_latex = u('CNOT') simplify_cgate = True #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): args = Gate._eval_args(args) return args @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(self.label) + 1 @property def targets(self): """A tuple of target qubits.""" return (self.label[1],) @property def controls(self): """A tuple of control qubits.""" return (self.label[0],) @property def gate(self): """The non-controlled gate that will be applied to the targets.""" return XGate(self.label[1]) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- # The default printing of Gate works better than those of CGate, so we # go around the overridden methods in CGate. def _print_label(self, printer, *args): return Gate._print_label(self, printer, *args) def _pretty(self, printer, *args): return Gate._pretty(self, printer, *args) def _latex(self, printer, *args): return Gate._latex(self, printer, *args) #------------------------------------------------------------------------- # Commutator/AntiCommutator #------------------------------------------------------------------------- def _eval_commutator_ZGate(self, other, **hints): """[CNOT(i, j), Z(i)] == 0.""" if self.controls[0] == other.targets[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) def _eval_commutator_TGate(self, other, **hints): """[CNOT(i, j), T(i)] == 0.""" return self._eval_commutator_ZGate(other, **hints) def _eval_commutator_PhaseGate(self, other, **hints): """[CNOT(i, j), S(i)] == 0.""" return self._eval_commutator_ZGate(other, **hints) def _eval_commutator_XGate(self, other, **hints): """[CNOT(i, j), X(j)] == 0.""" if self.targets[0] == other.targets[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) def _eval_commutator_CNotGate(self, other, **hints): """[CNOT(i, j), CNOT(i,k)] == 0.""" if self.controls[0] == other.controls[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) class SwapGate(TwoQubitGate): """Two qubit SWAP gate. This gate swap the values of the two qubits. Parameters ---------- label : tuple A tuple of the form (target1, target2). Examples -------- """ gate_name = 'SWAP' gate_name_latex = u('SWAP') def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('SWAP', format) def decompose(self, **options): """Decompose the SWAP gate into CNOT gates.""" i, j = self.targets[0], self.targets[1] g1 = CNotGate(i, j) g2 = CNotGate(j, i) return g1*g2*g1 def plot_gate(self, circ_plot, gate_idx): min_wire = int(_min(self.targets)) max_wire = int(_max(self.targets)) circ_plot.control_line(gate_idx, min_wire, max_wire) circ_plot.swap_point(gate_idx, min_wire) circ_plot.swap_point(gate_idx, max_wire) def _represent_ZGate(self, basis, **options): """Represent the SWAP gate in the computational basis. The following representation is used to compute this: SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0| """ format = options.get('format', 'sympy') targets = [int(t) for t in self.targets] min_target = _min(targets) max_target = _max(targets) nqubits = options.get('nqubits', self.min_qubits) op01 = matrix_cache.get_matrix('op01', format) op10 = matrix_cache.get_matrix('op10', format) op11 = matrix_cache.get_matrix('op11', format) op00 = matrix_cache.get_matrix('op00', format) eye2 = matrix_cache.get_matrix('eye2', format) result = None for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)): product = nqubits*[eye2] product[nqubits - min_target - 1] = i product[nqubits - max_target - 1] = j new_result = matrix_tensor_product(*product) if result is None: result = new_result else: result = result + new_result return result # Aliases for gate names. CNOT = CNotGate SWAP = SwapGate def CPHASE(a,b): return CGateS((a,),Z(b)) #----------------------------------------------------------------------------- # Represent #----------------------------------------------------------------------------- def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'): """Represent a gate with controls, targets and target_matrix. This function does the low-level work of representing gates as matrices in the standard computational basis (ZGate). Currently, we support two main cases: 1. One target qubit and no control qubits. 2. One target qubits and multiple control qubits. For the base of multiple controls, we use the following expression [1]: 1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2}) Parameters ---------- controls : list, tuple A sequence of control qubits. targets : list, tuple A sequence of target qubits. target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse The matrix form of the transformation to be performed on the target qubits. The format of this matrix must match that passed into the `format` argument. nqubits : int The total number of qubits used for the representation. format : str The format of the final matrix ('sympy', 'numpy', 'scipy.sparse'). Examples -------- References ---------- [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html. """ controls = [int(x) for x in controls] targets = [int(x) for x in targets] nqubits = int(nqubits) # This checks for the format as well. op11 = matrix_cache.get_matrix('op11', format) eye2 = matrix_cache.get_matrix('eye2', format) # Plain single qubit case if len(controls) == 0 and len(targets) == 1: product = [] bit = targets[0] # Fill product with [I1,Gate,I2] such that the unitaries, # I, cause the gate to be applied to the correct Qubit if bit != nqubits - 1: product.append(matrix_eye(2**(nqubits - bit - 1), format=format)) product.append(target_matrix) if bit != 0: product.append(matrix_eye(2**bit, format=format)) return matrix_tensor_product(*product) # Single target, multiple controls. elif len(targets) == 1 and len(controls) >= 1: target = targets[0] # Build the non-trivial part. product2 = [] for i in range(nqubits): product2.append(matrix_eye(2, format=format)) for control in controls: product2[nqubits - 1 - control] = op11 product2[nqubits - 1 - target] = target_matrix - eye2 return matrix_eye(2**nqubits, format=format) + \ matrix_tensor_product(*product2) # Multi-target, multi-control is not yet implemented. else: raise NotImplementedError( 'The representation of multi-target, multi-control gates ' 'is not implemented.' ) #----------------------------------------------------------------------------- # Gate manipulation functions. #----------------------------------------------------------------------------- def gate_simp(circuit): """Simplifies gates symbolically It first sorts gates using gate_sort. It then applies basic simplification rules to the circuit, e.g., XGate**2 = Identity """ # Bubble sort out gates that commute. circuit = gate_sort(circuit) # Do simplifications by subing a simplification into the first element # which can be simplified. We recursively call gate_simp with new circuit # as input more simplifications exist. if isinstance(circuit, Add): return sum(gate_simp(t) for t in circuit.args) elif isinstance(circuit, Mul): circuit_args = circuit.args elif isinstance(circuit, Pow): b, e = circuit.as_base_exp() circuit_args = (gate_simp(b)**e,) else: return circuit # Iterate through each element in circuit, simplify if possible. for i in xrange(len(circuit_args)): # H,X,Y or Z squared is 1. # T**2 = S, S**2 = Z if isinstance(circuit_args[i], Pow): if isinstance(circuit_args[i].base, (HadamardGate, XGate, YGate, ZGate)) \ and isinstance(circuit_args[i].exp, Number): # Build a new circuit taking replacing the # H,X,Y,Z squared with one. newargs = (circuit_args[:i] + (circuit_args[i].base**(circuit_args[i].exp % 2),) + circuit_args[i + 1:]) # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break elif isinstance(circuit_args[i].base, PhaseGate): # Build a new circuit taking old circuit but splicing # in simplification. newargs = circuit_args[:i] # Replace PhaseGate**2 with ZGate. newargs = newargs + (ZGate(circuit_args[i].base.args[0])** (Integer(circuit_args[i].exp/2)), circuit_args[i].base** (circuit_args[i].exp % 2)) # Append the last elements. newargs = newargs + circuit_args[i + 1:] # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break elif isinstance(circuit_args[i].base, TGate): # Build a new circuit taking all the old elements. newargs = circuit_args[:i] # Put an Phasegate in place of any TGate**2. newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])** Integer(circuit_args[i].exp/2), circuit_args[i].base** (circuit_args[i].exp % 2)) # Append the last elements. newargs = newargs + circuit_args[i + 1:] # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break return circuit def gate_sort(circuit): """Sorts the gates while keeping track of commutation relations This function uses a bubble sort to rearrange the order of gate application. Keeps track of Quantum computations special commutation relations (e.g. things that apply to the same Qubit do not commute with each other) circuit is the Mul of gates that are to be sorted. """ # Make sure we have an Add or Mul. if isinstance(circuit, Add): return sum(gate_sort(t) for t in circuit.args) if isinstance(circuit, Pow): return gate_sort(circuit.base)**circuit.exp elif isinstance(circuit, Gate): return circuit if not isinstance(circuit, Mul): return circuit changes = True while changes: changes = False circ_array = circuit.args for i in xrange(len(circ_array) - 1): # Go through each element and switch ones that are in wrong order if isinstance(circ_array[i], (Gate, Pow)) and \ isinstance(circ_array[i + 1], (Gate, Pow)): # If we have a Pow object, look at only the base first_base, first_exp = circ_array[i].as_base_exp() second_base, second_exp = circ_array[i + 1].as_base_exp() # Use sympy's hash based sorting. This is not mathematical # sorting, but is rather based on comparing hashes of objects. # See Basic.compare for details. if first_base.compare(second_base) > 0: if Commutator(first_base, second_base).doit() == 0: new_args = (circuit.args[:i] + (circuit.args[i + 1],) + (circuit.args[i],) + circuit.args[i + 2:]) circuit = Mul(*new_args) circ_array = circuit.args changes = True break if AntiCommutator(first_base, second_base).doit() == 0: new_args = (circuit.args[:i] + (circuit.args[i + 1],) + (circuit.args[i],) + circuit.args[i + 2:]) sign = Integer(-1)**(first_exp*second_exp) circuit = sign*Mul(*new_args) circ_array = circuit.args changes = True break return circuit #----------------------------------------------------------------------------- # Utility functions #----------------------------------------------------------------------------- def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)): """Return a random circuit of ngates and nqubits. This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP) gates. Parameters ---------- ngates : int The number of gates in the circuit. nqubits : int The number of qubits in the circuit. gate_space : tuple A tuple of the gate classes that will be used in the circuit. Repeating gate classes multiple times in this tuple will increase the frequency they appear in the random circuit. """ qubit_space = range(nqubits) result = [] for i in xrange(ngates): g = random.choice(gate_space) if g == CNotGate or g == SwapGate: qubits = random.sample(qubit_space, 2) g = g(*qubits) else: qubit = random.choice(qubit_space) g = g(qubit) result.append(g) return Mul(*result) def zx_basis_transform(self, format='sympy'): """Transformation matrix from Z to X basis.""" return matrix_cache.get_matrix('ZX', format) def zy_basis_transform(self, format='sympy'): """Transformation matrix from Z to Y basis.""" return matrix_cache.get_matrix('ZY', format)
{ "repo_name": "dennisss/sympy", "path": "sympy/physics/quantum/gate.py", "copies": "24", "size": "42016", "license": "bsd-3-clause", "hash": 5269753086676920000, "line_mean": 31.5453137103, "line_max": 82, "alpha_frac": 0.5343440594, "autogenerated": false, "ratio": 4.072106997480132, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
"""An implementation of gates that act on qubits. Gates are unitary operators that act on the space of qubits. Medium Term Todo: * Optimize Gate._apply_operators_Qubit to remove the creation of many intermediate Qubit objects. * Add commutation relationships to all operators and use this in gate_sort. * Fix gate_sort and gate_simp. * Get multi-target UGates plotting properly. * Get UGate to work with either sympy/numpy matrices and output either format. This should also use the matrix slots. """ from itertools import chain import random from sympy import Mul, Pow, Integer, Matrix, Rational, Tuple, I, sqrt, Add from sympy.core.numbers import Number from sympy.core.compatibility import is_sequence from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.operator import UnitaryOperator, Operator, HermitianOperator from sympy.physics.quantum.matrixutils import ( matrix_tensor_product, matrix_eye ) from sympy.physics.quantum.matrixcache import matrix_cache, sqrt2_inv __all__ = [ 'Gate', 'CGate', 'UGate', 'OneQubitGate', 'TwoQubitGate', 'IdentityGate', 'HadamardGate', 'XGate', 'YGate', 'ZGate', 'TGate', 'PhaseGate', 'SwapGate', 'CNotGate', # Aliased gate names 'CNOT', 'SWAP', 'H', 'X', 'Y', 'Z', 'T', 'S', 'Phase', 'normalized', 'gate_sort', 'gate_simp', 'random_circuit', ] #----------------------------------------------------------------------------- # Gate Super-Classes #----------------------------------------------------------------------------- _normalized = True def normalized(normalize): """Should Hadamard gates be normalized by a 1/sqrt(2). This is a global setting that can be used to simplify the look of various expressions, by leaving of the leading 1/sqrt(2) of the Hadamard gate. Parameters ---------- normalize : bool Should the Hadamard gate include the 1/sqrt(2) normalization factor? When True, the Hadamard gate will have the 1/sqrt(2). When False, the Hadamard gate will not have this factor. """ global _normalized _normalized = normalize def _validate_targets_controls(tandc): tandc = list(tandc) # Check for integers for bit in tandc: if not bit.is_Integer: raise TypeError('Integer expected, got: %r' % tandc[bit]) # Detect duplicates if len(list(set(tandc))) != len(tandc): raise QuantumError( 'Target/control qubits in a gate cannot be duplicated' ) class Gate(UnitaryOperator): """Non-controlled unitary gate operator that acts on qubits. This is a general abstract gate that needs to be subclassed to do anything useful. Parameters ---------- label : tuple, int A list of the target qubits (as ints) that the gate will apply to. Examples -------- """ _label_separator = ',' gate_name = u'G' gate_name_latex = u'G' #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): args = UnitaryOperator._eval_args(args) _validate_targets_controls(args) return args @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(max(args)+1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def nqubits(self): """The total number of qubits this gate acts on. For controlled gate subclasses this includes both target and control qubits, so that, for examples the CNOT gate acts on 2 qubits. """ return len(self.targets) @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return max(self.targets)+1 @property def targets(self): """A tuple of target qubits.""" return self.label @property def gate_name_plot(self): return r'$%s$' % self.gate_name_latex #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): """The matrix rep. of the target part of the gate. Parameters ---------- format : str The format string ('sympy','numpy', etc.) """ raise NotImplementedError('get_target_matrix is not implemented in Gate.') #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_IntQubit(self, qubits, **options): """Redirect an apply from IntQubit to Qubit""" return self._apply_operator_Qubit(qubits, **options) def _apply_operator_Qubit(self, qubits, **options): """Apply this gate to a Qubit.""" # Check number of qubits this gate acts on. if qubits.nqubits < self.min_qubits: raise QuantumError( 'Gate needs a minimum of %r qubits to act on, got: %r' %\ (self.min_qubits, qubits.nqubits) ) # If the controls are not met, just return if isinstance(self, CGate): if not self.eval_controls(qubits): return qubits targets = self.targets target_matrix = self.get_target_matrix(format='sympy') # Find which column of the target matrix this applies to. column_index = 0 n = 1 for target in targets: column_index += n*qubits[target] n = n<<1 column = target_matrix[:,int(column_index)] # Now apply each column element to the qubit. result = 0 for index in range(column.rows): # TODO: This can be optimized to reduce the number of Qubit # creations. We should simply manipulate the raw list of qubit # values and then build the new Qubit object once. # Make a copy of the incoming qubits. new_qubit = qubits.__class__(*qubits.args) # Flip the bits that need to be flipped. for bit in range(len(targets)): if new_qubit[targets[bit]] != (index>>bit)&1: new_qubit = new_qubit.flip(targets[bit]) # The value in that row and column times the flipped-bit qubit # is the result for that part. result += column[index]*new_qubit return result #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): format = options.get('format','sympy') nqubits = options.get('nqubits',0) if nqubits == 0: raise QuantumError('The number of qubits must be given as nqubits.') # Make sure we have enough qubits for the gate. if nqubits < self.min_qubits: raise QuantumError( 'The number of qubits %r is too small for the gate.' % nqubits ) target_matrix = self.get_target_matrix(format) targets = self.targets if isinstance(self, CGate): controls = self.controls else: controls = [] m = represent_zbasis( controls, targets, target_matrix, nqubits, format ) return m #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _print_contents(self, printer, *args): label = self._print_label(printer, *args) return '%s(%s)' % (self.gate_name, label) def _print_contents_pretty(self, printer, *args): a = stringPict(unicode(self.gate_name)) b = self._print_label_pretty(printer, *args) return self._print_subscript_pretty(a, b) def _print_contents_latex(self, printer, *args): label = self._print_label(printer, *args) return '%s_{%s}' % (self.gate_name_latex, label) def plot_gate(self, axes, gate_idx, gate_grid, wire_grid): raise NotImplementedError('plot_gate is not implemented.') class CGate(Gate): """A general unitary gate with control qubits. A general control gate applies a target gate to a set of targets if all of the control qubits have a particular values (set by ``CGate.control_value``). Parameters ---------- label : tuple The label in this case has the form (controls, gate), where controls is a tuple/list of control qubits (as ints) and gate is a ``Gate`` instance that is the target operator. Examples -------- """ gate_name = u'C' gate_name_latex = u'C' # The values this class controls for. control_value = Integer(1) #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): # _eval_args has the right logic for the controls argument. controls = args[0] gate = args[1] if not is_sequence(controls): controls = (controls,) controls = UnitaryOperator._eval_args(controls) _validate_targets_controls(chain(controls,gate.targets)) return (controls, gate) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**max(max(args[0])+1,args[1].min_qubits) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def nqubits(self): """The total number of qubits this gate acts on. For controlled gate subclasses this includes both target and control qubits, so that, for examples the CNOT gate acts on 2 qubits. """ return len(self.targets)+len(self.controls) @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return max(max(self.controls),max(self.targets))+1 @property def targets(self): """A tuple of target qubits.""" return self.gate.targets @property def controls(self): """A tuple of control qubits.""" return tuple(self.label[0]) @property def gate(self): """The non-controlled gate that will be applied to the targets.""" return self.label[1] #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): return self.gate.get_target_matrix(format) def eval_controls(self, qubit): """Return True/False to indicate if the controls are satisfied.""" return all(qubit[bit]==self.control_value for bit in self.controls) def decompose(self, **options): """Decompose the controlled gate into CNOT and single qubits gates.""" if len(self.controls) == 1: c = self.controls[0] t = self.gate.targets[0] if isinstance(self.gate, YGate): g1 = PhaseGate(t) g2 = CNotGate(c, t) g3 = PhaseGate(t) g4 = ZGate(t) return g1*g2*g3*g4 if isinstance(self.gate, ZGate): g1 = HadamardGate(t) g2 = CNotGate(c, t) g3 = HadamardGate(t) return g1*g2*g3 else: return self #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _print_contents(self, printer, *args): controls = self._print_sequence(self.controls, ',', printer, *args) gate = printer._print(self.gate, *args) return '%s((%s),%s)' %\ (self.gate_name, controls, gate) def _print_contents_pretty(self, printer, *args): controls = self._print_sequence_pretty(self.controls, ',', printer, *args) gate = printer._print(self.gate) gate_name = stringPict(unicode(self.gate_name)) first = self._print_subscript_pretty(gate_name, controls) gate = self._print_parens_pretty(gate) final = prettyForm(*first.right((gate))) return final def _print_contents_latex(self, printer, *args): controls = self._print_sequence(self.controls, ',', printer, *args) gate = printer._print(self.gate, *args) return r'%s_{%s}{\left(%s\right)}' %\ (self.gate_name_latex, controls, gate) def plot_gate(self, circ_plot, gate_idx): min_wire = int(min(chain(self.controls, self.targets))) max_wire = int(max(chain(self.controls, self.targets))) circ_plot.control_line(gate_idx, min_wire, max_wire) for c in self.controls: circ_plot.control_point(gate_idx, int(c)) self.gate.plot_gate(circ_plot, gate_idx) class UGate(Gate): """General gate specified by a set of targets and a target matrix. Parameters ---------- label : tuple A tuple of the form (targets, U), where targets is a tuple of the target qubits and U is a unitary matrix with dimension of len(targets). """ gate_name = u'U' gate_name_latex = u'U' #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): targets = args[0] if not is_sequence(targets): targets = (targets,) targets = Gate._eval_args(targets) _validate_targets_controls(targets) mat = args[1] if not isinstance(mat, Matrix): raise TypeError('Matrix expected, got: %r' % mat) dim = 2**len(targets) if not all(dim == shape for shape in mat.shape): raise IndexError( 'Number of targets must match the matrix size: %r %r' %\ (targets, mat) ) return (targets, mat) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(max(args[0])+1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def targets(self): """A tuple of target qubits.""" return tuple(self.label[0]) #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): """The matrix rep. of the target part of the gate. Parameters ---------- format : str The format string ('sympy','numpy', etc.) """ return self.label[1] #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _print_contents(self, printer, *args): targets = self._print_targets(printer, *args) return '%s(%s)' % (self.gate_name, targets) def _print_contents_pretty(self, printer, *args): targets = self._print_sequence_pretty(self.targets, ',', printer, *args) gate_name = stringPict(unicode(self.gate_name)) return self._print_subscript_pretty(gate_name, targets) def _print_contents_latex(self, printer, *args): targets = self._print_sequence(self.targets, ',', printer, *args) return r'%s_{%s}' % (self.gate_name_latex, targets) def plot_gate(self, circ_plot, gate_idx): circ_plot.one_qubit_box( self.gate_name_plot, gate_idx, int(self.targets[0]) ) class OneQubitGate(Gate): """A single qubit unitary gate base class.""" nqubits = Integer(1) def plot_gate(self, circ_plot, gate_idx): circ_plot.one_qubit_box( self.gate_name_plot, gate_idx, int(self.targets[0]) ) def _eval_commutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(0) return Operator._eval_commutator(self, other, **hints) def _eval_anticommutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(2)*self*other return Operator._eval_anticommutator(self, other, **hints) class TwoQubitGate(Gate): """A two qubit unitary gate base class.""" nqubits = Integer(2) #----------------------------------------------------------------------------- # Single Qubit Gates #----------------------------------------------------------------------------- class IdentityGate(OneQubitGate): """The single qubit identity gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u'1' gate_name_latex = u'1' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('eye2', format) def _eval_commutator(self, other, **hints): return Integer(0) def _eval_anticommutator(self, other, **hints): return Integer(2)*other class HadamardGate(OneQubitGate): """The single qubit Hadamard gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u'H' gate_name_latex = u'H' def get_target_matrix(self, format='sympy'): if _normalized: return matrix_cache.get_matrix('H', format) else: return matrix_cache.get_matrix('Hsqrt2', format) def _eval_commutator_XGate(self, other, **hints): return I*sqrt(2)*YGate(self.targets[0]) def _eval_commutator_YGate(self, other, **hints): return I*sqrt(2)*(ZGate(self.targets[0])-XGate(self.targets[0])) def _eval_commutator_ZGate(self, other, **hints): return -I*sqrt(2)*YGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return sqrt(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) def _eval_anticommutator_ZGate(self, other, **hints): return sqrt(2)*IdentityGate(self.targets[0]) class XGate(HermitianOperator, OneQubitGate): """The single qubit X, or NOT, gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u'X' gate_name_latex = u'X' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('X', format) def plot_gate(self, circ_plot, gate_idx): circ_plot.not_point( gate_idx, int(self.label[0]) ) def _eval_commutator_YGate(self, other, **hints): return Integer(2)*I*ZGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) def _eval_anticommutator_ZGate(self, other, **hints): return Integer(0) class YGate(HermitianOperator, OneQubitGate): """The single qubit Y gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u'Y' gate_name_latex = u'Y' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Y', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(2)*I*XGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_ZGate(self, other, **hints): return Integer(0) class ZGate(HermitianOperator, OneQubitGate): """The single qubit Z gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u'Z' gate_name_latex = u'Z' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Z', format) def _eval_commutator_XGate(self, other, **hints): return Integer(2)*I*YGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) class PhaseGate(OneQubitGate): """The single qubit phase, or S, gate. This gate rotates the phase of the state by pi/2 if the state is |1> and does nothing if the state is |0>. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u'S' gate_name_latex = u'S' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('S', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(0) def _eval_commutator_TGate(self, other, **hints): return Integer(0) class TGate(OneQubitGate): """The single qubit pi/8 gate. This gate rotates the phase of the state by pi/4 if the state is |1> and does nothing if the state is |0>. Parameters ---------- target : int The target qubit this gate will apply to. Examples -------- """ gate_name = u'T' gate_name_latex = u'T' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('T', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(0) def _eval_commutator_PhaseGate(self, other, **hints): return Integer(0) # Aliases for gate names. H = HadamardGate X = XGate Y = YGate Z = ZGate T = TGate Phase = S = PhaseGate #----------------------------------------------------------------------------- # 2 Qubit Gates #----------------------------------------------------------------------------- class CNotGate(CGate, TwoQubitGate): """Two qubit controlled-NOT. This gate performs the NOT or X gate on the target qubit if the control qubits all have the value 1. Parameters ---------- label : tuple A tuple of the form (control, target). Examples -------- """ gate_name = 'CNOT' gate_name_latex = u'CNOT' #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): args = Gate._eval_args(args) return args @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(max(args)+1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return max(self.label)+1 @property def targets(self): """A tuple of target qubits.""" return (self.label[1],) @property def controls(self): """A tuple of control qubits.""" return (self.label[0],) @property def gate(self): """The non-controlled gate that will be applied to the targets.""" return XGate(self.label[1]) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- # The default printing of Gate works better than those of CGate, so we # go around the overridden methods in CGate. def _print_contents(self, printer, *args): return Gate._print_contents(self, printer, *args) def _print_contents_pretty(self, printer, *args): return Gate._print_contents_pretty(self, printer, *args) def _print_contents_latex(self, printer, *args): return Gate._print_contents_latex(self, printer, *args) #------------------------------------------------------------------------- # Commutator/AntiCommutator #------------------------------------------------------------------------- def _eval_commutator_ZGate(self, other, **hints): """[CNOT(i, j), Z(i)] == 0.""" if self.controls[0] == other.targets[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) def _eval_commutator_TGate(self, other, **hints): """[CNOT(i, j), T(i)] == 0.""" return self._eval_commutator_ZGate(other, **hints) def _eval_commutator_PhaseGate(self, other, **hints): """[CNOT(i, j), S(i)] == 0.""" return self._eval_commutator_ZGate(other, **hints) def _eval_commutator_XGate(self, other, **hints): """[CNOT(i, j), X(j)] == 0.""" if self.targets[0] == other.targets[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) def _eval_commutator_CNotGate(self, other, **hints): """[CNOT(i, j), CNOT(i,k)] == 0.""" if self.controls[0] == other.controls[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) class SwapGate(TwoQubitGate): """Two qubit SWAP gate. This gate swap the values of the two qubits. Parameters ---------- label : tuple A tuple of the form (target1, target2). Examples -------- """ gate_name = 'SWAP' gate_name_latex = u'SWAP' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('SWAP', format) def decompose(self, **options): """Decompose the SWAP gate into CNOT gates.""" i,j = self.targets[0], self.targets[1] g1 = CNotGate(i, j) g2 = CNotGate(j, i) return g1*g2*g1 def plot_gate(self, circ_plot, gate_idx): min_wire = int(min(self.targets)) max_wire = int(max(self.targets)) circ_plot.control_line(gate_idx, min_wire, max_wire) circ_plot.swap_point(gate_idx, min_wire) circ_plot.swap_point(gate_idx, max_wire) def _represent_ZGate(self, basis, **options): """Represent the SWAP gate in the computational basis. The following representation is used to compute this: SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0| """ format = options.get('format', 'sympy') targets = [int(t) for t in self.targets] min_target = min(targets) max_target = max(targets) nqubits = options.get('nqubits',self.min_qubits) op01 = matrix_cache.get_matrix('op01', format) op10 = matrix_cache.get_matrix('op10', format) op11 = matrix_cache.get_matrix('op11', format) op00 = matrix_cache.get_matrix('op00', format) eye2 = matrix_cache.get_matrix('eye2', format) result = None for i, j in ((op01,op10),(op10,op01),(op00,op00),(op11,op11)): product = nqubits*[eye2] product[nqubits-min_target-1] = i product[nqubits-max_target-1] = j new_result = matrix_tensor_product(*product) if result is None: result = new_result else: result = result + new_result return result # Aliases for gate names. CNOT = CNotGate SWAP = SwapGate #----------------------------------------------------------------------------- # Represent #----------------------------------------------------------------------------- def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'): """Represent a gate with controls, targets and target_matrix. This function does the low-level work of representing gates as matrices in the standard computational basis (ZGate). Currently, we support two main cases: 1. One target qubit and no control qubits. 2. One target qubits and multiple control qubits. For the base of multiple controls, we use the following expression [1]: 1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2}) Parameters ---------- controls : list, tuple A sequence of control qubits. targets : list, tuple A sequence of target qubits. target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse The matrix form of the transformation to be performed on the target qubits. The format of this matrix must match that passed into the `format` argument. nqubits : int The total number of qubits used for the representation. format : str The format of the final matrix ('sympy', 'numpy', 'scipy.sparse'). Examples -------- References ---------- [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html. """ controls = [int(x) for x in controls] targets = [int(x) for x in targets] nqubits = int(nqubits) # This checks for the format as well. op11 = matrix_cache.get_matrix('op11', format) eye2 = matrix_cache.get_matrix('eye2', format) # Plain single qubit case if len(controls) == 0 and len(targets) == 1: product = [] bit = targets[0] # Fill product with [I1,Gate,I2] such that the unitaries, # I, cause the gate to be applied to the correct Qubit if bit != nqubits-1: product.append(matrix_eye(2**(nqubits-bit-1), format=format)) product.append(target_matrix) if bit != 0: product.append(matrix_eye(2**bit, format=format)) return matrix_tensor_product(*product) # Single target, multiple controls. elif len(targets) == 1 and len(controls) >= 1: target = targets[0] # Build the non-trivial part. product2 = [] for i in range(nqubits): product2.append(matrix_eye(2, format=format)) for control in controls: product2[nqubits-1-control] = op11 product2[nqubits-1-target] = target_matrix - eye2 return matrix_eye(2**nqubits, format=format) +\ matrix_tensor_product(*product2) # Multi-target, multi-control is not yet implemented. else: raise NotImplementedError( 'The representation of multi-target, multi-control gates ' 'is not implemented.' ) #----------------------------------------------------------------------------- # Gate manipulation functions. #----------------------------------------------------------------------------- def gate_simp(circuit): """Simplifies gates symbolically It first sorts gates using gate_sort. It then applies basic simplification rules to the circuit, e.g., XGate**2 = Identity """ # Bubble sort out gates that commute. circuit = gate_sort(circuit) # Do simplifications by subing a simplification into the first element # which can be simplified. We recursively call gate_simp with new circuit # as input more simplifications exist. if isinstance(circuit, Add): return sum(gate_simp(t) for t in circuit.args) elif isinstance(circuit, Mul): circuit_args = circuit.args elif isinstance(circuit, Pow): b, e = circuit.as_base_exp() circuit_args = (gate_simp(b)**e,) else: return circuit # Iterate through each element in circuit, simplify if possible. for i in xrange(len(circuit_args)): # H,X,Y or Z squared is 1. # T**2 = S, S**2 = Z if isinstance(circuit_args[i], Pow): if isinstance(circuit_args[i].base, (HadamardGate, XGate, YGate, ZGate))\ and isinstance(circuit_args[i].exp, Number): # Build a new circuit taking replacing the # H,X,Y,Z squared with one. newargs = (circuit_args[:i] +\ (circuit_args[i].base**(circuit_args[i].exp % 2),) +\ circuit_args[i+1:]) # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break elif isinstance(circuit_args[i].base, PhaseGate): # Build a new circuit taking old circuit but splicing # in simplification. newargs = circuit_args[:i] # Replace PhaseGate**2 with ZGate. newargs = newargs + (ZGate(circuit_args[i].base.args[0])**\ (Integer(circuit_args[i].exp/2)), circuit_args[i].base**\ (circuit_args[i].exp % 2)) # Append the last elements. newargs = newargs + circuit_args[i+1:] # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break elif isinstance(circuit_args[i].base, TGate): # Build a new circuit taking all the old elements. newargs = circuit_args[:i] # Put an Phasegate in place of any TGate**2. newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**\ Integer(circuit_args[i].exp/2), circuit_args[i].base**\ (circuit_args[i].exp % 2)) # Append the last elements. newargs = newargs + circuit_args[i+1:] # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break return circuit def gate_sort(circuit): """Sorts the gates while keeping track of commutation relations This function uses a bubble sort to rearrange the order of gate application. Keeps track of Quantum computations special commutation relations (e.g. things that apply to the same Qubit do not commute with each other) circuit is the Mul of gates that are to be sorted. """ # Make sure we have an Add or Mul. if isinstance(circuit, Add): return sum(gate_sort(t) for t in circuit.args) if isinstance(circuit, Pow): return gate_sort(circuit.base)**circuit.exp elif isinstance(circuit, Gate): return circuit if not isinstance(circuit, Mul): return circuit changes = True while changes: changes = False circ_array = circuit.args for i in xrange(len(circ_array)-1): # Go through each element and switch ones that are in wrong order if isinstance(circ_array[i], (Gate, Pow)) and\ isinstance(circ_array[i+1], (Gate, Pow)): # If we have a Pow object, look at only the base first_base, first_exp = circ_array[i].as_base_exp() second_base, second_exp = circ_array[i+1].as_base_exp() # Use sympy's hash based sorting. This is not mathematical # sorting, but is rather based on comparing hashes of objects. # See Basic.compare for details. if first_base.compare(second_base) > 0: if Commutator(first_base, second_base).doit() == 0: new_args = (circuit.args[:i] + (circuit.args[i+1],) +\ (circuit.args[i],) + circuit.args[i+2:]) circuit = Mul(*new_args) circ_array = circuit.args changes = True break if AntiCommutator(first_base, second_base).doit() == 0: new_args = (circuit.args[:i] + (circuit.args[i+1],) +\ (circuit.args[i],) + circuit.args[i+2:]) sign = Integer(-1)**(first_exp*second_exp) circuit = sign*Mul(*new_args) circ_array = circuit.args changes = True break return circuit #----------------------------------------------------------------------------- # Utility functions #----------------------------------------------------------------------------- def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)): """Return a random circuit of ngates and nqubits. This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP) gates. Parameters ---------- ngates : int The number of gates in the circuit. nqubits : int The number of qubits in the circuit. gate_space : tuple A tuple of the gate classes that will be used in the circuit. Repeating gate classes multiple times in this tuple will increase the frequency they appear in the random circuit. """ qubit_space = range(nqubits) result = [] for i in xrange(ngates): g = random.choice(gate_space) if g == CNotGate or g == SwapGate: qubits = random.sample(qubit_space,2) g = g(*qubits) else: qubit = random.choice(qubit_space) g = g(qubit) result.append(g) return Mul(*result) def zx_basis_transform(self, format='sympy'): """Transformation matrix from Z to X basis.""" return matrix_cache.get_matrix('ZX', format) def zy_basis_transform(self, format='sympy'): """Transformation matrix from Z to Y basis.""" return matrix_cache.get_matrix('ZY', format)
{ "repo_name": "Cuuuurzel/KiPyCalc", "path": "sympy_old/physics/quantum/gate.py", "copies": "2", "size": "39057", "license": "mit", "hash": -820304495215943400, "line_mean": 31.4663341646, "line_max": 87, "alpha_frac": 0.5364467317, "autogenerated": false, "ratio": 4.093596059113301, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0022169990446906564, "num_lines": 1203 }
import math class LogisticRegression: # Initialize member variables. We have two member variables # 1) weight: a dict obejct storing the weight of all features. # 2) bias: a float value of the bias value. def __init__(self): self.rate = 0.01 self.weight = {} return # data is a list of [label, feature]. label is an integer, # 1 for positive instance, 0 for negative instance. feature is # a dict object, the key is feature name, the value is feature # weight. # # n is the number of training iterations. # # We use online update formula to train the model. def train(self, data, n): for i in range(n): for [label, feature] in data: predicted = self.classify(feature) for f,v in feature.iteritems(): if f not in self.weight: self.weight[f] = 0 update = (label - predicted) * v self.weight[f] = self.weight[f] + self.rate * update print 'iteration', i, 'done' return # feature is a dict object, the key is feature name, the value # is feature weight. Return value is the probability of being # a positive instance. def classify(self, feature): logit = 0 for f,v in feature.iteritems(): coef = 0 if f in self.weight: coef = self.weight[f] logit += coef * v return 1.0 / (1.0 + math.exp(-logit))
{ "repo_name": "applecool/AI", "path": "Logistic Regression/lr.py", "copies": "1", "size": "1706", "license": "mit", "hash": 1914856542245616400, "line_mean": 37.7727272727, "line_max": 72, "alpha_frac": 0.5896834701, "autogenerated": false, "ratio": 4.160975609756098, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0033620735325280778, "num_lines": 44 }
# An implementation of LSTM networks, CTC alignment, and related classes. # # This code operates on sequences of vectors as inputs, and either outputs # sequences of vectors, or symbol sequences. Sequences of vectors are # represented as 2D arrays, with rows representing vectors at different # time steps. # # The code makes liberal use of array programming, including slicing, # both for speed and for simplicity. All arrays are actual narrays (not matrices), # so `*` means element-wise multiplication. If you're not familiar with array # programming style, the numerical code may be hard to follow. If you're familiar with # MATLAB, here is a side-by-side comparison: http://wiki.scipy.org/NumPy_for_Matlab_Users # # Implementations follow the mathematical formulas for forward and backward # propagation closely; these are not documented in the code, but you can find # them in the original publications or the slides for the LSTM tutorial # at http://lstm.iupr.com/ # # You can find a simple example of how to use this code in this worksheet: # https://docs.google.com/a/iupr.com/file/d/0B2VUW2Zx_hNoXzJQemFhOXlLN0U # More complex usage is illustrated by the ocropus-rpred and ocropus-rtrain # command line programs. # # Author: Thomas M. Breuel # License: Apache 2.0 from __future__ import print_function import common as ocrolib from numpy import (amax, amin, argmax, arange, array, clip, concatenate, dot, exp, isnan, log, maximum, mean, nan, ones, outer, roll, sum, tanh, tile, vstack, zeros) from pylab import (clf, cm, figure, ginput, imshow, newaxis, rand, subplot, where) from collections import defaultdict from ocrolib.exceptions import RecognitionError from ocrolib.edist import levenshtein import utils import unicodedata from scipy.ndimage import measurements,filters initial_range = 0.1 class RangeError(Exception): def __init__(self,s=None): Exception.__init__(self,s) def prepare_line(line,pad=16): """Prepare a line for recognition; this inverts it, transposes it, and pads it.""" line = line * 1.0/amax(line) line = amax(line)-line line = line.T if pad>0: w = line.shape[1] line = vstack([zeros((pad,w)),line,zeros((pad,w))]) return line def randu(*shape): """Generate uniformly random values in the range (-1,1). This can usually be used as a drop-in replacement for `randn` resulting in a different distribution for weight initializations. Empirically, the choice of randu/randn can make a difference for neural network initialization.""" return 2*rand(*shape)-1 def sigmoid(x): """Compute the sigmoid function. We don't bother with clipping the input value because IEEE floating point behaves reasonably with this function even for infinities.""" return 1.0/(1.0+exp(-x)) def rownorm(a): """Compute a vector consisting of the Euclidean norm of the rows of the 2D array.""" return sum(array(a)**2,axis=1)**.5 def check_nan(*args,**kw): "Check whether there are any NaNs in the argument arrays." for arg in args: if isnan(arg).any(): raise FloatingPointError() def sumouter(us,vs,lo=-1.0,hi=1.0,out=None): """Sum the outer products of the `us` and `vs`. Values are clipped into the range `[lo,hi]`. This is mainly used for computing weight updates in logistic regression layers.""" result = out or zeros((len(us[0]),len(vs[0]))) for u,v in zip(us,vs): result += outer(clip(u,lo,hi),v) return result def sumprod(us,vs,lo=-1.0,hi=1.0,out=None): """Sum the element-wise products of the `us` and `vs`. Values are clipped into the range `[lo,hi]`. This is mainly used for computing weight updates in logistic regression layers.""" assert len(us[0])==len(vs[0]) result = out or zeros(len(us[0])) for u,v in zip(us,vs): result += clip(u,lo,hi)*v return result class Network: """General interface for networks. This mainly adds convenience functions for `predict` and `train`. For the purposes of this library, all inputs and outputs are in the form of (temporal) sequences of vectors. Sequences of vectors are represented as 2D arrays, with each row representing a vector at the time step given by the row index. Both activations and deltas are propagated that way. Common implementations of this are the `MLP`, `Logreg`, `Softmax`, and `LSTM` networks. These implementations do most of the numerical computation and learning. Networks are designed such that they can be abstracted; that is, you can create a network class that implements forward/backward methods but internally implements through calls to component networks. The `Stacked`, `Reversed`, and `Parallel` classes below take advantage of that. """ def predict(self,xs): """Prediction is the same as forward propagation.""" return self.forward(xs) def train(self,xs,ys,debug=0): """Training performs forward propagation, computes the output deltas as the difference between the predicted and desired values, and then propagates those deltas backwards.""" xs = array(xs) ys = array(ys) pred = array(self.forward(xs)) deltas = ys - pred self.backward(deltas) self.update() return pred def walk(self): yield self def preSave(self): pass def postLoad(self): pass def ctrain(self,xs,cs,debug=0,lo=1e-5,accelerated=1): """Training for classification. This handles the special case of just two classes. It also can use regular least square error training or accelerated training using 1/pred as the error signal.""" assert len(cs.shape)==1 assert (cs==array(cs,'i')).all() xs = array(xs) pred = array(self.forward(xs)) deltas = zeros(pred.shape) assert len(deltas)==len(cs) # NB: these deltas are such that they can be used # directly to update the gradient; some other libraries # use the negative value. if accelerated: # ATTENTION: These deltas use an "accelerated" error signal. if deltas.shape[1]==1: # Binary class case uses just one output variable. for i,c in enumerate(cs): if c==0: deltas[i,0] = -1.0/max(lo,1.0-pred[i,0]) else: deltas[i,0] = 1.0/max(lo,pred[i,0]) else: # For the multi-class case, we use all output variables. deltas[:,:] = -pred[:,:] for i,c in enumerate(cs): deltas[i,c] = 1.0/max(lo,pred[i,c]) else: # These are the deltas from least-square error # updates. They are slower than `accelerated`, # but may give more accurate probability estimates. if deltas.shape[1]==1: # Binary class case uses just one output variable. for i,c in enumerate(cs): if c==0: deltas[i,0] = -pred[i,0] else: deltas[i,0] = 1.0-pred[i,0] else: # For the multi-class case, we use all output variables. deltas[:,:] = -pred[:,:] for i,c in enumerate(cs): deltas[i,c] = 1.0-pred[i,c] self.backward(deltas) self.update() return pred def setLearningRate(self,r,momentum=0.9): """Set the learning rate and momentum for weight updates.""" self.learning_rate = r self.momentum = momentum def weights(self): """Return an iterator that iterates over (W,DW,name) triples representing the weight matrix, the computed deltas, and the names of all the components of this network. This needs to be implemented in subclasses. The objects returned by the iterator must not be copies, since they are updated in place by the `update` method.""" pass def allweights(self): """Return all weights as a single vector. This is mainly a convenience function for plotting.""" aw = list(self.weights()) weights,derivs,names = zip(*aw) weights = [w.ravel() for w in weights] derivs = [d.ravel() for d in derivs] return concatenate(weights),concatenate(derivs) def update(self): """Update the weights using the deltas computed in the last forward/backward pass. Subclasses need not implement this, they should implement the `weights` method.""" if not hasattr(self,"verbose"): self.verbose = 0 if not hasattr(self,"deltas") or self.deltas is None: self.deltas = [zeros(dw.shape) for w,dw,n in self.weights()] for ds,(w,dw,n) in zip(self.deltas,self.weights()): ds.ravel()[:] = self.momentum * ds.ravel()[:] + self.learning_rate * dw.ravel()[:] w.ravel()[:] += ds.ravel()[:] if self.verbose: print(n, (amin(w), amax(w)), (amin(dw), amax(dw))) ''' The following are subclass responsibility: def forward(self,xs): """Propagate activations forward through the network. This needs to be implemented in subclasses. It updates the internal state of the object for an (optional) subsequent call to `backward`. """ pass def backward(self,deltas): """Propagate error signals backward through the network. This needs to be implemented in subclasses. It assumes that activations for the input have previously been computed by a call to `forward`. It should not perform weight updates (that is handled by the `update` method).""" pass ''' class Logreg(Network): """A logistic regression layer, a straightforward implementation of the logistic regression equations. Uses 1-augmented vectors.""" def __init__(self,Nh,No,initial_range=initial_range,rand=rand): self.Nh = Nh self.No = No self.W2 = randu(No,Nh+1)*initial_range self.DW2 = zeros((No,Nh+1)) def ninputs(self): return self.Nh def noutputs(self): return self.No def forward(self,ys): n = len(ys) inputs,zs = [None]*n,[None]*n for i in range(n): inputs[i] = concatenate([ones(1),ys[i]]) zs[i] = sigmoid(dot(self.W2,inputs[i])) self.state = (inputs,zs) return zs def backward(self,deltas): inputs,zs = self.state n = len(zs) assert len(deltas)==len(inputs) dzspre,dys = [None]*n,[None]*n for i in reversed(range(len(zs))): dzspre[i] = deltas[i] * zs[i] * (1-zs[i]) dys[i] = dot(dzspre[i],self.W2)[1:] self.dzspre = dzspre self.DW2 = sumouter(dzspre,inputs) return dys def info(self): vars = sorted("W2".split()) for v in vars: a = array(getattr(self,v)) print(v, a.shape, amin(a), amax(a)) def weights(self): yield self.W2,self.DW2,"Logreg" class Softmax(Network): """A softmax layer, a straightforward implementation of the softmax equations. Uses 1-augmented vectors.""" def __init__(self,Nh,No,initial_range=initial_range,rand=rand): self.Nh = Nh self.No = No self.W2 = randu(No,Nh+1)*initial_range self.DW2 = zeros((No,Nh+1)) def ninputs(self): return self.Nh def noutputs(self): return self.No def forward(self,ys): """Forward propagate activations. This updates the internal state for a subsequent call to `backward` and returns the output activations.""" n = len(ys) inputs,zs = [None]*n,[None]*n for i in range(n): inputs[i] = concatenate([ones(1),ys[i]]) temp = dot(self.W2,inputs[i]) temp = exp(clip(temp,-100,100)) temp /= sum(temp) zs[i] = temp self.state = (inputs,zs) return zs def backward(self,deltas): inputs,zs = self.state n = len(zs) assert len(deltas)==len(inputs) dzspre,dys = [None]*n,[None]*n for i in reversed(range(len(zs))): dzspre[i] = deltas[i] dys[i] = dot(dzspre[i],self.W2)[1:] self.DW2 = sumouter(dzspre,inputs) return dys def info(self): vars = sorted("W2".split()) for v in vars: a = array(getattr(self,v)) print(v, a.shape, amin(a), amax(a)) def weights(self): yield self.W2,self.DW2,"Softmax" class MLP(Network): """A multilayer perceptron (direct implementation). Effectively, two `Logreg` layers stacked on top of each other, or a simple direct implementation of the MLP equations. This is mainly used for testing.""" def __init__(self,Ni,Nh,No,initial_range=initial_range,rand=randu): self.Ni = Ni self.Nh = Nh self.No = No self.W1 = rand(Nh,Ni+1)*initial_range self.W2 = rand(No,Nh+1)*initial_range def ninputs(self): return self.Ni def noutputs(self): return self.No def forward(self,xs): n = len(xs) inputs,ys,zs = [None]*n,[None]*n,[None]*n for i in range(n): inputs[i] = concatenate([ones(1),xs[i]]) ys[i] = sigmoid(dot(self.W1,inputs[i])) ys[i] = concatenate([ones(1),ys[i]]) zs[i] = sigmoid(dot(self.W2,ys[i])) self.state = (inputs,ys,zs) return zs def backward(self,deltas): xs,ys,zs = self.state n = len(xs) dxs,dyspre,dzspre,dys = [None]*n,[None]*n,[None]*n,[None]*n for i in reversed(range(len(zs))): dzspre[i] = deltas[i] * zs[i] * (1-zs[i]) dys[i] = dot(dzspre[i],self.W2)[1:] dyspre[i] = dys[i] * (ys[i] * (1-ys[i]))[1:] dxs[i] = dot(dyspre[i],self.W1)[1:] self.DW2 = sumouter(dzspre,ys) self.DW1 = sumouter(dyspre,xs) return dxs def weights(self): yield self.W1,self.DW1,"MLP1" yield self.W2,self.DW2,"MLP2" # These are the nonlinearities used by the LSTM network. # We don't bother parameterizing them here def ffunc(x): "Nonlinearity used for gates." # cliping to avoid overflows return 1.0/(1.0+exp(clip(-x,-20,20))) def fprime(x,y=None): "Derivative of nonlinearity used for gates." if y is None: y = sigmoid(x) return y*(1.0-y) def gfunc(x): "Nonlinearity used for input to state." return tanh(x) def gprime(x,y=None): "Derivative of nonlinearity used for input to state." if y is None: y = tanh(x) return 1-y**2 # ATTENTION: try linear for hfunc def hfunc(x): "Nonlinearity used for output." return tanh(x) def hprime(x,y=None): "Derivative of nonlinearity used for output." if y is None: y = tanh(x) return 1-y**2 # These two routines have been factored out of the class in order to # make their conversion to native code easy; these are the "inner loops" # of the LSTM algorithm. # Both functions are a straightforward implementation of the # LSTM equations. It is possible to abstract this further and # represent gates and memory cells as individual data structures. # However, that is several times slower and the extra abstraction # isn't actually all that useful. def forward_py(n,N,ni,ns,na,xs,source,gix,gfx,gox,cix,gi,gf,go,ci,state,output,WGI,WGF,WGO,WCI,WIP,WFP,WOP): """Perform forward propagation of activations for a simple LSTM layer.""" for t in range(n): prev = zeros(ns) if t==0 else output[t-1] source[t,0] = 1 source[t,1:1+ni] = xs[t] source[t,1+ni:] = prev dot(WGI,source[t],out=gix[t]) dot(WGF,source[t],out=gfx[t]) dot(WGO,source[t],out=gox[t]) dot(WCI,source[t],out=cix[t]) if t>0: gix[t] += WIP*state[t-1] gfx[t] += WFP*state[t-1] gi[t] = ffunc(gix[t]) gf[t] = ffunc(gfx[t]) ci[t] = gfunc(cix[t]) state[t] = ci[t]*gi[t] if t>0: state[t] += gf[t]*state[t-1] gox[t] += WOP*state[t] go[t] = ffunc(gox[t]) output[t] = hfunc(state[t]) * go[t] assert not isnan(output[:n]).any() def backward_py(n,N,ni,ns,na,deltas, source, gix,gfx,gox,cix, gi,gf,go,ci, state,output, WGI,WGF,WGO,WCI, WIP,WFP,WOP, sourceerr, gierr,gferr,goerr,cierr, stateerr,outerr, DWGI,DWGF,DWGO,DWCI, DWIP,DWFP,DWOP): """Perform backward propagation of deltas for a simple LSTM layer.""" for t in reversed(range(n)): outerr[t] = deltas[t] if t<n-1: outerr[t] += sourceerr[t+1][-ns:] goerr[t] = fprime(None,go[t]) * hfunc(state[t]) * outerr[t] stateerr[t] = hprime(state[t]) * go[t] * outerr[t] stateerr[t] += goerr[t]*WOP if t<n-1: stateerr[t] += gferr[t+1]*WFP stateerr[t] += gierr[t+1]*WIP stateerr[t] += stateerr[t+1]*gf[t+1] if t>0: gferr[t] = fprime(None,gf[t])*stateerr[t]*state[t-1] gierr[t] = fprime(None,gi[t])*stateerr[t]*ci[t] # gfunc(cix[t]) cierr[t] = gprime(None,ci[t])*stateerr[t]*gi[t] dot(gierr[t],WGI,out=sourceerr[t]) if t>0: sourceerr[t] += dot(gferr[t],WGF) sourceerr[t] += dot(goerr[t],WGO) sourceerr[t] += dot(cierr[t],WCI) DWIP = utils.sumprod(gierr[1:n],state[:n-1],out=DWIP) DWFP = utils.sumprod(gferr[1:n],state[:n-1],out=DWFP) DWOP = utils.sumprod(goerr[:n],state[:n],out=DWOP) DWGI = utils.sumouter(gierr[:n],source[:n],out=DWGI) DWGF = utils.sumouter(gferr[1:n],source[1:n],out=DWGF) DWGO = utils.sumouter(goerr[:n],source[:n],out=DWGO) DWCI = utils.sumouter(cierr[:n],source[:n],out=DWCI) class LSTM(Network): """A standard LSTM network. This is a direct implementation of all the forward and backward propagation formulas, mainly for speed. (There is another, more abstract implementation as well, but that's significantly slower in Python due to function call overhead.)""" def __init__(self,ni,ns,initial=initial_range,maxlen=5000): na = 1+ni+ns self.dims = ni,ns,na self.init_weights(initial) self.allocate(maxlen) def ninputs(self): return self.dims[0] def noutputs(self): return self.dims[1] def states(self): """Return the internal state array for the last forward propagation. This is mostly used for visualizations.""" return array(self.state[:self.last_n]) def init_weights(self,initial): "Initialize the weight matrices and derivatives" ni,ns,na = self.dims # gate weights for w in "WGI WGF WGO WCI".split(): setattr(self,w,randu(ns,na)*initial) setattr(self,"D"+w,zeros((ns,na))) # peep weights for w in "WIP WFP WOP".split(): setattr(self,w,randu(ns)*initial) setattr(self,"D"+w,zeros(ns)) def weights(self): "Yields all the weight and derivative matrices" weights = "WGI WGF WGO WCI WIP WFP WOP" for w in weights.split(): yield(getattr(self,w),getattr(self,"D"+w),w) def info(self): "Print info about the internal state" vars = "WGI WGF WGO WIP WFP WOP cix ci gix gi gox go gfx gf" vars += " source state output gierr gferr goerr cierr stateerr" vars = vars.split() vars = sorted(vars) for v in vars: a = array(getattr(self,v)) print(v, a.shape, amin(a), amax(a)) def preSave(self): self.max_n = max(500,len(self.ci)) self.allocate(1) def postLoad(self): self.allocate(getattr(self,"max_n",5000)) def allocate(self,n): """Allocate space for the internal state variables. `n` is the maximum sequence length that can be processed.""" ni,ns,na = self.dims vars = "cix ci gix gi gox go gfx gf" vars += " state output gierr gferr goerr cierr stateerr outerr" for v in vars.split(): setattr(self,v,nan*ones((n,ns))) self.source = nan*ones((n,na)) self.sourceerr = nan*ones((n,na)) def reset(self,n): """Reset the contents of the internal state variables to `nan`""" vars = "cix ci gix gi gox go gfx gf" vars += " state output gierr gferr goerr cierr stateerr outerr" vars += " source sourceerr" for v in vars.split(): getattr(self,v)[:,:] = nan def forward(self,xs): """Perform forward propagation of activations and update the internal state for a subsequent call to `backward`. Since this performs sequence classification, `xs` is a 2D array, with rows representing input vectors at each time step. Returns a 2D array whose rows represent output vectors for each input vector.""" ni,ns,na = self.dims assert len(xs[0])==ni n = len(xs) self.last_n = n N = len(self.gi) if n>N: raise RecognitionError("input too large for LSTM model") self.reset(n) forward_py(n,N,ni,ns,na,xs, self.source, self.gix,self.gfx,self.gox,self.cix, self.gi,self.gf,self.go,self.ci, self.state,self.output, self.WGI,self.WGF,self.WGO,self.WCI, self.WIP,self.WFP,self.WOP) assert not isnan(self.output[:n]).any() return self.output[:n] def backward(self,deltas): """Perform backward propagation of deltas. Must be called after `forward`. Does not perform weight updating (for that, use the generic `update` method). Returns the `deltas` for the input vectors.""" ni,ns,na = self.dims n = len(deltas) self.last_n = n N = len(self.gi) if n>N: raise ocrolib.RecognitionError("input too large for LSTM model") backward_py(n,N,ni,ns,na,deltas, self.source, self.gix,self.gfx,self.gox,self.cix, self.gi,self.gf,self.go,self.ci, self.state,self.output, self.WGI,self.WGF,self.WGO,self.WCI, self.WIP,self.WFP,self.WOP, self.sourceerr, self.gierr,self.gferr,self.goerr,self.cierr, self.stateerr,self.outerr, self.DWGI,self.DWGF,self.DWGO,self.DWCI, self.DWIP,self.DWFP,self.DWOP) return [s[1:1+ni] for s in self.sourceerr[:n]] ################################################################ # combination classifiers ################################################################ class Stacked(Network): """Stack two networks on top of each other.""" def __init__(self,nets): self.nets = nets self.dstats = defaultdict(list) def walk(self): yield self for sub in self.nets: for x in sub.walk(): yield x def ninputs(self): return self.nets[0].ninputs() def noutputs(self): return self.nets[-1].noutputs() def forward(self,xs): for i,net in enumerate(self.nets): xs = net.forward(xs) return xs def backward(self,deltas): self.ldeltas = [deltas] for i,net in reversed(list(enumerate(self.nets))): if deltas is not None: self.dstats[i].append((amin(deltas),mean(deltas),amax(deltas))) deltas = net.backward(deltas) self.ldeltas.append(deltas) self.ldeltas = self.ldeltas[::-1] return deltas def lastdeltas(self): return self.ldeltas[-1] def info(self): for net in self.nets: net.info() def states(self): return self.nets[0].states() def weights(self): for i,net in enumerate(self.nets): for w,dw,n in net.weights(): yield w,dw,"Stacked%d/%s"%(i,n) class Reversed(Network): """Run a network on the time-reversed input.""" def __init__(self,net): self.net = net def walk(self): yield self for x in self.net.walk(): yield x def ninputs(self): return self.net.ninputs() def noutputs(self): return self.net.noutputs() def forward(self,xs): return self.net.forward(xs[::-1])[::-1] def backward(self,deltas): result = self.net.backward(deltas[::-1]) return result[::-1] if result is not None else None def info(self): self.net.info() def states(self): return self.net.states()[::-1] def weights(self): for w,dw,n in self.net.weights(): yield w,dw,"Reversed/%s"%n class Parallel(Network): """Run multiple networks in parallel on the same input.""" def __init__(self,*nets): self.nets = nets def walk(self): yield self for sub in self.nets: for x in sub.walk(): yield x def forward(self,xs): outputs = [net.forward(xs) for net in self.nets] outputs = zip(*outputs) outputs = [concatenate(l) for l in outputs] return outputs def backward(self,deltas): deltas = array(deltas) start = 0 for i,net in enumerate(self.nets): k = net.noutputs() net.backward(deltas[:,start:start+k]) start += k return None def info(self): for net in self.nets: net.info() def states(self): # states = [net.states() for net in self.nets] # FIXME outputs = zip(*outputs) outputs = [concatenate(l) for l in outputs] return outputs def weights(self): for i,net in enumerate(self.nets): for w,dw,n in net.weights(): yield w,dw,"Parallel%d/%s"%(i,n) def MLP1(Ni,Ns,No): """An MLP implementation by stacking two `Logreg` networks on top of each other.""" lr1 = Logreg(Ni,Ns) lr2 = Logreg(Ns,No) stacked = Stacked([lr1,lr2]) return stacked def LSTM1(Ni,Ns,No): """An LSTM layer with a `Logreg` layer for the output.""" lstm = LSTM(Ni,Ns) if No==1: logreg = Logreg(Ns,No) else: logreg = Softmax(Ns,No) stacked = Stacked([lstm,logreg]) return stacked def BIDILSTM(Ni,Ns,No): """A bidirectional LSTM, constructed from regular and reversed LSTMs.""" lstm1 = LSTM(Ni,Ns) lstm2 = Reversed(LSTM(Ni,Ns)) bidi = Parallel(lstm1,lstm2) assert No>1 # logreg = Logreg(2*Ns,No) logreg = Softmax(2*Ns,No) stacked = Stacked([bidi,logreg]) return stacked ################################################################ # LSTM classification with forward/backward alignment ("CTC") ################################################################ def make_target(cs,nc): """Given a list of target classes `cs` and a total maximum number of classes, compute an array that has a `1` in each column and time step corresponding to the target class.""" result = zeros((2*len(cs)+1,nc)) for i,j in enumerate(cs): result[2*i,0] = 1.0 result[2*i+1,j] = 1.0 result[-1,0] = 1.0 return result def translate_back0(outputs,threshold=0.25): """Simple code for translating output from a classifier back into a list of classes. TODO/ATTENTION: this can probably be improved.""" ms = amax(outputs,axis=1) cs = argmax(outputs,axis=1) cs[ms<threshold*amax(outputs)] = 0 result = [] for i in range(1,len(cs)): if cs[i]!=cs[i-1]: if cs[i]!=0: result.append(cs[i]) return result def translate_back(outputs,threshold=0.7,pos=0): """Translate back. Thresholds on class 0, then assigns the maximum class to each region. ``pos`` determines the depth of character information returned: * `pos=0`: Return list of recognized characters * `pos=1`: Return list of position-character tuples * `pos=2`: Return list of character-probability tuples """ labels,n = measurements.label(outputs[:,0]<threshold) mask = tile(labels.reshape(-1,1),(1,outputs.shape[1])) maxima = measurements.maximum_position(outputs,mask,arange(1,amax(mask)+1)) if pos==1: return maxima # include character position if pos==2: return [(c, outputs[r,c]) for (r,c) in maxima] # include character probabilities return [c for (r,c) in maxima] # only recognized characters def log_mul(x,y): "Perform multiplication in the log domain (i.e., addition)." return x+y def log_add(x,y): "Perform addition in the log domain." #return where(abs(x-y)>10,maximum(x,y),log(exp(x-y)+1)+y) return where(abs(x-y)>10,maximum(x,y),log(exp(clip(x-y,-20,20))+1)+y) def forward_algorithm(match,skip=-5.0): """Apply the forward algorithm to an array of log state correspondence probabilities.""" v = skip*arange(len(match[0])) result = [] # This is a fairly straightforward dynamic programming problem and # implemented in close analogy to the edit distance: # we either stay in the same state at no extra cost or make a diagonal # step (transition into new state) at no extra cost; the only costs come # from how well the symbols match the network output. for i in range(0,len(match)): w = roll(v,1).copy() # extra cost for skipping initial symbols w[0] = skip*i # total cost is match cost of staying in same state # plus match cost of making a transition into the next state v = log_add(log_mul(v,match[i]),log_mul(w,match[i])) result.append(v) return array(result,'f') def forwardbackward(lmatch): """Apply the forward-backward algorithm to an array of log state correspondence probabilities.""" lr = forward_algorithm(lmatch) # backward is just forward applied to the reversed sequence rl = forward_algorithm(lmatch[::-1,::-1])[::-1,::-1] both = lr+rl return both def ctc_align_targets(outputs,targets,threshold=100.0,verbose=0,debug=0,lo=1e-5): """Perform alignment between the `outputs` of a neural network classifier and some targets. The targets themselves are a time sequence of vectors, usually a unary representation of each target class (but possibly sequences of arbitrary posterior probability distributions represented as vectors).""" outputs = maximum(lo,outputs) outputs = outputs * 1.0/sum(outputs,axis=1)[:,newaxis] # first, we compute the match between the outputs and the targets # and put the result in the log domain match = dot(outputs,targets.T) lmatch = log(match) if debug: figure("ctcalign"); clf(); subplot(411); imshow(outputs.T,interpolation='nearest',cmap=cm.hot) subplot(412); imshow(lmatch.T,interpolation='nearest',cmap=cm.hot) assert not isnan(lmatch).any() # Now, we compute a forward-backward algorithm over the matches between # the input and the output states. both = forwardbackward(lmatch) # We need posterior probabilities for the states, so we need to normalize # the output. Instead of keeping track of the normalization # factors, we just normalize the posterior distribution directly. epath = exp(both-amax(both)) l = sum(epath,axis=0)[newaxis,:] epath /= where(l==0.0,1e-9,l) # The previous computation gives us an alignment between input time # and output sequence position as posteriors over states. # However, we actually want the posterior probability distribution over # output classes at each time step. This dot product gives # us that result. We renormalize again afterwards. aligned = maximum(lo,dot(epath,targets)) l = sum(aligned,axis=1)[:,newaxis] aligned /= where(l==0.0,1e-9,l) if debug: subplot(413); imshow(epath.T,cmap=cm.hot,interpolation='nearest') subplot(414); imshow(aligned.T,cmap=cm.hot,interpolation='nearest') ginput(1,0.01); return aligned def normalize_nfkc(s): return unicodedata.normalize('NFKC',s) def add_training_info(network): return network class SeqRecognizer: """Perform sequence recognition using BIDILSTM and alignment.""" def __init__(self,ninput,nstates,noutput=-1,codec=None,normalize=normalize_nfkc): self.Ni = ninput if codec: noutput = codec.size() assert noutput>0 self.No = noutput self.lstm = BIDILSTM(ninput,nstates,noutput) self.setLearningRate(1e-4) self.debug_align = 0 self.normalize = normalize self.codec = codec self.clear_log() def walk(self): for x in self.lstm.walk(): yield x def clear_log(self): self.command_log = [] self.error_log = [] self.cerror_log = [] self.key_log = [] def __setstate__(self,state): self.__dict__.update(state) self.upgrade() def upgrade(self): if "last_trial" not in dir(self): self.last_trial = 0 if "command_log" not in dir(self): self.command_log = [] if "error_log" not in dir(self): self.error_log = [] if "cerror_log" not in dir(self): self.cerror_log = [] if "key_log" not in dir(self): self.key_log = [] def info(self): self.net.info() def setLearningRate(self,r,momentum=0.9): self.lstm.setLearningRate(r,momentum) def predictSequence(self,xs): "Predict an integer sequence of codes." assert xs.shape[1]==self.Ni,\ "wrong image height (image: %d, expected: %d)"%(xs.shape[1],self.Ni) self.outputs = array(self.lstm.forward(xs)) return translate_back(self.outputs) def trainSequence(self,xs,cs,update=1,key=None): "Train with an integer sequence of codes." assert xs.shape[1]==self.Ni,"wrong image height" # forward step self.outputs = array(self.lstm.forward(xs)) # CTC alignment self.targets = array(make_target(cs,self.No)) self.aligned = array(ctc_align_targets(self.outputs,self.targets,debug=self.debug_align)) # propagate the deltas back deltas = self.aligned-self.outputs self.lstm.backward(deltas) if update: self.lstm.update() # translate back into a sequence result = translate_back(self.outputs) # compute least square error self.error = sum(deltas**2) self.error_log.append(self.error**.5/len(cs)) # compute class error self.cerror = levenshtein(cs,result) self.cerror_log.append((self.cerror,len(cs))) # training keys self.key_log.append(key) return result # we keep track of errors within the object; this even gets # saved to give us some idea of the training history def errors(self,range=10000,smooth=0): result = self.error_log[-range:] if smooth>0: result = filters.gaussian_filter(result,smooth,mode='mirror') return result def cerrors(self,range=10000,smooth=0): result = [e*1.0/max(1,n) for e,n in self.cerror_log[-range:]] if smooth>0: result = filters.gaussian_filter(result,smooth,mode='mirror') return result def s2l(self,s): "Convert a unicode sequence into a code sequence for training." s = self.normalize(s) s = [c for c in s] return self.codec.encode(s) def l2s(self,l): "Convert a code sequence into a unicode string after recognition." l = self.codec.decode(l) return u"".join(l) def trainString(self,xs,s,update=1): "Perform training with a string. This uses the codec and normalizer." return self.trainSequence(xs,self.s2l(s),update=update) def predictString(self,xs): "Predict output as a string. This uses codec and normalizer." cs = self.predictSequence(xs) return self.l2s(cs) class Codec: """Translate between integer codes and characters.""" def init(self,charset): charset = sorted(list(set(charset))) self.code2char = {} self.char2code = {} for code,char in enumerate(charset): self.code2char[code] = char self.char2code[char] = code return self def size(self): """The total number of codes (use this for the number of output classes when training a classifier.""" return len(list(self.code2char.keys())) def encode(self,s): "Encode the string `s` into a code sequence." # tab = self.char2code dflt = self.char2code["~"] return [self.char2code.get(c,dflt) for c in s] def decode(self,l): "Decode a code sequence into a string." s = [self.code2char.get(c,"~") for c in l] return s ascii_labels = [""," ","~"] + [unichr(x) for x in range(33,126)] def ascii_codec(): "Create a codec containing just ASCII characters." return Codec().init(ascii_labels) def ocropus_codec(): """Create a codec containing ASCII characters plus the default character set from ocrolib.""" import ocrolib base = [c for c in ascii_labels] base_set = set(base) extra = [c for c in ocrolib.chars.default if c not in base_set] return Codec().init(base+extra) def getstates_for_display(net): """Get internal states of an LSTM network for making nice state plots. This only works on a few types of LSTM.""" if isinstance(net,LSTM): return net.state[:net.last_n] if isinstance(net,Stacked) and isinstance(net.nets[0],LSTM): return net.nets[0].state[:net.nets[0].last_n] return None
{ "repo_name": "zuphilip/ocropy", "path": "ocrolib/lstm.py", "copies": "1", "size": "38186", "license": "apache-2.0", "hash": -2337910622605893000, "line_mean": 37.3778894472, "line_max": 108, "alpha_frac": 0.603755303, "autogenerated": false, "ratio": 3.5334505413158137, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.953849537137212, "avg_score": 0.0197420945887389, "num_lines": 995 }
"""An implementation of Matching Tensor Layer.""" import typing import numpy as np import tensorflow as tf from keras import backend as K from keras.engine import Layer from keras.initializers import constant class MatchingTensorLayer(Layer): """ Layer that captures the basic interactions between two tensors. :param channels: Number of word interaction tensor channels :param normalize: Whether to L2-normalize samples along the dot product axis before taking the dot product. If set to True, then the output of the dot product is the cosine proximity between the two samples. :param init_diag: Whether to initialize the diagonal elements of the matrix. :param kwargs: Standard layer keyword arguments. Examples: >>> import matchzoo as mz >>> layer = mz.contrib.layers.MatchingTensorLayer(channels=4, ... normalize=True, ... init_diag=True) >>> num_batch, left_len, right_len, num_dim = 5, 3, 2, 10 >>> layer.build([[num_batch, left_len, num_dim], ... [num_batch, right_len, num_dim]]) """ def __init__(self, channels: int = 4, normalize: bool = True, init_diag: bool = True, **kwargs): """:class:`MatchingTensorLayer` constructor.""" super().__init__(**kwargs) self._channels = channels self._normalize = normalize self._init_diag = init_diag self._shape1 = None self._shape2 = None def build(self, input_shape: list): """ Build the layer. :param input_shape: the shapes of the input tensors, for MatchingTensorLayer we need two input tensors. """ # Used purely for shape validation. if not isinstance(input_shape, list) or len(input_shape) != 2: raise ValueError('A `MatchingTensorLayer` layer should be called ' 'on a list of 2 inputs.') self._shape1 = input_shape[0] self._shape2 = input_shape[1] for idx in (0, 2): if self._shape1[idx] != self._shape2[idx]: raise ValueError( 'Incompatible dimensions: ' f'{self._shape1[idx]} != {self._shape2[idx]}.' f'Layer shapes: {self._shape1}, {self._shape2}.' ) if self._init_diag: interaction_matrix = np.float32( np.random.uniform( -0.05, 0.05, [self._channels, self._shape1[2], self._shape2[2]] ) ) for channel_index in range(self._channels): np.fill_diagonal(interaction_matrix[channel_index], 0.1) self.interaction_matrix = self.add_weight( name='interaction_matrix', shape=(self._channels, self._shape1[2], self._shape2[2]), initializer=constant(interaction_matrix), trainable=True ) else: self.interaction_matrix = self.add_weight( name='interaction_matrix', shape=(self._channels, self._shape1[2], self._shape2[2]), initializer='uniform', trainable=True ) super(MatchingTensorLayer, self).build(input_shape) def call(self, inputs: list, **kwargs) -> typing.Any: """ The computation logic of MatchingTensorLayer. :param inputs: two input tensors. """ x1 = inputs[0] x2 = inputs[1] # Normalize x1 and x2 if self._normalize: x1 = K.l2_normalize(x1, axis=2) x2 = K.l2_normalize(x2, axis=2) # b = batch size # l = length of `x1` # r = length of `x2` # d, e = embedding size # c = number of channels # output = [b, c, l, r] output = tf.einsum( 'bld,cde,bre->bclr', x1, self.interaction_matrix, x2 ) return output def compute_output_shape(self, input_shape: list) -> tuple: """ Calculate the layer output shape. :param input_shape: the shapes of the input tensors, for MatchingTensorLayer we need two input tensors. """ if not isinstance(input_shape, list) or len(input_shape) != 2: raise ValueError('A `MatchingTensorLayer` layer should be called ' 'on a list of 2 inputs.') shape1 = list(input_shape[0]) shape2 = list(input_shape[1]) if len(shape1) != 3 or len(shape2) != 3: raise ValueError('A `MatchingTensorLayer` layer should be called ' 'on 2 inputs with 3 dimensions.') if shape1[0] != shape2[0] or shape1[2] != shape2[2]: raise ValueError('A `MatchingTensorLayer` layer should be called ' 'on 2 inputs with same 0,2 dimensions.') output_shape = [shape1[0], self._channels, shape1[1], shape2[1]] return tuple(output_shape)
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/contrib/layers/matching_tensor_layer.py", "copies": "1", "size": "5169", "license": "apache-2.0", "hash": 8803972556210350000, "line_mean": 37.2888888889, "line_max": 78, "alpha_frac": 0.5451731476, "autogenerated": false, "ratio": 4.233415233415234, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5278588381015233, "avg_score": null, "num_lines": null }
"""An implementation of MatchPyramid Model.""" import typing import keras import matchzoo from matchzoo.engine.base_model import BaseModel from matchzoo.engine.param import Param from matchzoo.engine.param_table import ParamTable from matchzoo.engine import hyper_spaces class MatchPyramid(BaseModel): """ MatchPyramid Model. Examples: >>> model = MatchPyramid() >>> model.params['embedding_output_dim'] = 300 >>> model.params['num_blocks'] = 2 >>> model.params['kernel_count'] = [16, 32] >>> model.params['kernel_size'] = [[3, 3], [3, 3]] >>> model.params['dpool_size'] = [3, 10] >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build() """ @classmethod def get_default_params(cls) -> ParamTable: """:return: model default parameters.""" params = super().get_default_params(with_embedding=True) params.add(Param(name='num_blocks', value=1, desc="Number of convolution blocks.")) params.add(Param(name='kernel_count', value=[32], desc="The kernel count of the 2D convolution " "of each block.")) params.add(Param(name='kernel_size', value=[[3, 3]], desc="The kernel size of the 2D convolution " "of each block.")) params.add(Param(name='activation', value='relu', desc="The activation function.")) params.add(Param(name='dpool_size', value=[3, 10], desc="The max-pooling size of each block.")) params.add(Param( name='padding', value='same', desc="The padding mode in the convolution layer." )) params.add(Param( name='dropout_rate', value=0.0, hyper_space=hyper_spaces.quniform(low=0.0, high=0.8, q=0.01), desc="The dropout rate." )) return params def build(self): """ Build model structure. MatchPyramid text matching as image recognition. """ input_left, input_right = self._make_inputs() input_dpool_index = keras.layers.Input( name='dpool_index', shape=[self._params['input_shapes'][0][0], self._params['input_shapes'][1][0], 2], dtype='int32') embedding = self._make_embedding_layer() embed_left = embedding(input_left) embed_right = embedding(input_right) # Interaction matching_layer = matchzoo.layers.MatchingLayer(matching_type='dot') embed_cross = matching_layer([embed_left, embed_right]) for i in range(self._params['num_blocks']): embed_cross = self._conv_block( embed_cross, self._params['kernel_count'][i], self._params['kernel_size'][i], self._params['padding'], self._params['activation'] ) # Dynamic Pooling dpool_layer = matchzoo.layers.DynamicPoolingLayer( *self._params['dpool_size']) embed_pool = dpool_layer([embed_cross, input_dpool_index]) embed_flat = keras.layers.Flatten()(embed_pool) x = keras.layers.Dropout(rate=self._params['dropout_rate'])(embed_flat) inputs = [input_left, input_right, input_dpool_index] x_out = self._make_output_layer()(x) self._backend = keras.Model(inputs=inputs, outputs=x_out) @classmethod def _conv_block( cls, x, kernel_count: int, kernel_size: int, padding: str, activation: str ) -> typing.Any: output = keras.layers.Conv2D(kernel_count, kernel_size, padding=padding, activation=activation)(x) return output
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/models/match_pyramid.py", "copies": "1", "size": "4014", "license": "apache-2.0", "hash": 1656123595082250200, "line_mean": 34.8392857143, "line_max": 79, "alpha_frac": 0.5401096163, "autogenerated": false, "ratio": 4.18125, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.52213596163, "avg_score": null, "num_lines": null }
"""An implementation of Match-SRNN Model.""" import keras from matchzoo.contrib.layers import MatchingTensorLayer from matchzoo.contrib.layers import SpatialGRU from matchzoo.engine import hyper_spaces from matchzoo.engine.base_model import BaseModel from matchzoo.engine.param import Param from matchzoo.engine.param_table import ParamTable class MatchSRNN(BaseModel): """ Match-SRNN Model. Examples: >>> model = MatchSRNN() >>> model.params['channels'] = 4 >>> model.params['units'] = 10 >>> model.params['dropout_rate'] = 0.0 >>> model.params['direction'] = 'lt' >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build() """ @classmethod def get_default_params(cls) -> ParamTable: """:return: model default parameters.""" params = super().get_default_params(with_embedding=True) params.add(Param(name='channels', value=4, desc="Number of word interaction tensor channels")) params.add(Param(name='units', value=10, desc="Number of SpatialGRU units")) params.add(Param(name='direction', value='lt', desc="Direction of SpatialGRU scanning")) params.add(Param( name='dropout_rate', value=0.0, hyper_space=hyper_spaces.quniform(low=0.0, high=0.8, q=0.01), desc="The dropout rate." )) return params def build(self): """ Build model structure. Match-SRNN: Modeling the Recursive Matching Structure with Spatial RNN """ # Scalar dimensions referenced here: # B = batch size (number of sequences) # D = embedding size # L = `input_left` sequence length # R = `input_right` sequence length # C = number of channels # Left input and right input. # query = [B, L] # doc = [B, R] query, doc = self._make_inputs() # Process left and right input. # embed_query = [B, L, D] # embed_doc = [B, R, D] embedding = self._make_embedding_layer() embed_query = embedding(query) embed_doc = embedding(doc) # Get matching tensor # matching_tensor = [B, C, L, R] matching_tensor_layer = MatchingTensorLayer( channels=self._params['channels']) matching_tensor = matching_tensor_layer([embed_query, embed_doc]) # Apply spatial GRU to the word level interaction tensor # h_ij = [B, U] spatial_gru = SpatialGRU( units=self._params['units'], direction=self._params['direction']) h_ij = spatial_gru(matching_tensor) # Apply Dropout x = keras.layers.Dropout( rate=self._params['dropout_rate'])(h_ij) # Make output layer x_out = self._make_output_layer()(x) self._backend = keras.Model(inputs=[query, doc], outputs=x_out)
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/contrib/models/match_srnn.py", "copies": "1", "size": "3058", "license": "apache-2.0", "hash": -2351120072906550300, "line_mean": 31.8817204301, "line_max": 76, "alpha_frac": 0.571942446, "autogenerated": false, "ratio": 4.013123359580052, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5085065805580051, "avg_score": null, "num_lines": null }
"""An implementation of MultiPerspectiveLayer for Bimpm model.""" import tensorflow as tf from keras import backend as K from keras.engine import Layer from matchzoo.contrib.layers.attention_layer import AttentionLayer class MultiPerspectiveLayer(Layer): """ A keras implementation of multi-perspective layer of BiMPM. For detailed information, see Bilateral Multi-Perspective Matching for Natural Language Sentences, section 3.2. Examples: >>> import matchzoo as mz >>> perspective={'full': True, 'max-pooling': True, ... 'attentive': True, 'max-attentive': True} >>> layer = mz.contrib.layers.MultiPerspectiveLayer( ... att_dim=50, mp_dim=20, perspective=perspective) >>> layer.compute_output_shape( ... [(32, 10, 100), (32, 50), None, (32, 50), None, ... [(32, 40, 100), (32, 50), None, (32, 50), None]]) (32, 10, 83) """ def __init__(self, att_dim: int, mp_dim: int, perspective: dict): """Class initialization.""" super(MultiPerspectiveLayer, self).__init__() self._att_dim = att_dim self._mp_dim = mp_dim self._perspective = perspective @classmethod def list_available_perspectives(cls) -> list: """List available strategy for multi-perspective matching.""" return ['full', 'max-pooling', 'attentive', 'max-attentive'] @property def num_perspective(self): """Get the number of perspectives that is True.""" return sum(self._perspective.values()) def build(self, input_shape: list): """Input shape.""" # The shape of the weights is l * d. if self._perspective.get('full'): self.full_match = MpFullMatch(self._mp_dim) if self._perspective.get('max-pooling'): self.max_pooling_match = MpMaxPoolingMatch(self._mp_dim) if self._perspective.get('attentive'): self.attentive_match = MpAttentiveMatch(self._att_dim, self._mp_dim) if self._perspective.get('max-attentive'): self.max_attentive_match = MpMaxAttentiveMatch(self._att_dim) self.built = True def call(self, x: list, **kwargs): """Call.""" seq_lt, seq_rt = x[:5], x[5:] # unpack seq_left and seq_right # all hidden states, last hidden state of forward pass, # last cell state of forward pass, last hidden state of # backward pass, last cell state of backward pass. lstm_reps_lt, forward_h_lt, _, backward_h_lt, _ = seq_lt lstm_reps_rt, forward_h_rt, _, backward_h_rt, _ = seq_rt match_tensor_list = [] match_dim = 0 if self._perspective.get('full'): # Each forward & backward contextual embedding compare # with the last step of the last time step of the other sentence. h_lt = tf.concat([forward_h_lt, backward_h_lt], axis=-1) full_match_tensor = self.full_match([h_lt, lstm_reps_rt]) match_tensor_list.append(full_match_tensor) match_dim += self._mp_dim + 1 if self._perspective.get('max-pooling'): # Each contextual embedding compare with each contextual embedding. # retain the maximum of each dimension. max_match_tensor = self.max_pooling_match([lstm_reps_lt, lstm_reps_rt]) match_tensor_list.append(max_match_tensor) match_dim += self._mp_dim if self._perspective.get('attentive'): # Each contextual embedding compare with each contextual embedding. # retain sum of weighted mean of each dimension. attentive_tensor = self.attentive_match([lstm_reps_lt, lstm_reps_rt]) match_tensor_list.append(attentive_tensor) match_dim += self._mp_dim + 1 if self._perspective.get('max-attentive'): # Each contextual embedding compare with each contextual embedding. # retain max of weighted mean of each dimension. relevancy_matrix = _calc_relevancy_matrix(lstm_reps_lt, lstm_reps_rt) max_attentive_tensor = self.max_attentive_match([lstm_reps_lt, lstm_reps_rt, relevancy_matrix]) match_tensor_list.append(max_attentive_tensor) match_dim += self._mp_dim + 1 mp_tensor = tf.concat(match_tensor_list, axis=-1) return mp_tensor def compute_output_shape(self, input_shape: list): """Compute output shape.""" shape_a = input_shape[0] match_dim = 0 if self._perspective.get('full'): match_dim += self._mp_dim + 1 if self._perspective.get('max-pooling'): match_dim += self._mp_dim if self._perspective.get('attentive'): match_dim += self._mp_dim + 1 if self._perspective.get('max-attentive'): match_dim += self._mp_dim + 1 return shape_a[0], shape_a[1], match_dim class MpFullMatch(Layer): """Mp Full Match Layer.""" def __init__(self, mp_dim): """Init.""" super(MpFullMatch, self).__init__() self.mp_dim = mp_dim def build(self, input_shapes): """Build.""" # input_shape = input_shapes[0] self.built = True def call(self, x, **kwargs): """Call. """ rep_lt, reps_rt = x att_lt = tf.expand_dims(rep_lt, 1) match_tensor, match_dim = _multi_perspective_match(self.mp_dim, reps_rt, att_lt) # match_tensor => [b, len_rt, mp_dim+1] return match_tensor def compute_output_shape(self, input_shape): """Compute output shape.""" return input_shape[1][0], input_shape[1][1], self.mp_dim + 1 class MpMaxPoolingMatch(Layer): """MpMaxPoolingMatch.""" def __init__(self, mp_dim): """Init.""" super(MpMaxPoolingMatch, self).__init__() self.mp_dim = mp_dim def build(self, input_shapes): """Build.""" d = input_shapes[0][-1] self.kernel = self.add_weight(name='kernel', shape=(1, 1, 1, self.mp_dim, d), initializer='uniform', trainable=True) self.built = True def call(self, x, **kwargs): """Call.""" reps_lt, reps_rt = x # kernel: [1, 1, 1, mp_dim, d] # lstm_lt => [b, len_lt, 1, 1, d] reps_lt = tf.expand_dims(reps_lt, axis=2) reps_lt = tf.expand_dims(reps_lt, axis=2) reps_lt = reps_lt * self.kernel # lstm_rt -> [b, 1, len_rt, 1, d] reps_rt = tf.expand_dims(reps_rt, axis=2) reps_rt = tf.expand_dims(reps_rt, axis=1) match_tensor = _cosine_distance(reps_lt, reps_rt, cosine_norm=False) max_match_tensor = tf.reduce_max(match_tensor, axis=1) # match_tensor => [b, len_rt, m] return max_match_tensor def compute_output_shape(self, input_shape): """Compute output shape.""" return input_shape[1][0], input_shape[1][1], self.mp_dim class MpAttentiveMatch(Layer): """ MpAttentiveMatch Layer. Reference: https://github.com/zhiguowang/BiMPM/blob/master/src/match_utils.py#L188-L193 Examples: >>> import matchzoo as mz >>> layer = mz.contrib.layers.multi_perspective_layer.MpAttentiveMatch( ... att_dim=30, mp_dim=20) >>> layer.compute_output_shape([(32, 10, 100), (32, 40, 100)]) (32, 40, 20) """ def __init__(self, att_dim, mp_dim): """Init.""" super(MpAttentiveMatch, self).__init__() self.att_dim = att_dim self.mp_dim = mp_dim def build(self, input_shapes): """Build.""" # input_shape = input_shapes[0] self.built = True def call(self, x, **kwargs): """Call.""" reps_lt, reps_rt = x[0], x[1] # attention prob matrix attention_layer = AttentionLayer(self.att_dim) attn_prob = attention_layer([reps_rt, reps_lt]) # attention reps att_lt = K.batch_dot(attn_prob, reps_lt) # mp match attn_match_tensor, match_dim = _multi_perspective_match(self.mp_dim, reps_rt, att_lt) return attn_match_tensor def compute_output_shape(self, input_shape): """Compute output shape.""" return input_shape[1][0], input_shape[1][1], self.mp_dim class MpMaxAttentiveMatch(Layer): """MpMaxAttentiveMatch.""" def __init__(self, mp_dim): """Init.""" super(MpMaxAttentiveMatch, self).__init__() self.mp_dim = mp_dim def build(self, input_shapes): """Build.""" # input_shape = input_shapes[0] self.built = True def call(self, x): """Call.""" reps_lt, reps_rt = x[0], x[1] relevancy_matrix = x[2] max_att_lt = cal_max_question_representation(reps_lt, relevancy_matrix) max_attentive_tensor, match_dim = _multi_perspective_match(self.mp_dim, reps_rt, max_att_lt) return max_attentive_tensor def cal_max_question_representation(reps_lt, attn_scores): """ Calculate max_question_representation. :param reps_lt: [batch_size, passage_len, hidden_size] :param attn_scores: [] :return: [batch_size, passage_len, hidden_size]. """ attn_positions = tf.argmax(attn_scores, axis=2) max_reps_lt = collect_representation(reps_lt, attn_positions) return max_reps_lt def collect_representation(representation, positions): """ Collect_representation. :param representation: [batch_size, node_num, feature_dim] :param positions: [batch_size, neighbour_num] :return: [batch_size, neighbour_num]? """ return collect_probs(representation, positions) def collect_final_step_of_lstm(lstm_representation, lengths): """ Collect final step of lstm. :param lstm_representation: [batch_size, len_rt, dim] :param lengths: [batch_size] :return: [batch_size, dim] """ lengths = tf.maximum(lengths, K.zeros_like(lengths)) batch_size = tf.shape(lengths)[0] # shape (batch_size) batch_nums = tf.range(0, limit=batch_size) # shape (batch_size, 2) indices = tf.stack((batch_nums, lengths), axis=1) result = tf.gather_nd(lstm_representation, indices, name='last-forwar-lstm') # [batch_size, dim] return result def collect_probs(probs, positions): """ Collect Probabilities. Reference: https://github.com/zhiguowang/BiMPM/blob/master/src/layer_utils.py#L128-L140 :param probs: [batch_size, chunks_size] :param positions: [batch_size, pair_size] :return: [batch_size, pair_size] """ batch_size = tf.shape(probs)[0] pair_size = tf.shape(positions)[1] # shape (batch_size) batch_nums = K.arange(0, batch_size) # [batch_size, 1] batch_nums = tf.reshape(batch_nums, shape=[-1, 1]) # [batch_size, pair_size] batch_nums = K.tile(batch_nums, [1, pair_size]) # shape (batch_size, pair_size, 2) # Alert: to solve error message positions = tf.cast(positions, tf.int32) indices = tf.stack([batch_nums, positions], axis=2) pair_probs = tf.gather_nd(probs, indices) # pair_probs = tf.reshape(pair_probs, shape=[batch_size, pair_size]) return pair_probs def _multi_perspective_match(mp_dim, reps_rt, att_lt, with_cosine=True, with_mp_cosine=True): """ The core function of zhiguowang's implementation. reference: https://github.com/zhiguowang/BiMPM/blob/master/src/match_utils.py#L207-L223 :param mp_dim: about 20 :param reps_rt: [batch, len_rt, dim] :param att_lt: [batch, len_rt, dim] :param with_cosine: True :param with_mp_cosine: True :return: [batch, len, 1 + mp_dim] """ shape_rt = tf.shape(reps_rt) batch_size = shape_rt[0] len_lt = shape_rt[1] match_dim = 0 match_result_list = [] if with_cosine: cosine_tensor = _cosine_distance(reps_rt, att_lt, False) cosine_tensor = tf.reshape(cosine_tensor, [batch_size, len_lt, 1]) match_result_list.append(cosine_tensor) match_dim += 1 if with_mp_cosine: mp_cosine_layer = MpCosineLayer(mp_dim) mp_cosine_tensor = mp_cosine_layer([reps_rt, att_lt]) mp_cosine_tensor = tf.reshape(mp_cosine_tensor, [batch_size, len_lt, mp_dim]) match_result_list.append(mp_cosine_tensor) match_dim += mp_cosine_layer.mp_dim match_result = tf.concat(match_result_list, 2) return match_result, match_dim class MpCosineLayer(Layer): """ Implementation of Multi-Perspective Cosine Distance. Reference: https://github.com/zhiguowang/BiMPM/blob/master/src/match_utils.py#L121-L129 Examples: >>> import matchzoo as mz >>> layer = mz.contrib.layers.multi_perspective_layer.MpCosineLayer( ... mp_dim=50) >>> layer.compute_output_shape([(32, 10, 100), (32, 10, 100)]) (32, 10, 50) """ def __init__(self, mp_dim, **kwargs): """Init.""" self.mp_dim = mp_dim super(MpCosineLayer, self).__init__(**kwargs) def build(self, input_shape): """Build.""" self.kernel = self.add_weight(name='kernel', shape=(1, 1, self.mp_dim, input_shape[0][-1]), initializer='uniform', trainable=True) super(MpCosineLayer, self).build(input_shape) def call(self, x, **kwargs): """Call.""" v1, v2 = x v1 = tf.expand_dims(v1, 2) * self.kernel # [b, s_lt, m, d] v2 = tf.expand_dims(v2, 2) # [b, s_lt, 1, d] return _cosine_distance(v1, v2, False) def compute_output_shape(self, input_shape): """Compute output shape.""" return input_shape[0][0], input_shape[0][1], self.mp_dim def _calc_relevancy_matrix(reps_lt, reps_rt): reps_lt = tf.expand_dims(reps_lt, 1) # [b, 1, len_lt, d] reps_rt = tf.expand_dims(reps_rt, 2) # [b, len_rt, 1, d] relevancy_matrix = _cosine_distance(reps_lt, reps_rt) # => [b, len_rt, len_lt, d] return relevancy_matrix def _mask_relevancy_matrix(relevancy_matrix, mask_lt, mask_rt): """ Mask relevancy matrix. :param relevancy_matrix: [b, len_rt, len_lt] :param mask_lt: [b, len_lt] :param mask_rt: [b, len_rt] :return: masked_matrix: [b, len_rt, len_lt] """ if mask_lt is not None: relevancy_matrix = relevancy_matrix * tf.expand_dims(mask_lt, 1) relevancy_matrix = relevancy_matrix * tf.expand_dims(mask_rt, 2) return relevancy_matrix def _cosine_distance(v1, v2, cosine_norm=True, eps=1e-6): """ Only requires `tf.reduce_sum(v1 * v2, axis=-1)`. :param v1: [batch, time_steps(v1), 1, m, d] :param v2: [batch, 1, time_steps(v2), m, d] :param cosine_norm: True :param eps: 1e-6 :return: [batch, time_steps(v1), time_steps(v2), m] """ cosine_numerator = tf.reduce_sum(v1 * v2, axis=-1) if not cosine_norm: return K.tanh(cosine_numerator) v1_norm = K.sqrt(tf.maximum(tf.reduce_sum(tf.square(v1), axis=-1), eps)) v2_norm = K.sqrt(tf.maximum(tf.reduce_sum(tf.square(v2), axis=-1), eps)) return cosine_numerator / v1_norm / v2_norm
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/contrib/layers/multi_perspective_layer.py", "copies": "1", "size": "16251", "license": "apache-2.0", "hash": -7697306292055920000, "line_mean": 33.7243589744, "line_max": 80, "alpha_frac": 0.5573810842, "autogenerated": false, "ratio": 3.431376689189189, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44887577733891887, "avg_score": null, "num_lines": null }
"""An implementation of MVLSTM Model.""" import keras import tensorflow as tf from matchzoo.engine import hyper_spaces from matchzoo.engine.base_model import BaseModel from matchzoo.engine.param import Param from matchzoo.engine.param_table import ParamTable class MVLSTM(BaseModel): """ MVLSTM Model. Examples: >>> model = MVLSTM() >>> model.params['lstm_units'] = 32 >>> model.params['top_k'] = 50 >>> model.params['mlp_num_layers'] = 2 >>> model.params['mlp_num_units'] = 20 >>> model.params['mlp_num_fan_out'] = 10 >>> model.params['mlp_activation_func'] = 'relu' >>> model.params['dropout_rate'] = 0.5 >>> model.guess_and_fill_missing_params(verbose=0) >>> model.build() """ @classmethod def get_default_params(cls) -> ParamTable: """:return: model default parameters.""" params = super().get_default_params( with_embedding=True, with_multi_layer_perceptron=True) params.add(Param(name='lstm_units', value=32, desc="Integer, the hidden size in the " "bi-directional LSTM layer.")) params.add(Param(name='dropout_rate', value=0.0, desc="Float, the dropout rate.")) params.add(Param( 'top_k', value=10, hyper_space=hyper_spaces.quniform(low=2, high=100), desc="Integer, the size of top-k pooling layer." )) params['optimizer'] = 'adam' return params def build(self): """Build model structure.""" query, doc = self._make_inputs() # Embedding layer embedding = self._make_embedding_layer(mask_zero=True) embed_query = embedding(query) embed_doc = embedding(doc) # Bi-directional LSTM layer rep_query = keras.layers.Bidirectional(keras.layers.LSTM( self._params['lstm_units'], return_sequences=True, dropout=self._params['dropout_rate'] ))(embed_query) rep_doc = keras.layers.Bidirectional(keras.layers.LSTM( self._params['lstm_units'], return_sequences=True, dropout=self._params['dropout_rate'] ))(embed_doc) # Top-k matching layer matching_matrix = keras.layers.Dot( axes=[2, 2], normalize=False)([rep_query, rep_doc]) matching_signals = keras.layers.Reshape((-1,))(matching_matrix) matching_topk = keras.layers.Lambda( lambda x: tf.nn.top_k(x, k=self._params['top_k'], sorted=True)[0] )(matching_signals) # Multilayer perceptron layer. mlp = self._make_multi_layer_perceptron_layer()(matching_topk) mlp = keras.layers.Dropout( rate=self._params['dropout_rate'])(mlp) x_out = self._make_output_layer()(mlp) self._backend = keras.Model(inputs=[query, doc], outputs=x_out)
{ "repo_name": "faneshion/MatchZoo", "path": "matchzoo/models/mvlstm.py", "copies": "1", "size": "2963", "license": "apache-2.0", "hash": -1193117711284654800, "line_mean": 34.6987951807, "line_max": 77, "alpha_frac": 0.5821802227, "autogenerated": false, "ratio": 3.755386565272497, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9837566787972497, "avg_score": 0, "num_lines": 83 }
"""An implementation of qubits and gates acting on them. Todo: * Update docstrings. * Update tests. * Implement apply using decompose. * Implement represent using decompose or something smarter. For this to work we first have to implement represent for SWAP. * Decide if we want upper index to be inclusive in the constructor. * Fix the printing of Rk gates in plotting. """ from __future__ import print_function, division from sympy import Expr, Matrix, exp, I, pi, Integer, Symbol from sympy.core.compatibility import range from sympy.functions import sqrt from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qexpr import QuantumError, QExpr from sympy.matrices import eye from sympy.physics.quantum.tensorproduct import matrix_tensor_product from sympy.physics.quantum.gate import ( Gate, HadamardGate, SwapGate, OneQubitGate, CGate, PhaseGate, TGate, ZGate ) __all__ = [ 'QFT', 'IQFT', 'RkGate', 'Rk' ] #----------------------------------------------------------------------------- # Fourier stuff #----------------------------------------------------------------------------- class RkGate(OneQubitGate): """This is the R_k gate of the QTF.""" gate_name = u'Rk' gate_name_latex = u'R' def __new__(cls, *args): if len(args) != 2: raise QuantumError( 'Rk gates only take two arguments, got: %r' % args ) # For small k, Rk gates simplify to other gates, using these # substitutions give us familiar results for the QFT for small numbers # of qubits. target = args[0] k = args[1] if k == 1: return ZGate(target) elif k == 2: return PhaseGate(target) elif k == 3: return TGate(target) args = cls._eval_args(args) inst = Expr.__new__(cls, *args) inst.hilbert_space = cls._eval_hilbert_space(args) return inst @classmethod def _eval_args(cls, args): # Fall back to this, because Gate._eval_args assumes that args is # all targets and can't contain duplicates. return QExpr._eval_args(args) @property def k(self): return self.label[1] @property def targets(self): return self.label[:1] @property def gate_name_plot(self): return r'$%s_%s$' % (self.gate_name_latex, str(self.k)) def get_target_matrix(self, format='sympy'): if format == 'sympy': return Matrix([[1, 0], [0, exp(Integer(2)*pi*I/(Integer(2)**self.k))]]) raise NotImplementedError( 'Invalid format for the R_k gate: %r' % format) Rk = RkGate class Fourier(Gate): """Superclass of Quantum Fourier and Inverse Quantum Fourier Gates.""" @classmethod def _eval_args(self, args): if len(args) != 2: raise QuantumError( 'QFT/IQFT only takes two arguments, got: %r' % args ) if args[0] >= args[1]: raise QuantumError("Start must be smaller than finish") return Gate._eval_args(args) def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): """ Represents the (I)QFT In the Z Basis """ nqubits = options.get('nqubits', 0) if nqubits == 0: raise QuantumError( 'The number of qubits must be given as nqubits.') if nqubits < self.min_qubits: raise QuantumError( 'The number of qubits %r is too small for the gate.' % nqubits ) size = self.size omega = self.omega #Make a matrix that has the basic Fourier Transform Matrix arrayFT = [[omega**( i*j % size)/sqrt(size) for i in range(size)] for j in range(size)] matrixFT = Matrix(arrayFT) #Embed the FT Matrix in a higher space, if necessary if self.label[0] != 0: matrixFT = matrix_tensor_product(eye(2**self.label[0]), matrixFT) if self.min_qubits < nqubits: matrixFT = matrix_tensor_product( matrixFT, eye(2**(nqubits - self.min_qubits))) return matrixFT @property def targets(self): return range(self.label[0], self.label[1]) @property def min_qubits(self): return self.label[1] @property def size(self): """Size is the size of the QFT matrix""" return 2**(self.label[1] - self.label[0]) @property def omega(self): return Symbol('omega') class QFT(Fourier): """The forward quantum Fourier transform.""" gate_name = u'QFT' gate_name_latex = u'QFT' def decompose(self): """Decomposes QFT into elementary gates.""" start = self.label[0] finish = self.label[1] circuit = 1 for level in reversed(range(start, finish)): circuit = HadamardGate(level)*circuit for i in range(level - start): circuit = CGate(level - i - 1, RkGate(level, i + 2))*circuit for i in range((finish - start)//2): circuit = SwapGate(i + start, finish - i - 1)*circuit return circuit def _apply_operator_Qubit(self, qubits, **options): return qapply(self.decompose()*qubits) def _eval_inverse(self): return IQFT(*self.args) @property def omega(self): return exp(2*pi*I/self.size) class IQFT(Fourier): """The inverse quantum Fourier transform.""" gate_name = u'IQFT' gate_name_latex = u'{QFT^{-1}}' def decompose(self): """Decomposes IQFT into elementary gates.""" start = self.args[0] finish = self.args[1] circuit = 1 for i in range((finish - start)//2): circuit = SwapGate(i + start, finish - i - 1)*circuit for level in range(start, finish): for i in reversed(range(level - start)): circuit = CGate(level - i - 1, RkGate(level, -i - 2))*circuit circuit = HadamardGate(level)*circuit return circuit def _eval_inverse(self): return QFT(*self.args) @property def omega(self): return exp(-2*pi*I/self.size)
{ "repo_name": "souravsingh/sympy", "path": "sympy/physics/quantum/qft.py", "copies": "34", "size": "6297", "license": "bsd-3-clause", "hash": -4286954834484160500, "line_mean": 28.7028301887, "line_max": 83, "alpha_frac": 0.5772590122, "autogenerated": false, "ratio": 3.688927943760984, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
"""An implementation of qubits and gates acting on them. Todo: * Update docstrings. * Update tests. * Implement apply using decompose. * Implement represent using decompose or something smarter. For this to work we first have to implement represent for SWAP. * Decide if we want upper index to be inclusive in the constructor. * Fix the printing of Rk gates in plotting. """ from sympy import Expr, Matrix, exp, I, pi, Integer, Symbol from sympy.functions import sqrt from sympy.physics.quantum.applyops import apply_operators from sympy.physics.quantum.qexpr import QuantumError, QExpr from sympy.matrices.matrices import zeros, eye from sympy.physics.quantum.tensorproduct import matrix_tensor_product from sympy.physics.quantum.gate import ( Gate, HadamardGate, SwapGate, OneQubitGate, CGate, PhaseGate, TGate, ZGate ) __all__ = [ 'QFT', 'IQFT', 'RkGate', 'Rk' ] #----------------------------------------------------------------------------- # Fourier stuff #----------------------------------------------------------------------------- class RkGate(OneQubitGate): """This is the R_k gate of the QTF.""" gate_name = u'Rk' gate_name_latex = u'R' def __new__(cls, *args, **old_assumptions): if len(args) != 2: raise QuantumError( 'Rk gates only take two arguments, got: %r' % args ) # For small k, Rk gates simplify to other gates, using these # substitutions give us familiar results for the QFT for small numbers # of qubits. target = args[0] k = args[1] if k == 1: return ZGate(target) elif k == 2: return PhaseGate(target) elif k == 3: return TGate(target) args = cls._eval_args(args) inst = Expr.__new__(cls, *args, **{'commutative':False}) inst.hilbert_space = cls._eval_hilbert_space(args) return inst @classmethod def _eval_args(cls, args): # Fall back to this, because Gate._eval_args assumes that args is # all targets and can't contain duplicates. return QExpr._eval_args(args) @property def k(self): return self.label[1] @property def targets(self): return self.label[:1] @property def gate_name_plot(self): return r'$%s_%s$' % (self.gate_name_latex, str(self.k)) def get_target_matrix(self, format='sympy'): if format == 'sympy': return Matrix([[1,0],[0,exp(Integer(2)*pi*I/(Integer(2)**self.k))]]) raise NotImplementedError('Invalid format for the R_k gate: %r' % format) Rk = RkGate class Fourier(Gate): """Superclass of Quantum Fourier and Inverse Quantum Fourier Gates.""" @classmethod def _eval_args(self, args): if len(args) != 2: raise QuantumError( 'QFT/IQFT only takes two arguments, got: %r' % args ) if args[0] >= args[1]: raise QuantumError("Start must be smaller than finish") return Gate._eval_args(args) def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): """ Represents the (I)QFT In the Z Basis """ nqubits = options.get('nqubits',0) if nqubits == 0: raise QuantumError('The number of qubits must be given as nqubits.') if nqubits < self.min_qubits: raise QuantumError( 'The number of qubits %r is too small for the gate.' % nqubits ) size = self.size omega = self.omega #Make a matrix that has the basic Fourier Transform Matrix arrayFT = [[omega**(i*j%size)/sqrt(size) for i in range(size)] for j in range(size)] matrixFT = Matrix(arrayFT) #Embed the FT Matrix in a higher space, if necessary if self.label[0] != 0: matrixFT = matrix_tensor_product(eye(2**self.label[0]), matrixFT) if self.min_qubits < nqubits: matrixFT = matrix_tensor_product(matrixFT, eye(2**(nqubits-self.min_qubits))) return matrixFT @property def targets(self): return range(self.label[0],self.label[1]) @property def min_qubits(self): return self.label[1] @property def size(self): """Size is the size of the QFT matrix""" return 2**(self.label[1]-self.label[0]) @property def omega(self): return Symbol('omega') class QFT(Fourier): """The forward quantum Fourier transform.""" gate_name = u'QFT' gate_name_latex = u'QFT' def decompose(self): """Decomposes QFT into elementary gates.""" start = self.label[0] finish = self.label[1] circuit = 1 for level in reversed(range(start, finish)): circuit = HadamardGate(level)*circuit for i in range(level-start): circuit = CGate(level-i-1, RkGate(level, i+2))*circuit for i in range((finish-start)/2): circuit = SwapGate(i+start, finish-i-1)*circuit return circuit def _apply_operator_Qubit(self, qubits, **options): return apply_operators(self.decompose()*qubits) def _eval_inverse(self): return IQFT(*self.args) @property def omega(self): return exp(2*pi*I/self.size) class IQFT(Fourier): """The inverse quantum Fourier transform.""" gate_name = u'IQFT' gate_name_latex = u'{QFT^{-1}}' def decompose(self): """Decomposes IQFT into elementary gates.""" start = self.args[0] finish = self.args[1] circuit = 1 for i in range((finish-start)/2): circuit = SwapGate(i+start, finish-i-1)*circuit for level in range(start, finish): for i in reversed(range(level-start)): circuit = CGate(level-i-1, RkGate(level, -i-2))*circuit circuit = HadamardGate(level)*circuit return circuit def _eval_inverse(self): return QFT(*self.args) @property def omega(self): return exp(-2*pi*I/self.size)
{ "repo_name": "tarballs-are-good/sympy", "path": "sympy/physics/quantum/qft.py", "copies": "1", "size": "6181", "license": "bsd-3-clause", "hash": -285427498167477280, "line_mean": 29.0048543689, "line_max": 92, "alpha_frac": 0.5859893221, "autogenerated": false, "ratio": 3.6423099587507366, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9698643559849287, "avg_score": 0.005931144200289955, "num_lines": 206 }
'''An implementation of several types of Restricted Boltzmann Machines. This code is largely based on the Matlab generously provided by Taylor, Hinton and Roweis, and described in their 2006 NIPS paper, "Modeling Human Motion Using Binary Hidden Variables". Their code and results are available online at http://www.cs.nyu.edu/~gwtaylor/publications/nips2006mhmublv/. There are more RBM implementations in this module than just the Taylor "conditional RBM," though. The basic (non-Temporal) RBM is based on the Taylor, Hinton, and Roweis code, but stripped of the dynamic bias terms and refactored into an object-oriented style. The convolutional RBM code is based on the 2009 ICML paper by Lee, Grosse, Ranganath and Ng, "Convolutional Deep Belief Networks for Scalable Unsupervised Learning of Hierarchical Representations". The mean-covariance RBM is based on XXX. All implementations incorporate an option to train hidden unit biases using a sparsity criterion, as described in the 2008 NIPS paper by Lee, Ekanadham and Ng, "Sparse Deep Belief Net Model for Visual Area V2". Most RBM implementations provide an option to treat visible units as either binary or gaussian. Training networks with gaussian visible units is a tricky dance of parameter-twiddling, but binary units seem quite stable in their learning and convergence properties. Finally, although I have tried to ensure that the code is correct, there are probably many bugs, all of which are my own doing. I wrote this code to get a better intuitive understanding for the RBM family of machine learning algorithms, but I do not claim that the code is useful for a particular purpose or produces state-of-the-art results. Mostly I hope that this code is readable so that others can use it to better understand how this whole RBM thing works. ''' import numpy as np import logging import numpy.random as rng def sigmoid(eta): '''Return the logistic sigmoid function of the argument.''' return 1. / (1. + np.exp(-eta)) def identity(eta): '''Return the identity function of the argument.''' return eta def bernoulli(p): '''Return an array of boolean samples from Bernoulli(p). Parameters ---------- p : ndarray This array should contain values in [0, 1]. Returns ------- An array of the same shape as p. Each value in the result will be a boolean indicating whether a single Bernoulli trial succeeded for the corresponding element of `p`. ''' return rng.rand(*p.shape) < p class RBM(object): '''A Restricted Boltzmann Machine (RBM) is a probabilistic model of data. RBMs have two layers of variables (here called "units," in keeping with neural network terminology) -- a "visible" layer that models data in the world, and a "hidden" layer that is imagined to generate the data in the visible layer. RBMs are inspired by the (unrestricted) Boltzmann Machine, a model from statistical physics in which each unit is connected to all other units, and the states of unobserved variables can be inferred by using a sampling procedure. The full connectivity of an unrestricted Boltzmann Machine makes inference difficult, requiring sampling or some other approximate technique. RBMs restrict this more general model by requiring that the visible and hidden units form a fully connected, undirected, bipartite graph. In this way, each of the visible units is independent from the other visible units when conditioned on the state of the hidden layer, and each of the hidden units is independent of the others when conditioned on the state of the visible layer. This conditional independence makes inference tractable for the units in a single RBM. To "encode" a signal by determining the state of the hidden units given some visible data ("signal"), 1. the signal is presented to the visible units, and 2. the states of the hidden units are sampled from the conditional distribution given the visible data. To "decode" an encoding in the hidden units, 3. the states of the visible units are sampled from the conditional distribution given the states of the hidden units. Once a signal has been encoded and then decoded, 4. the sampled visible units can be compared directly with the original visible data. Training takes place by presenting a number of data points to the network, encoding the data, reconstructing it from the hidden states, and encoding the reconstruction in the hidden units again. Then, using contrastive divergence (Hinton 2002; Hinton & Salakhutdinov 2006), the gradient is approximated using the correlations between visible and hidden units in the first encoding and the same correlations in the second encoding. ''' def __init__(self, num_visible, num_hidden, binary=True, scale=0.001): '''Initialize a restricted boltzmann machine. Parameters ---------- num_visible : int The number of visible units. num_hidden : int The number of hidden units. binary : bool True if the visible units are binary, False if the visible units are normally distributed. scale : float Sample initial weights from N(0, scale). ''' self.weights = scale * rng.randn(num_hidden, num_visible) self.hid_bias = scale * rng.randn(num_hidden, 1) self.vis_bias = scale * rng.randn(num_visible, 1) self._visible = binary and sigmoid or identity @property def num_hidden(self): return len(self.hid_bias) @property def num_visible(self): return len(self.vis_bias) def hidden_expectation(self, visible, bias=0.): '''Given visible data, return the expected hidden unit values.''' return sigmoid(np.dot(self.weights, visible.T) + self.hid_bias + bias) def visible_expectation(self, hidden, bias=0.): '''Given hidden states, return the expected visible unit values.''' return self._visible(np.dot(hidden.T, self.weights) + self.vis_bias.T + bias) def iter_passes(self, visible): '''Repeatedly pass the given visible layer up and then back down. Parameters ---------- visible : ndarray The initial state of the visible layer. Returns ------- Generates a sequence of (visible, hidden) states. The first pair will be the (original visible, resulting hidden) states, followed by pairs containing the values from (visible down-pass, hidden up-pass). ''' while True: hidden = self.hidden_expectation(visible) yield visible, hidden visible = self.visible_expectation(bernoulli(hidden)) def reconstruct(self, visible, passes=1): '''Reconstruct a given visible layer through the hidden layer. Parameters ---------- visible : ndarray The initial state of the visible layer. passes : int The number of up- and down-passes. Returns ------- An array containing the reconstructed visible layer after the specified number of up- and down- passes. ''' for i, (visible, _) in enumerate(self.iter_passes(visible)): if i + 1 == passes: return visible class Trainer(object): ''' ''' def __init__(self, rbm, momentum=0., l2=0., target_sparsity=None): ''' ''' self.rbm = rbm self.momentum = momentum self.l2 = l2 self.target_sparsity = target_sparsity self.grad_weights = np.zeros(rbm.weights.shape, float) self.grad_vis = np.zeros(rbm.vis_bias.shape, float) self.grad_hid = np.zeros(rbm.hid_bias.shape, float) def learn(self, visible, learning_rate=0.2): ''' ''' gradients = self.calculate_gradients(visible) self.apply_gradients(*gradients, learning_rate=learning_rate) def calculate_gradients(self, visible_batch): '''Calculate gradients for a batch of visible data. Returns a 3-tuple of gradients: weights, visible bias, hidden bias. visible_batch: A (batch size, visible units) array of visible data. Each row represents one visible data sample. ''' passes = self.rbm.iter_passes(visible_batch) v0, h0 = passes.next() v1, h1 = passes.next() gw = (np.dot(h0, v0) - np.dot(h1, v1)) / len(visible_batch) gv = (v0 - v1).mean(axis=0) gh = (h0 - h1).mean(axis=1) if self.target_sparsity is not None: gh = self.target_sparsity - h0.mean(axis=1) logging.debug('displacement: %.3g, hidden std: %.3g', np.linalg.norm(gv), h0.std(axis=1).mean()) # make sure we pass ndarrays gv = gv.reshape(gv.shape[0],1) gh = gh.reshape(gh.shape[0],1) return gw, gv, gh def apply_gradients(self, weights, visible, hidden, learning_rate=0.2): ''' ''' def update(name, g, _g, l2=0): target = getattr(self.rbm, name) g *= 1 - self.momentum g += self.momentum * (g - l2 * target) target += learning_rate * g _g[:] = g update('vis_bias', visible, self.grad_vis) update('hid_bias', hidden, self.grad_hid) update('weights', weights, self.grad_weights, self.l2) class Temporal(RBM): '''An RBM that incorporates temporal (dynamic) visible and hidden biases. This RBM is based on work and code by Taylor, Hinton, and Roweis (2006). ''' def __init__(self, num_visible, num_hidden, order, binary=True, scale=0.001): ''' ''' super(TemporalRBM, self).__init__( num_visible, num_hidden, binary=binary, scale=scale) self.order = order self.vis_dyn_bias = scale * rng.randn(order, num_visible, num_visible) self.hid_dyn_bias = scale * rng.randn(order, num_hidden, num_visible) - 1. def iter_passes(self, frames): '''Repeatedly pass the given visible layer up and then back down. Generates the resulting sequence of (visible, hidden) states. visible: An (order, visible units) array containing frames of visible data to "prime" the network. The temporal order of the frames is assumed to be reversed, so frames[0] will be the current visible frame, frames[1] is the previous frame, etc. ''' vdb = self.vis_dyn_bias[0] vis_dyn_bias = collections.deque( [np.dot(self.vis_dyn_bias[i], f).T for i, f in enumerate(frames)], maxlen=self.order) hdb = self.hid_dyn_bias[0] hid_dyn_bias = collections.deque( [np.dot(self.hid_dyn_bias[i], f).T for i, f in enumerate(frames)], maxlen=self.order) visible = frames[0] while True: hidden = self.hidden_expectation(visible, sum(hid_dyn_bias)) yield visible, hidden visible = self.visible_expectation(bernoulli(hidden), sum(vis_dyn_bias)) vis_dyn_bias.append(np.dot(vdb, visible)) hid_dyn_bias.append(np.dot(hdb, visible)) class TemporalTrainer(Trainer): ''' ''' def __init__(self, rbm, momentum=0.2, l2=0.1, target_sparsity=None): ''' ''' super(TemporalTrainer, self).__init__(rbm, momentum, l2, target_sparsity) self.grad_dyn_vis = np.zeros(rbm.hid_dyn_bias.shape, float) self.grad_dyn_hid = np.zeros(rbm.hid_dyn_bias.shape, float) def calculate_gradients(self, frames_batch): '''Calculate gradients using contrastive divergence. Returns a 5-tuple of gradients: weights, visible bias, hidden bias, dynamic visible bias, and dynamic hidden bias. frames_batch: An (order, visible units, batch size) array containing a batch of frames of visible data. Frames are assumed to be reversed temporally, across the order dimension, i.e., frames_batch[0] is the current visible frame in each batch element, frames_batch[1] is the previous visible frame, frames_batch[2] is the one before that, etc. ''' order, _, batch_size = frames_batch.shape assert order == self.rbm.order vis_bias = sum(np.dot(self.rbm.vis_dyn_bias[i], f).T for i, f in enumerate(frames_batch)) hid_bias = sum(np.dot(self.rbm.hid_dyn_bias[i], f).T for i, f in enumerate(frames_batch)) v0 = frames_batch[0].T h0 = self.rbm.hidden_expectation(v0, hid_bias) v1 = self.rbm.visible_expectation(bernoulli(h0), vis_bias) h1 = self.rbm.hidden_expectation(v1, hid_bias) gw = (np.dot(h0.T, v0) - np.dot(h1.T, v1)) / batch_size gv = (v0 - v1).mean(axis=0) gh = (h0 - h1).mean(axis=0) gvd = np.zeros(self.rbm.vis_dyn_bias.shape, float) ghd = np.zeros(self.rbm.hid_dyn_bias.shape, float) v = v0 - self.rbm.vis_bias - vis_bias for i, f in enumerate(frames_batch): gvd[i] += np.dot(v.T, f) ghd[i] += np.dot(h0.T, f) v = v1 - self.rbm.vis_bias - vis_bias for i, f in enumerate(frames_batch): gvd[i] -= np.dot(v.T, f) ghd[i] -= np.dot(h1.T, f) return gw, gv, gh, gvd, ghd def apply_gradients(self, weights, visible, hidden, visible_dyn, hidden_dyn, learning_rate=0.2): ''' ''' def update(name, g, _g, l2=0): target = getattr(self.rbm, name) g *= 1 - self.momentum g += self.momentum * (g - l2 * target) target += learning_rate * g _g[:] = g update('vis_bias', visible, self.grad_vis) update('hid_bias', hidden, self.grad_hid) update('weights', weights, self.grad_weights, self.l2) update('vis_dyn_bias', visible_dyn, self.grad_vis_dyn, self.l2) update('hid_dyn_bias', hidden_dyn, self.grad_hid_dyn, self.l2) import scipy.signal convolve = scipy.signal.convolve class Convolutional(RBM): ''' ''' def __init__(self, num_filters, filter_shape, pool_shape, binary=True, scale=0.001): '''Initialize a convolutional restricted boltzmann machine. num_filters: The number of convolution filters. filter_shape: An ordered pair describing the shape of the filters. pool_shape: An ordered pair describing the shape of the pooling groups. binary: True if the visible units are binary, False if the visible units are normally distributed. scale: Scale initial values by this parameter. ''' self.num_filters = num_filters self.weights = scale * rng.randn(num_filters, *filter_shape) self.vis_bias = scale * rng.randn() self.hid_bias = scale * rng.randn(num_filters) self._visible = binary and sigmoid or identity self._pool_shape = pool_shape def _pool(self, hidden): '''Given activity in the hidden units, pool it into groups.''' _, r, c = hidden.shape rows, cols = self._pool_shape active = np.exp(hidden.T) pool = np.zeros(active.shape, float) for j in range(int(np.ceil(float(c) / cols))): cslice = slice(j * cols, (j + 1) * cols) for i in range(int(np.ceil(float(r) / rows))): mask = (cslice, slice(i * rows, (i + 1) * rows)) pool[mask] = active[mask].sum(axis=0).sum(axis=0) return pool.T def pooled_expectation(self, visible, bias=0.): '''Given visible data, return the expected pooling unit values.''' activation = np.exp(np.array([ convolve(visible, self.weights[k, ::-1, ::-1], 'valid') for k in range(self.num_filters)]).T + self.hid_bias + bias).T return 1. - 1. / (1. + self._pool(activation)) def hidden_expectation(self, visible, bias=0.): '''Given visible data, return the expected hidden unit values.''' activation = np.exp(np.array([ convolve(visible, self.weights[k, ::-1, ::-1], 'valid') for k in range(self.num_filters)]).T + self.hid_bias + bias).T return activation / (1. + self._pool(activation)) def visible_expectation(self, hidden, bias=0.): '''Given hidden states, return the expected visible unit values.''' activation = sum( convolve(hidden[k], self.weights[k], 'full') for k in range(self.num_filters)) + self.vis_bias + bias return self._visible(activation) class ConvolutionalTrainer(Trainer): ''' ''' def calculate_gradients(self, visible): '''Calculate gradients for an instance of visible data. Returns a 3-tuple of gradients: weights, visible bias, hidden bias. visible: A single array of visible data. ''' v0 = visible h0 = self.rbm.hidden_expectation(v0) v1 = self.rbm.visible_expectation(bernoulli(h0)) h1 = self.rbm.hidden_expectation(v1) # h0.shape == h1.shape == (num_filters, visible_rows - filter_rows + 1, visible_columns - filter_columns + 1) # v0.shape == v1.shape == (visible_rows, visible_columns) gw = np.array([ convolve(v0, h0[k, ::-1, ::-1], 'valid') - convolve(v1, h1[k, ::-1, ::-1], 'valid') for k in range(self.rbm.num_filters)]) gv = (v0 - v1).sum() gh = (h0 - h1).sum(axis=-1).sum(axis=-1) if self.target_sparsity is not None: h = self.target_sparsity - self.rbm.hidden_expectation(visible).mean(axis=-1).mean(axis=-1) logging.debug('displacement: %.3g, hidden activations: %.3g', np.linalg.norm(gv), h0.mean(axis=-1).mean(axis=-1).std()) return gw, gv, gh class MeanCovariance(RBM): ''' ''' def __init__(self, num_visible, num_mean, num_precision, scale=0.001): '''Initialize a mean-covariance restricted boltzmann machine. num_visible: The number of visible units. num_mean: The number of units in the hidden mean vector. num_precision: The number of units in the hidden precision vector. ''' super(MeanCovariance, self).__init__( num_visible, num_mean, binary=False, scale=scale) # replace the hidden bias to reflect the precision units. self.hid_bias = scale * rng.randn(num_precision, 1) self.hid_mean = scale * rng.randn(num_mean, 1) self.hid_factor_u = scale * -abs(rng.randn(num_precision - 1)) self.hid_factor_c = scale * -abs(rng.randn(num_precision)) self.hid_factor_l = scale * -abs(rng.randn(num_precision - 1)) self.vis_factor = scale * rng.randn(num_visible, num_precision) @property def hid_factor(self): return (numpy.diag(self.hid_factor_u, 1) + numpy.diag(self.hid_factor_c, 0) + numpy.diag(self.hid_factor_l, -1)) def hidden_expectation(self, visible): '''Given visible data, return the expected hidden unit values.''' z = numpy.dot(visible.T, self.vis_factor) return sigmoid(numpy.dot(z * z, self.hid_factor).T + self.hid_bias) def visible_expectation(self, hidden): '''Given hidden states, return the expected visible unit values.''' z = numpy.diag(numpy.dot(-self.hid_factor.T, hidden)) Sinv = numpy.dot(self.vis_factor, numpy.dot(z, self.vis_factor.T)) return numpy.dot(numpy.dot(numpy.pinv(Sinv), self.weights), self.hid_mean) class MeanCovarianceTrainer(Trainer): ''' '''
{ "repo_name": "mertyildiran/Cerebrum", "path": "cerebrum/neuralnet/elements/rbm.py", "copies": "1", "size": "17740", "license": "mit", "hash": 7332081787800155000, "line_mean": 33.7162426614, "line_max": 111, "alpha_frac": 0.7040586246, "autogenerated": false, "ratio": 3.1554606901458557, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4359519314745856, "avg_score": null, "num_lines": null }
# An implementation of Speck32/64 from collections import namedtuple, defaultdict import speck32_64 DiffPair = namedtuple('DifferentialPair', ['p1', 'c1', 'p2', 'c2']) def main(): speck32_64.ROUNDS = 3 plaintext = 0x12345678 diff = 0x00400000 keytext = 0x1918111009080100 epoch = 500 pairs = [] round_keys = speck32_64.expand_key(keytext) for i in range(epoch): plain = (plaintext + i) % (speck32_64.MOD**2) c1 = speck32_64.encrypt(plain, keytext) c2 = speck32_64.encrypt(plain ^ diff, keytext) pairs += [DiffPair(plain, c1, plain ^ diff, c2)] cand_dict = defaultdict(int) for key_cand in range(256 * 256): for pair in pairs: c1, c2 = pair.c1, pair.c2 L1, R1 = speck32_64.split(c1) L2, R2 = speck32_64.split(c2) L3, R3 = speck32_64.round_function_inverse(L1, R1, key_cand) L4, R4 = speck32_64.round_function_inverse(L2, R2, key_cand) # if L3 ^ L4 == 0x8000 and R3 ^ R4 == 0x840a: if L3 ^ L4 == 0x8100 and R3 ^ R4 == 0x8102: cand_dict[key_cand] += 1 key_3, _ = max(cand_dict.items(), key=lambda x: x[1]) print(key_3) assert key_3 == round_keys[2] if __name__ == "__main__": main() ''' Tue Aug 27 19:40:25 JST 2019 ~/prog/lab/cryptography/crypto-misc/Speck 100% > time pypy pure_diff.py 24957 real 0m0.825s user 0m0.783s sys 0m0.024s Tue Aug 27 19:40:28 JST 2019 ~/prog/lab/cryptography/crypto-misc/Speck 100% > time python pure_diff.py 24957 real 2m6.178s user 2m6.150s sys 0m0.056s '''
{ "repo_name": "elliptic-shiho/crypto_misc", "path": "Speck/pure_diff.py", "copies": "1", "size": "1515", "license": "mit", "hash": 1359774719850077700, "line_mean": 25.1206896552, "line_max": 75, "alpha_frac": 0.6369636964, "autogenerated": false, "ratio": 2.495881383855025, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3632845080255025, "avg_score": null, "num_lines": null }
# An implementation of Speck32/64 # params k = 16 alpha = 7 beta = 2 MOD = 2**k MASK = MOD - 1 ROUNDS = 22 def rol(x, y): assert 0 < y < k, "Can't shift by negative negative shifts" return ((x << y) & MASK) | (x >> (k - y)) def ror(x, y): assert 0 < y < k, "Can't shift by negative negative shifts" return rol(x, k - y) def split(x): return (x >> k, x & MASK) def merge(x, y): return (x << k) | y def round_function(x, y, key): ret_x = ((ror(x, alpha) + y) % MOD) ^ key ret_y = rol(y, beta) ^ ret_x return ret_x, ret_y def round_function_inverse(x, y, key): ret_y = ror(x ^ y, beta) ret_x = rol(((x ^ key) - ret_y) % MOD, alpha) return ret_x, ret_y def encrypt(m, key): keys = expand_key(key) # assert len(keys) == ROUNDS, "Invalid keys specified" x, y = split(m) for i in range(ROUNDS): x, y = round_function(x, y, keys[i]) return merge(x, y) def decrypt(c, key): keys = expand_key(key) x, y = split(c) for i in range(ROUNDS - 1, -1, -1): x, y = round_function_inverse(x, y, keys[i]) return merge(x, y) def expand_key(key): k_words = [] while key != 0: k_words += [key & MASK] key >>= k m = len(k_words) ret = [k_words[0]] ell = k_words[1:] for i in range(ROUNDS - 1): ell += [((ret[i] + ror(ell[i], alpha)) % MOD) ^ i] ret += [rol(ret[i], beta) ^ ell[i + m - 1]] return ret def main(): plaintext = 0x6574694c ciphertext = 0xa86842f2 keytext = 0x1918111009080100 assert encrypt(plaintext, keytext) == ciphertext assert decrypt(ciphertext, keytext) == plaintext if __name__ == "__main__": main()
{ "repo_name": "elliptic-shiho/crypto_misc", "path": "Speck/speck32_64.py", "copies": "1", "size": "1611", "license": "mit", "hash": -3113466928769063400, "line_mean": 18.6463414634, "line_max": 61, "alpha_frac": 0.573556797, "autogenerated": false, "ratio": 2.5410094637223977, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8529453865530534, "avg_score": 0.017022479038372562, "num_lines": 82 }
"""An implementation of SumBasic Algorithm (Partial for sentence selection). Ref: Nenkova A, Vanderwende L. The impact of frequency on summarization[J]. Microsoft Research, Redmond, Washington, Tech. Rep. MSR-TR-2005-101, 2005. Code: Bo """ import os import nltk import math import string import operator from file_reader import File_Reader from collections import defaultdict, OrderedDict import sys reload(sys) sys.setdefaultencoding('utf8') class SentenceSelection: """Select topically import sentences from given document""" def __init__(self): self.fr = File_Reader() self.ratio = os.environ.get("SENTENCE_RATIO") def _load_sentences(self, file_name): """Load sentences from given document Args: file_name: document name to read Return: sentences: sentences read from given document """ return self.fr.read_file(file_name) def _clean_sentences(self, sentences): """Clean sentences, remove digit, punctuation, upper case to lower Args: sentences: sentences to be cleaned Return: sentences_processed: dict of cleaned sentences """ flag = 0 sentence_processed = {} sentences = sentences.decode('utf-8') punc = set(string.punctuation) punc.remove('.') sentences = ''.join([x for x in sentences if not x.isdigit()]) sentences = ''.join([x for x in sentences if x not in punc]) sentences = ''.join([x.lower() for x in sentences]) sentences = ' '.join(sentences.split()) stop_words = nltk.corpus.stopwords.words('english') stemmer = nltk.stem.PorterStemmer() tokenize = nltk.word_tokenize for sentence in sentences.split('.'): sentence = sentence.strip() sentence = [stemmer.stem(word) for word in tokenize( sentence) if not word in stop_words] if sentence: sentence_processed[flag] = sentence flag += 1 return sentence_processed def _word_distribution(self, sentence_processed): """Compute word probabilistic distribution """ word_distr = defaultdict(int) word_count = 0.0 for k in sentence_processed: for word in sentence_processed[k]: word_distr[word] += 1 word_count += 1 for word in word_distr: word_distr[word] = word_distr[word] / word_count return word_distr def _sentence_weight(self, word_distribution, sentence_processed): """Compute weight with respect to sentences Args: word_distribution: probabilistic distribution of terms in document sentence_processed: dict of processed sentences generated by clean_sentences Return: sentence_weight: dict of weight of each sentence """ sentence_weight = {} for sentence_id in sentence_processed: for word in sentence_processed[sentence_id]: if word_distribution[word] and sentence_id in sentence_weight: sentence_weight[sentence_id] += word_distribution[word] else: sentence_weight[sentence_id] = word_distribution[word] sentence_weight[sentence_id] = sentence_weight[ sentence_id] / float(len(sentence_processed[sentence_id])) sentence_weight = sorted(sentence_weight.items( ), key=operator.itemgetter(1), reverse=True) return sentence_weight def _topically_important_sentence(self, sentence_weight, sentences): """Select topically import sentences Args: sentence_weight: dict, weight of sentences computed in sentence_weight sentences: set of sentences Return: sentences_selected: dict, topically important sentences selected """ sentence_length = len(sentence_weight) # how many sentences to retain num_sentences_selected = math.ceil(float(self.ratio) * sentence_length) num_sentences_selected = int(num_sentences_selected) # key of selected sentences sentences_selected_key = [] # dictionary of all sentences sentences_dict = {} flag = 0 for k, v in sentence_weight[0:num_sentences_selected]: sentences_selected_key.append(k) for sentence in sentences.split('.'): if sentence: sentences_dict[flag] = sentence flag += 1 sentences_selected = OrderedDict() for key in sentences_selected_key: sentences_selected[key] = sentences_dict[key] return sentences_selected def prepare_sentences(self, file_name): """Prepare sentences to be parsed Args: file_names(str): string of file names Returns: important_sentences(OrderedDict): OrderedDict of important sentences position:sentence, ordered by importance """ sentences = self._load_sentences(file_name) sentences_cleaned = self._clean_sentences(sentences) distribution = self._word_distribution(sentences_cleaned) sentence_weight = self._sentence_weight( distribution, sentences_cleaned) important_sentences = self._topically_important_sentence( sentence_weight, sentences) return important_sentences
{ "repo_name": "bwanglzu/Automatic_Question_Generation", "path": "aqg/utils/sentence_selection.py", "copies": "1", "size": "5565", "license": "mit", "hash": 6004704151349350000, "line_mean": 34, "line_max": 92, "alpha_frac": 0.6143755615, "autogenerated": false, "ratio": 4.656903765690377, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0014509804664065873, "num_lines": 159 }
"""An implementation of tabbed pages using only standard Tkinter. Originally developed for use in IDLE. Based on tabpage.py. Classes exported: TabbedPageSet -- A Tkinter implementation of a tabbed-page widget. TabSet -- A widget containing tabs (buttons) in one or more rows. """ from tkinter import * class InvalidNameError(Exception): pass class AlreadyExistsError(Exception): pass class TabSet(Frame): """A widget containing tabs (buttons) in one or more rows. Only one tab may be selected at a time. """ def __init__(self, page_set, select_command, tabs=None, n_rows=1, max_tabs_per_row=5, expand_tabs=False, **kw): """Constructor arguments: select_command -- A callable which will be called when a tab is selected. It is called with the name of the selected tab as an argument. tabs -- A list of strings, the names of the tabs. Should be specified in the desired tab order. The first tab will be the default and first active tab. If tabs is None or empty, the TabSet will be initialized empty. n_rows -- Number of rows of tabs to be shown. If n_rows <= 0 or is None, then the number of rows will be decided by TabSet. See _arrange_tabs() for details. max_tabs_per_row -- Used for deciding how many rows of tabs are needed, when the number of rows is not constant. See _arrange_tabs() for details. """ Frame.__init__(self, page_set, **kw) self.select_command = select_command self.n_rows = n_rows self.max_tabs_per_row = max_tabs_per_row self.expand_tabs = expand_tabs self.page_set = page_set self._tabs = {} self._tab2row = {} if tabs: self._tab_names = list(tabs) else: self._tab_names = [] self._selected_tab = None self._tab_rows = [] self.padding_frame = Frame(self, height=2, borderwidth=0, relief=FLAT, background=self.cget('background')) self.padding_frame.pack(side=TOP, fill=X, expand=False) self._arrange_tabs() def add_tab(self, tab_name): """Add a new tab with the name given in tab_name.""" if not tab_name: raise InvalidNameError("Invalid Tab name: '%s'" % tab_name) if tab_name in self._tab_names: raise AlreadyExistsError("Tab named '%s' already exists" %tab_name) self._tab_names.append(tab_name) self._arrange_tabs() def remove_tab(self, tab_name): """Remove the tab named <tab_name>""" if not tab_name in self._tab_names: raise KeyError("No such Tab: '%s" % tab_name) self._tab_names.remove(tab_name) self._arrange_tabs() def set_selected_tab(self, tab_name): """Show the tab named <tab_name> as the selected one""" if tab_name == self._selected_tab: return if tab_name is not None and tab_name not in self._tabs: raise KeyError("No such Tab: '%s" % tab_name) # deselect the current selected tab if self._selected_tab is not None: self._tabs[self._selected_tab].set_normal() self._selected_tab = None if tab_name is not None: # activate the tab named tab_name self._selected_tab = tab_name tab = self._tabs[tab_name] tab.set_selected() # move the tab row with the selected tab to the bottom tab_row = self._tab2row[tab] tab_row.pack_forget() tab_row.pack(side=TOP, fill=X, expand=0) def _add_tab_row(self, tab_names, expand_tabs): if not tab_names: return tab_row = Frame(self) tab_row.pack(side=TOP, fill=X, expand=0) self._tab_rows.append(tab_row) for tab_name in tab_names: tab = TabSet.TabButton(tab_name, self.select_command, tab_row, self) if expand_tabs: tab.pack(side=LEFT, fill=X, expand=True) else: tab.pack(side=LEFT) self._tabs[tab_name] = tab self._tab2row[tab] = tab_row # tab is the last one created in the above loop tab.is_last_in_row = True def _reset_tab_rows(self): while self._tab_rows: tab_row = self._tab_rows.pop() tab_row.destroy() self._tab2row = {} def _arrange_tabs(self): """ Arrange the tabs in rows, in the order in which they were added. If n_rows >= 1, this will be the number of rows used. Otherwise the number of rows will be calculated according to the number of tabs and max_tabs_per_row. In this case, the number of rows may change when adding/removing tabs. """ # remove all tabs and rows while self._tabs: self._tabs.popitem()[1].destroy() self._reset_tab_rows() if not self._tab_names: return if self.n_rows is not None and self.n_rows > 0: n_rows = self.n_rows else: # calculate the required number of rows n_rows = (len(self._tab_names) - 1) // self.max_tabs_per_row + 1 # not expanding the tabs with more than one row is very ugly expand_tabs = self.expand_tabs or n_rows > 1 i = 0 # index in self._tab_names for row_index in range(n_rows): # calculate required number of tabs in this row n_tabs = (len(self._tab_names) - i - 1) // (n_rows - row_index) + 1 tab_names = self._tab_names[i:i + n_tabs] i += n_tabs self._add_tab_row(tab_names, expand_tabs) # re-select selected tab so it is properly displayed selected = self._selected_tab self.set_selected_tab(None) if selected in self._tab_names: self.set_selected_tab(selected) class TabButton(Frame): """A simple tab-like widget.""" bw = 2 # borderwidth def __init__(self, name, select_command, tab_row, tab_set): """Constructor arguments: name -- The tab's name, which will appear in its button. select_command -- The command to be called upon selection of the tab. It is called with the tab's name as an argument. """ Frame.__init__(self, tab_row, borderwidth=self.bw, relief=RAISED) self.name = name self.select_command = select_command self.tab_set = tab_set self.is_last_in_row = False self.button = Radiobutton( self, text=name, command=self._select_event, padx=5, pady=1, takefocus=FALSE, indicatoron=FALSE, highlightthickness=0, selectcolor='', borderwidth=0) self.button.pack(side=LEFT, fill=X, expand=True) self._init_masks() self.set_normal() def _select_event(self, *args): """Event handler for tab selection. With TabbedPageSet, this calls TabbedPageSet.change_page, so that selecting a tab changes the page. Note that this does -not- call set_selected -- it will be called by TabSet.set_selected_tab, which should be called when whatever the tabs are related to changes. """ self.select_command(self.name) return def set_selected(self): """Assume selected look""" self._place_masks(selected=True) def set_normal(self): """Assume normal look""" self._place_masks(selected=False) def _init_masks(self): page_set = self.tab_set.page_set background = page_set.pages_frame.cget('background') # mask replaces the middle of the border with the background color self.mask = Frame(page_set, borderwidth=0, relief=FLAT, background=background) # mskl replaces the bottom-left corner of the border with a normal # left border self.mskl = Frame(page_set, borderwidth=0, relief=FLAT, background=background) self.mskl.ml = Frame(self.mskl, borderwidth=self.bw, relief=RAISED) self.mskl.ml.place(x=0, y=-self.bw, width=2*self.bw, height=self.bw*4) # mskr replaces the bottom-right corner of the border with a normal # right border self.mskr = Frame(page_set, borderwidth=0, relief=FLAT, background=background) self.mskr.mr = Frame(self.mskr, borderwidth=self.bw, relief=RAISED) def _place_masks(self, selected=False): height = self.bw if selected: height += self.bw self.mask.place(in_=self, relx=0.0, x=0, rely=1.0, y=0, relwidth=1.0, width=0, relheight=0.0, height=height) self.mskl.place(in_=self, relx=0.0, x=-self.bw, rely=1.0, y=0, relwidth=0.0, width=self.bw, relheight=0.0, height=height) page_set = self.tab_set.page_set if selected and ((not self.is_last_in_row) or (self.winfo_rootx() + self.winfo_width() < page_set.winfo_rootx() + page_set.winfo_width()) ): # for a selected tab, if its rightmost edge isn't on the # rightmost edge of the page set, the right mask should be one # borderwidth shorter (vertically) height -= self.bw self.mskr.place(in_=self, relx=1.0, x=0, rely=1.0, y=0, relwidth=0.0, width=self.bw, relheight=0.0, height=height) self.mskr.mr.place(x=-self.bw, y=-self.bw, width=2*self.bw, height=height + self.bw*2) # finally, lower the tab set so that all of the frames we just # placed hide it self.tab_set.lower() class TabbedPageSet(Frame): """A Tkinter tabbed-pane widget. Constains set of 'pages' (or 'panes') with tabs above for selecting which page is displayed. Only one page will be displayed at a time. Pages may be accessed through the 'pages' attribute, which is a dictionary of pages, using the name given as the key. A page is an instance of a subclass of Tk's Frame widget. The page widgets will be created (and destroyed when required) by the TabbedPageSet. Do not call the page's pack/place/grid/destroy methods. Pages may be added or removed at any time using the add_page() and remove_page() methods. """ class Page(object): """Abstract base class for TabbedPageSet's pages. Subclasses must override the _show() and _hide() methods. """ uses_grid = False def __init__(self, page_set): self.frame = Frame(page_set, borderwidth=2, relief=RAISED) def _show(self): raise NotImplementedError def _hide(self): raise NotImplementedError class PageRemove(Page): """Page class using the grid placement manager's "remove" mechanism.""" uses_grid = True def _show(self): self.frame.grid(row=0, column=0, sticky=NSEW) def _hide(self): self.frame.grid_remove() class PageLift(Page): """Page class using the grid placement manager's "lift" mechanism.""" uses_grid = True def __init__(self, page_set): super(TabbedPageSet.PageLift, self).__init__(page_set) self.frame.grid(row=0, column=0, sticky=NSEW) self.frame.lower() def _show(self): self.frame.lift() def _hide(self): self.frame.lower() class PagePackForget(Page): """Page class using the pack placement manager's "forget" mechanism.""" def _show(self): self.frame.pack(fill=BOTH, expand=True) def _hide(self): self.frame.pack_forget() def __init__(self, parent, page_names=None, page_class=PageLift, n_rows=1, max_tabs_per_row=5, expand_tabs=False, **kw): """Constructor arguments: page_names -- A list of strings, each will be the dictionary key to a page's widget, and the name displayed on the page's tab. Should be specified in the desired page order. The first page will be the default and first active page. If page_names is None or empty, the TabbedPageSet will be initialized empty. n_rows, max_tabs_per_row -- Parameters for the TabSet which will manage the tabs. See TabSet's docs for details. page_class -- Pages can be shown/hidden using three mechanisms: * PageLift - All pages will be rendered one on top of the other. When a page is selected, it will be brought to the top, thus hiding all other pages. Using this method, the TabbedPageSet will not be resized when pages are switched. (It may still be resized when pages are added/removed.) * PageRemove - When a page is selected, the currently showing page is hidden, and the new page shown in its place. Using this method, the TabbedPageSet may resize when pages are changed. * PagePackForget - This mechanism uses the pack placement manager. When a page is shown it is packed, and when it is hidden it is unpacked (i.e. pack_forget). This mechanism may also cause the TabbedPageSet to resize when the page is changed. """ Frame.__init__(self, parent, **kw) self.page_class = page_class self.pages = {} self._pages_order = [] self._current_page = None self._default_page = None self.columnconfigure(0, weight=1) self.rowconfigure(1, weight=1) self.pages_frame = Frame(self) self.pages_frame.grid(row=1, column=0, sticky=NSEW) if self.page_class.uses_grid: self.pages_frame.columnconfigure(0, weight=1) self.pages_frame.rowconfigure(0, weight=1) # the order of the following commands is important self._tab_set = TabSet(self, self.change_page, n_rows=n_rows, max_tabs_per_row=max_tabs_per_row, expand_tabs=expand_tabs) if page_names: for name in page_names: self.add_page(name) self._tab_set.grid(row=0, column=0, sticky=NSEW) self.change_page(self._default_page) def add_page(self, page_name): """Add a new page with the name given in page_name.""" if not page_name: raise InvalidNameError("Invalid TabPage name: '%s'" % page_name) if page_name in self.pages: raise AlreadyExistsError( "TabPage named '%s' already exists" % page_name) self.pages[page_name] = self.page_class(self.pages_frame) self._pages_order.append(page_name) self._tab_set.add_tab(page_name) if len(self.pages) == 1: # adding first page self._default_page = page_name self.change_page(page_name) def remove_page(self, page_name): """Destroy the page whose name is given in page_name.""" if not page_name in self.pages: raise KeyError("No such TabPage: '%s" % page_name) self._pages_order.remove(page_name) # handle removing last remaining, default, or currently shown page if len(self._pages_order) > 0: if page_name == self._default_page: # set a new default page self._default_page = self._pages_order[0] else: self._default_page = None if page_name == self._current_page: self.change_page(self._default_page) self._tab_set.remove_tab(page_name) page = self.pages.pop(page_name) page.frame.destroy() def change_page(self, page_name): """Show the page whose name is given in page_name.""" if self._current_page == page_name: return if page_name is not None and page_name not in self.pages: raise KeyError("No such TabPage: '%s'" % page_name) if self._current_page is not None: self.pages[self._current_page]._hide() self._current_page = None if page_name is not None: self._current_page = page_name self.pages[page_name]._show() self._tab_set.set_selected_tab(page_name) def _tabbed_pages(parent): # htest # top=Toplevel(parent) x, y = map(int, parent.geometry().split('+')[1:]) top.geometry("+%d+%d" % (x, y + 175)) top.title("Test tabbed pages") tabPage=TabbedPageSet(top, page_names=['Foobar','Baz'], n_rows=0, expand_tabs=False, ) tabPage.pack(side=TOP, expand=TRUE, fill=BOTH) Label(tabPage.pages['Foobar'].frame, text='Foo', pady=20).pack() Label(tabPage.pages['Foobar'].frame, text='Bar', pady=20).pack() Label(tabPage.pages['Baz'].frame, text='Baz').pack() entryPgName=Entry(top) buttonAdd=Button(top, text='Add Page', command=lambda:tabPage.add_page(entryPgName.get())) buttonRemove=Button(top, text='Remove Page', command=lambda:tabPage.remove_page(entryPgName.get())) labelPgName=Label(top, text='name of page to add/remove:') buttonAdd.pack(padx=5, pady=5) buttonRemove.pack(padx=5, pady=5) labelPgName.pack(padx=5) entryPgName.pack(padx=5) if __name__ == '__main__': from idlelib.idle_test.htest import run run(_tabbed_pages)
{ "repo_name": "MalloyPower/parsing-python", "path": "front-end/testsuite-python-lib/Python-3.6.0/Lib/idlelib/tabbedpages.py", "copies": "4", "size": "18375", "license": "mit", "hash": 1623215505980680200, "line_mean": 35.8975903614, "line_max": 80, "alpha_frac": 0.5680544218, "autogenerated": false, "ratio": 3.9246048697137974, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6492659291513798, "avg_score": null, "num_lines": null }
"""An implementation of tabbed pages using only standard Tkinter. Originally developed for use in IDLE. Based on tabpage.py. Classes exported: TabbedPageSet -- A Tkinter implementation of a tabbed-page widget. TabSet -- A widget containing tabs (buttons) in one or more rows. """ from Tkinter import * class InvalidNameError(Exception): pass class AlreadyExistsError(Exception): pass class TabSet(Frame): """A widget containing tabs (buttons) in one or more rows. Only one tab may be selected at a time. """ def __init__(self, page_set, select_command, tabs=None, n_rows=1, max_tabs_per_row=5, expand_tabs=False, **kw): """Constructor arguments: select_command -- A callable which will be called when a tab is selected. It is called with the name of the selected tab as an argument. tabs -- A list of strings, the names of the tabs. Should be specified in the desired tab order. The first tab will be the default and first active tab. If tabs is None or empty, the TabSet will be initialized empty. n_rows -- Number of rows of tabs to be shown. If n_rows <= 0 or is None, then the number of rows will be decided by TabSet. See _arrange_tabs() for details. max_tabs_per_row -- Used for deciding how many rows of tabs are needed, when the number of rows is not constant. See _arrange_tabs() for details. """ Frame.__init__(self, page_set, **kw) self.select_command = select_command self.n_rows = n_rows self.max_tabs_per_row = max_tabs_per_row self.expand_tabs = expand_tabs self.page_set = page_set self._tabs = {} self._tab2row = {} if tabs: self._tab_names = list(tabs) else: self._tab_names = [] self._selected_tab = None self._tab_rows = [] self.padding_frame = Frame(self, height=2, borderwidth=0, relief=FLAT, background=self.cget('background')) self.padding_frame.pack(side=TOP, fill=X, expand=False) self._arrange_tabs() def add_tab(self, tab_name): """Add a new tab with the name given in tab_name.""" if not tab_name: raise InvalidNameError("Invalid Tab name: '%s'" % tab_name) if tab_name in self._tab_names: raise AlreadyExistsError("Tab named '%s' already exists" %tab_name) self._tab_names.append(tab_name) self._arrange_tabs() def remove_tab(self, tab_name): """Remove the tab named <tab_name>""" if not tab_name in self._tab_names: raise KeyError("No such Tab: '%s" % page_name) self._tab_names.remove(tab_name) self._arrange_tabs() def set_selected_tab(self, tab_name): """Show the tab named <tab_name> as the selected one""" if tab_name == self._selected_tab: return if tab_name is not None and tab_name not in self._tabs: raise KeyError("No such Tab: '%s" % page_name) # deselect the current selected tab if self._selected_tab is not None: self._tabs[self._selected_tab].set_normal() self._selected_tab = None if tab_name is not None: # activate the tab named tab_name self._selected_tab = tab_name tab = self._tabs[tab_name] tab.set_selected() # move the tab row with the selected tab to the bottom tab_row = self._tab2row[tab] tab_row.pack_forget() tab_row.pack(side=TOP, fill=X, expand=0) def _add_tab_row(self, tab_names, expand_tabs): if not tab_names: return tab_row = Frame(self) tab_row.pack(side=TOP, fill=X, expand=0) self._tab_rows.append(tab_row) for tab_name in tab_names: tab = TabSet.TabButton(tab_name, self.select_command, tab_row, self) if expand_tabs: tab.pack(side=LEFT, fill=X, expand=True) else: tab.pack(side=LEFT) self._tabs[tab_name] = tab self._tab2row[tab] = tab_row # tab is the last one created in the above loop tab.is_last_in_row = True def _reset_tab_rows(self): while self._tab_rows: tab_row = self._tab_rows.pop() tab_row.destroy() self._tab2row = {} def _arrange_tabs(self): """ Arrange the tabs in rows, in the order in which they were added. If n_rows >= 1, this will be the number of rows used. Otherwise the number of rows will be calculated according to the number of tabs and max_tabs_per_row. In this case, the number of rows may change when adding/removing tabs. """ # remove all tabs and rows for tab_name in self._tabs.keys(): self._tabs.pop(tab_name).destroy() self._reset_tab_rows() if not self._tab_names: return if self.n_rows is not None and self.n_rows > 0: n_rows = self.n_rows else: # calculate the required number of rows n_rows = (len(self._tab_names) - 1) // self.max_tabs_per_row + 1 # not expanding the tabs with more than one row is very ugly expand_tabs = self.expand_tabs or n_rows > 1 i = 0 # index in self._tab_names for row_index in xrange(n_rows): # calculate required number of tabs in this row n_tabs = (len(self._tab_names) - i - 1) // (n_rows - row_index) + 1 tab_names = self._tab_names[i:i + n_tabs] i += n_tabs self._add_tab_row(tab_names, expand_tabs) # re-select selected tab so it is properly displayed selected = self._selected_tab self.set_selected_tab(None) if selected in self._tab_names: self.set_selected_tab(selected) class TabButton(Frame): """A simple tab-like widget.""" bw = 2 # borderwidth def __init__(self, name, select_command, tab_row, tab_set): """Constructor arguments: name -- The tab's name, which will appear in its button. select_command -- The command to be called upon selection of the tab. It is called with the tab's name as an argument. """ Frame.__init__(self, tab_row, borderwidth=self.bw, relief=RAISED) self.name = name self.select_command = select_command self.tab_set = tab_set self.is_last_in_row = False self.button = Radiobutton( self, text=name, command=self._select_event, padx=5, pady=1, takefocus=FALSE, indicatoron=FALSE, highlightthickness=0, selectcolor='', borderwidth=0) self.button.pack(side=LEFT, fill=X, expand=True) self._init_masks() self.set_normal() def _select_event(self, *args): """Event handler for tab selection. With TabbedPageSet, this calls TabbedPageSet.change_page, so that selecting a tab changes the page. Note that this does -not- call set_selected -- it will be called by TabSet.set_selected_tab, which should be called when whatever the tabs are related to changes. """ self.select_command(self.name) return def set_selected(self): """Assume selected look""" self._place_masks(selected=True) def set_normal(self): """Assume normal look""" self._place_masks(selected=False) def _init_masks(self): page_set = self.tab_set.page_set background = page_set.pages_frame.cget('background') # mask replaces the middle of the border with the background color self.mask = Frame(page_set, borderwidth=0, relief=FLAT, background=background) # mskl replaces the bottom-left corner of the border with a normal # left border self.mskl = Frame(page_set, borderwidth=0, relief=FLAT, background=background) self.mskl.ml = Frame(self.mskl, borderwidth=self.bw, relief=RAISED) self.mskl.ml.place(x=0, y=-self.bw, width=2*self.bw, height=self.bw*4) # mskr replaces the bottom-right corner of the border with a normal # right border self.mskr = Frame(page_set, borderwidth=0, relief=FLAT, background=background) self.mskr.mr = Frame(self.mskr, borderwidth=self.bw, relief=RAISED) def _place_masks(self, selected=False): height = self.bw if selected: height += self.bw self.mask.place(in_=self, relx=0.0, x=0, rely=1.0, y=0, relwidth=1.0, width=0, relheight=0.0, height=height) self.mskl.place(in_=self, relx=0.0, x=-self.bw, rely=1.0, y=0, relwidth=0.0, width=self.bw, relheight=0.0, height=height) page_set = self.tab_set.page_set if selected and ((not self.is_last_in_row) or (self.winfo_rootx() + self.winfo_width() < page_set.winfo_rootx() + page_set.winfo_width()) ): # for a selected tab, if its rightmost edge isn't on the # rightmost edge of the page set, the right mask should be one # borderwidth shorter (vertically) height -= self.bw self.mskr.place(in_=self, relx=1.0, x=0, rely=1.0, y=0, relwidth=0.0, width=self.bw, relheight=0.0, height=height) self.mskr.mr.place(x=-self.bw, y=-self.bw, width=2*self.bw, height=height + self.bw*2) # finally, lower the tab set so that all of the frames we just # placed hide it self.tab_set.lower() class TabbedPageSet(Frame): """A Tkinter tabbed-pane widget. Constains set of 'pages' (or 'panes') with tabs above for selecting which page is displayed. Only one page will be displayed at a time. Pages may be accessed through the 'pages' attribute, which is a dictionary of pages, using the name given as the key. A page is an instance of a subclass of Tk's Frame widget. The page widgets will be created (and destroyed when required) by the TabbedPageSet. Do not call the page's pack/place/grid/destroy methods. Pages may be added or removed at any time using the add_page() and remove_page() methods. """ class Page(object): """Abstract base class for TabbedPageSet's pages. Subclasses must override the _show() and _hide() methods. """ uses_grid = False def __init__(self, page_set): self.frame = Frame(page_set, borderwidth=2, relief=RAISED) def _show(self): raise NotImplementedError def _hide(self): raise NotImplementedError class PageRemove(Page): """Page class using the grid placement manager's "remove" mechanism.""" uses_grid = True def _show(self): self.frame.grid(row=0, column=0, sticky=NSEW) def _hide(self): self.frame.grid_remove() class PageLift(Page): """Page class using the grid placement manager's "lift" mechanism.""" uses_grid = True def __init__(self, page_set): super(TabbedPageSet.PageLift, self).__init__(page_set) self.frame.grid(row=0, column=0, sticky=NSEW) self.frame.lower() def _show(self): self.frame.lift() def _hide(self): self.frame.lower() class PagePackForget(Page): """Page class using the pack placement manager's "forget" mechanism.""" def _show(self): self.frame.pack(fill=BOTH, expand=True) def _hide(self): self.frame.pack_forget() def __init__(self, parent, page_names=None, page_class=PageLift, n_rows=1, max_tabs_per_row=5, expand_tabs=False, **kw): """Constructor arguments: page_names -- A list of strings, each will be the dictionary key to a page's widget, and the name displayed on the page's tab. Should be specified in the desired page order. The first page will be the default and first active page. If page_names is None or empty, the TabbedPageSet will be initialized empty. n_rows, max_tabs_per_row -- Parameters for the TabSet which will manage the tabs. See TabSet's docs for details. page_class -- Pages can be shown/hidden using three mechanisms: * PageLift - All pages will be rendered one on top of the other. When a page is selected, it will be brought to the top, thus hiding all other pages. Using this method, the TabbedPageSet will not be resized when pages are switched. (It may still be resized when pages are added/removed.) * PageRemove - When a page is selected, the currently showing page is hidden, and the new page shown in its place. Using this method, the TabbedPageSet may resize when pages are changed. * PagePackForget - This mechanism uses the pack placement manager. When a page is shown it is packed, and when it is hidden it is unpacked (i.e. pack_forget). This mechanism may also cause the TabbedPageSet to resize when the page is changed. """ Frame.__init__(self, parent, **kw) self.page_class = page_class self.pages = {} self._pages_order = [] self._current_page = None self._default_page = None self.columnconfigure(0, weight=1) self.rowconfigure(1, weight=1) self.pages_frame = Frame(self) self.pages_frame.grid(row=1, column=0, sticky=NSEW) if self.page_class.uses_grid: self.pages_frame.columnconfigure(0, weight=1) self.pages_frame.rowconfigure(0, weight=1) # the order of the following commands is important self._tab_set = TabSet(self, self.change_page, n_rows=n_rows, max_tabs_per_row=max_tabs_per_row, expand_tabs=expand_tabs) if page_names: for name in page_names: self.add_page(name) self._tab_set.grid(row=0, column=0, sticky=NSEW) self.change_page(self._default_page) def add_page(self, page_name): """Add a new page with the name given in page_name.""" if not page_name: raise InvalidNameError("Invalid TabPage name: '%s'" % page_name) if page_name in self.pages: raise AlreadyExistsError( "TabPage named '%s' already exists" % page_name) self.pages[page_name] = self.page_class(self.pages_frame) self._pages_order.append(page_name) self._tab_set.add_tab(page_name) if len(self.pages) == 1: # adding first page self._default_page = page_name self.change_page(page_name) def remove_page(self, page_name): """Destroy the page whose name is given in page_name.""" if not page_name in self.pages: raise KeyError("No such TabPage: '%s" % page_name) self._pages_order.remove(page_name) # handle removing last remaining, default, or currently shown page if len(self._pages_order) > 0: if page_name == self._default_page: # set a new default page self._default_page = self._pages_order[0] else: self._default_page = None if page_name == self._current_page: self.change_page(self._default_page) self._tab_set.remove_tab(page_name) page = self.pages.pop(page_name) page.frame.destroy() def change_page(self, page_name): """Show the page whose name is given in page_name.""" if self._current_page == page_name: return if page_name is not None and page_name not in self.pages: raise KeyError("No such TabPage: '%s'" % page_name) if self._current_page is not None: self.pages[self._current_page]._hide() self._current_page = None if page_name is not None: self._current_page = page_name self.pages[page_name]._show() self._tab_set.set_selected_tab(page_name) if __name__ == '__main__': # test dialog root=Tk() tabPage=TabbedPageSet(root, page_names=['Foobar','Baz'], n_rows=0, expand_tabs=False, ) tabPage.pack(side=TOP, expand=TRUE, fill=BOTH) Label(tabPage.pages['Foobar'].frame, text='Foo', pady=20).pack() Label(tabPage.pages['Foobar'].frame, text='Bar', pady=20).pack() Label(tabPage.pages['Baz'].frame, text='Baz').pack() entryPgName=Entry(root) buttonAdd=Button(root, text='Add Page', command=lambda:tabPage.add_page(entryPgName.get())) buttonRemove=Button(root, text='Remove Page', command=lambda:tabPage.remove_page(entryPgName.get())) labelPgName=Label(root, text='name of page to add/remove:') buttonAdd.pack(padx=5, pady=5) buttonRemove.pack(padx=5, pady=5) labelPgName.pack(padx=5) entryPgName.pack(padx=5) root.mainloop()
{ "repo_name": "Southpaw-TACTIC/Team", "path": "src/python/Lib/idlelib/tabbedpages.py", "copies": "6", "size": "18678", "license": "epl-1.0", "hash": 6106131278314845000, "line_mean": 36.1183673469, "line_max": 80, "alpha_frac": 0.5530035336, "autogenerated": false, "ratio": 4.030643072939146, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0010925936084230279, "num_lines": 490 }
# An implementation of the activity selction problem, in which we are given a list of activities # with start time and end time, and then determine the max amount of activities that can be # chosen in a certain time frame. # The input will be of the following format: # Time frame: {start time} {end time} # Number of events: # Event 1: {start time} {end time} # Event 2: {start time} {end time} # ... # Event n: {start time} {end time} def activity_selection (time_frame, events): # first we need to sort the events events.sort(key=lambda event: event[1]) optimal_events = Array.new() current_event = events.shift while current_event != nil and current_event[1] < time_frame[1] # take the element with lowest starting time optimal_events << current_event if current_event[0] >= time_frame[0] # now remove all elements that have conflicting starting time events.shift while optimal_events.last[1] > events.first current_event = events.shift end print_array(optimal_events) end print "Time frame: " time_frame = gets.split(" ") abort "Time frame requires a start time and end time" if time_frame.length != 2 print "Number of events: " num_events = gets.chomp.to_i events = Array.new(num_events) for i in 0...num_events print "Event #{i + 1}: " events[i] = gets.split(" ").each{ |x| x = x.to_i abort "Event time cannot be negative" if x < 0 } abort "Event #{i + 1} requires a start time and end time" if events[i].length != 2 end activity_selection(time_frame, events)
{ "repo_name": "pybae/etc", "path": "Algorithms/activity_selection.py", "copies": "1", "size": "1584", "license": "mit", "hash": 6930080188253518000, "line_mean": 35, "line_max": 96, "alpha_frac": 0.6710858586, "autogenerated": false, "ratio": 3.4813186813186814, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9575115716052304, "avg_score": 0.015457764773275486, "num_lines": 44 }
"""An implementation of the Broyden solver for multi-dimensional root finding """ import time import numpy as np from frankenstein.tools.io_utils import dumpVec, dumpMat def broyden_man(func, x0, params=None, B0=None, max_step=1., \ max_iter=100, xconv=5, fconv=6): """ Inp: func (functor): func(x, *params) = 0 is the equation to be solved Thus func(x, *params) returns a vector of same size as x (x0) x0 (np.array of shape n): Initial guess for the solution params (tuple): extra parameters that f takes B0 (np.array of shape n*n): Initial guess of the inverted Jacobian max_iter (int): Maximum number of iteration """ n = x0.shape[0] if params is None: params = () if B0 is None: # take identity initial guess B0 = np.eye(n) B = B0 xconv = 10.**(-xconv) fconv = 10.**(-fconv) start = time.time() x1 = x0 f1 = func(x1, *params) err_f = np.mean(f1**2.)**0.5 is_converged = False for iteration in range(0, max_iter+1): end = time.time() # print if iteration == 0: print(" iteration: {:3d} err_f: {:.5E} ".format(\ iteration, err_f), flush=True) else: print(" iteration: {:3d} err_x: {:.5E} err_f: {:.5E} " "time-broyd: {: .6f}".format(\ iteration, err_x, err_f, end-start), flush=True) start = time.time() # compute Newton's step dx = -B @ f1 # check x convergence err_x = np.mean(dx**2.)**0.5 if err_x < xconv: print(" Broyden serach is converged with " "err_f: {:.5E}.".format(err_f), flush=True) is_converged = True break elif err_x > max_step: # too large step, deemed failure print(" Step length exceeds threshold. Abort Broyden.", \ flush=True) break # take Newton's step x0 = x1.copy() f0 = f1.copy() x1 = x0 + dx f1 = func(x1, *params) df = f1 - f0 # check f convergence err_f = np.mean(f1**2.)**0.5 if err_f < fconv: print(" Broyden serach is converged with " "err_f: {:.5E}.".format(err_f), flush=True) is_converged = True break # Broyden's or NR's update dB = np.outer((dx - B@df)/(dx.T@B@df), dx.T@B) B += dB return x1, is_converged def newton_man(func, x0, jac=None, J0=None, params=None, max_iter=100, \ xconv=5, fconv=6, max_step=10.): """ Inp: func (functor): func(x, *params) = 0 is the equation to be solved Thus func(x, *params) returns a vector of same size as x (x0) x0 (np.array of shape n): Initial guess for the solution params (tuple): extra parameters that f takes max_iter (int): Maximum number of iteration """ n = x0.shape[0] if params is None: params = () start = time.time() x = x0 J = jac(x, *params) if J0 is None else J0 xconv = 10.**(-xconv) fconv = 10.**(-fconv) f = func(x, *params) err_f = np.mean(f**2.)**0.5 is_converged = False for iteration in range(0, max_iter+1): end = time.time() # print if iteration == 0: print(" iteration: {:3d} err_f: {:.5E} ".format(\ iteration, err_f), flush=True) else: print(" iteration: {:3d} err_x: {:.5E} err_f: {:.5E} " "time-broyd: {: .6f}".format(\ iteration, err_x, err_f, end-start), flush=True) start = time.time() # compute Newton's step dx = -np.linalg.pinv(J) @ f # check x convergence err_x = np.mean(dx**2.)**0.5 if err_x < xconv: print(" NR serach is converged with " "err_f: {:.5E}.".format(err_f), flush=True) is_converged = True break elif err_x > max_step: # too large step, indicates failure print(" Step length exceeds threshold. Abort NR.", \ flush=True) break # take Newton's step x += dx f = func(x, *params) # check f convergence err_f = np.mean(f**2.)**0.5 if err_f < fconv: print(" NR serach is converged with " "err_f: {:.5E}.".format(err_f), flush=True) is_converged = True break # Broyden's or NR's update J = jac(x, *params) return x, is_converged def test_broyden_man(): pass if __name__ == "__main__": test_broyden_man()
{ "repo_name": "hongzhouye/frankenstein", "path": "tools/broyden_man.py", "copies": "1", "size": "4820", "license": "bsd-3-clause", "hash": 8361719442901948000, "line_mean": 28.7530864198, "line_max": 77, "alpha_frac": 0.4991701245, "autogenerated": false, "ratio": 3.299110198494182, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42982803229941824, "avg_score": null, "num_lines": null }
"""An implementation of the Context Tree Switching model. The Context Tree Switching algorithm (Veness et al., 2012) is a variable order Markov model with pleasant regret guarantees. It achieves excellent performance over binary, and more generally small alphabet data. This is a fairly vanilla implementation with readability favoured over performance. """ import math import random import sys from . import fastmath # Parameters of the CTS model. For clarity, we take these as constants. PRIOR_STAY_PROB = 0.5 PRIOR_SPLIT_PROB = 0.5 LOG_PRIOR_STAY_PROB = math.log(PRIOR_STAY_PROB) LOG_PRIOR_SPLIT_PROB = math.log(1.0 - PRIOR_STAY_PROB) # Sampling parameter. The maximum number of rejections before we give up and # sample from the root estimator. MAX_SAMPLE_REJECTIONS = 25 # These define the prior count assigned to each unseen symbol. ESTIMATOR_PRIOR = { 'laplace': (lambda unused_alphabet_size: 1.0), 'jeffreys': (lambda unused_alphabet_size: 0.5), 'perks': (lambda alphabet_size: 1.0 / alphabet_size), } class Error(Exception): """Base exception for the `cts` module.""" pass class Estimator(object): """The estimator for a CTS node. This implements a Dirichlet-multinomial model with specified prior. This class does not perform alphabet checking, and will return invalid probabilities if it is ever fed more than `model.alphabet_size` distinct symbols. Args: model: Reference to CTS model. We expected model.symbol_prior to be a `float`. """ def __init__(self, model): self.counts = {} self.count_total = model.alphabet_size * model.symbol_prior self._model = model def prob(self, symbol): """Returns the probability assigned to this symbol.""" count = self.counts.get(symbol, None) # Allocate new symbols on the fly. if count is None: count = self.counts[symbol] = self._model.symbol_prior return count / self.count_total def update(self, symbol): """Updates our count for the given symbol.""" log_prob = math.log(self.prob(symbol)) self.counts[symbol] = ( self.counts.get(symbol, self._model.symbol_prior) + 1.0) self.count_total += 1.0 return log_prob def sample(self, rejection_sampling): """Samples this estimator's PDF in linear time.""" if rejection_sampling: # Automatically fail if this estimator is empty. if not self.counts: return None else: # TODO(mgbellemare): No need for rejection sampling here -- # renormalize instead. symbol = None while symbol is None: symbol = self._sample_once(use_prior_alphabet=False) return symbol else: if len(self._model.alphabet) < self._model.alphabet_size: raise Error( 'Cannot sample from prior without specifying alphabet') else: return self._sample_once(use_prior_alphabet=True) def _sample_once(self, use_prior_alphabet): """Samples once from the PDF. Args: use_prior_alphabet: If True, we will sample the alphabet given by the model to account for symbols not seen by this estimator. Otherwise, we return None. """ random_index = random.uniform(0, self.count_total) for item, count in self.counts.items(): if random_index < count: return item else: random_index -= count # We reach this point when we sampled a symbol which is not stored in # `self.counts`. if use_prior_alphabet: for symbol in self._model.alphabet: # Ignore symbols already accounted for. if symbol in self.counts: continue elif random_index < self._model.symbol_prior: return symbol else: random_index -= self._model.symbol_prior # Account for numerical errors. if random_index < self._model.symbol_prior: sys.stderr.write('Warning: sampling issues, random_index={}'. format(random_index)) # Return first item by default. return list(self._model.alphabet)[0] else: raise Error('Sampling failure, not enough symbols') else: return None class CTSNode(object): """A node in the CTS tree. Each node contains a base Dirichlet estimator holding the statistics for this particular context, and pointers to its children. """ def __init__(self, model): self._children = {} self._log_stay_prob = LOG_PRIOR_STAY_PROB self._log_split_prob = LOG_PRIOR_SPLIT_PROB # Back pointer to the CTS model object. self._model = model self.estimator = Estimator(model) def update(self, context, symbol): """Updates this node and its children. Recursively updates estimators for all suffixes of context. Each estimator is updated with the given symbol. Also updates the mixing weights. """ lp_estimator = self.estimator.update(symbol) # If not a leaf node, recurse, creating nodes as needed. if len(context) > 0: # We recurse on the last element of the context vector. child = self.get_child(context[-1]) lp_child = child.update(context[:-1], symbol) # This node predicts according to a mixture between its estimator # and its child. lp_node = self.mix_prediction(lp_estimator, lp_child) self.update_switching_weights(lp_estimator, lp_child) return lp_node else: # The log probability of staying at a leaf is log(1) = 0. This # isn't actually used in the code, tho. self._log_stay_prob = 0.0 return lp_estimator def log_prob(self, context, symbol): """Computes the log probability of the symbol in this subtree.""" lp_estimator = math.log(self.estimator.prob(symbol)) if len(context) > 0: # See update() above. More efficient is to avoid creating the # nodes and use a default node, but we omit this for clarity. child = self.get_child(context[-1]) lp_child = child.log_prob(context[:-1], symbol) return self.mix_prediction(lp_estimator, lp_child) else: return lp_estimator def sample(self, context, rejection_sampling): """Samples a symbol in the given context.""" if len(context) > 0: # Determine whether we should use this estimator or our child's. log_prob_stay = (self._log_stay_prob - fastmath.log_add(self._log_stay_prob, self._log_split_prob)) if random.random() < math.exp(log_prob_stay): return self.estimator.sample(rejection_sampling) else: # If using child, recurse. if rejection_sampling: child = self.get_child(context[-1], allocate=False) # We'll request another sample from the tree. if child is None: return None # TODO(mgbellemare): To avoid rampant memory allocation, # it's worthwhile to use a default estimator here rather than # recurse when the child is not allocated. else: child = self.get_child(context[-1]) symbol = child.sample(context[:-1], rejection_sampling) return symbol else: return self.estimator.sample(rejection_sampling) def get_child(self, symbol, allocate=True): """Returns the node corresponding to this symbol. New nodes are created as required, unless allocate is set to False. In this case, None is returned. """ node = self._children.get(symbol, None) # If needed and requested, allocated a new node. if node is None and allocate: node = CTSNode(self._model) self._children[symbol] = node return node def mix_prediction(self, lp_estimator, lp_child): """Returns the mixture x = w * p + (1 - w) * q. Here, w is the posterior probability of using the estimator at this node, versus using recursively calling our child node. The mixture is computed in log space, which makes things slightly trickier. Let log_stay_prob_ = p' = log p, log_split_prob_ = q' = log q. The mixing coefficient w is w = e^p' / (e^p' + e^q'), v = e^q' / (e^p' + e^q'). Then x = (e^{p' w'} + e^{q' v'}) / (e^w' + e^v'). """ numerator = fastmath.log_add(lp_estimator + self._log_stay_prob, lp_child + self._log_split_prob) denominator = fastmath.log_add(self._log_stay_prob, self._log_split_prob) return numerator - denominator def update_switching_weights(self, lp_estimator, lp_child): """Updates the switching weights according to Veness et al. (2012).""" log_alpha = self._model.log_alpha log_1_minus_alpha = self._model.log_1_minus_alpha # Avoid numerical issues with alpha = 1. This reverts to straight up # weighting. if log_1_minus_alpha == 0: self._log_stay_prob += lp_estimator self._log_split_prob += lp_child # Switching rule. It's possible to make this more concise, but we # leave it in full for clarity. else: # Mix in an alpha fraction of the other posterior: # switchingStayPosterior = ((1 - alpha) * stayPosterior # + alpha * splitPosterior) # where here we store the unnormalized posterior. self._log_stay_prob = fastmath.log_add(log_1_minus_alpha + lp_estimator + self._log_stay_prob, log_alpha + lp_child + self._log_split_prob) self._log_split_prob = fastmath.log_add(log_1_minus_alpha + lp_child + self._log_split_prob, log_alpha + lp_estimator + self._log_stay_prob) class CTS(object): """A class implementing Context Tree Switching. This version works with large alphabets. By default it uses a Dirichlet estimator with a Perks prior (works reasonably well for medium-sized, sparse alphabets) at each node. Methods in this class assume a human-readable context ordering, where the last symbol in the context list is the most recent (in the case of sequential prediction). This is slightly unintuitive from a computer's perspective but makes the update more legible. There are also only weak constraints on the alphabet. Basically: don't use more than alphabet_size symbols unless you know what you're doing. These do symbols can be any integers and need not be contiguous. Alternatively, you may set the full alphabet before using the model. This will allow sampling from the model prior (which is otherwise not possible). """ def __init__(self, context_length, alphabet=None, max_alphabet_size=256, symbol_prior='perks'): """CTS constructor. Args: context_length: The number of variables which CTS conditions on. In general, increasing this term increases prediction accuracy and memory usage. alphabet: The alphabet over which we operate, as a `set`. Set to None to allow CTS to dynamically determine the alphabet. max_alphabet_size: The total number of symbols in the alphabet. For character-level prediction, leave it at 256 (or set alphabet). If alphabet is specified, this field is ignored. symbol_prior: (float or string) The prior used within each node's Dirichlet estimator. If a string is given, valid choices are 'dirichlet', 'jeffreys', and 'perks'. This defaults to 'perks'. """ # Total number of symbols processed. self._time = 0.0 self.context_length = context_length # We store the observed alphabet in a set. if alphabet is None: self.alphabet, self.alphabet_size = set(), max_alphabet_size else: self.alphabet, self.alphabet_size = alphabet, len(alphabet) # These are properly set when we call update(). self.log_alpha, self.log_1_minus_alpha = 0.0, 0.0 # If we have an entry for it in our set of default priors, assume it's # one of our named priors. if symbol_prior in ESTIMATOR_PRIOR: self.symbol_prior = ( float(ESTIMATOR_PRIOR[symbol_prior](self.alphabet_size))) else: self.symbol_prior = float(symbol_prior) # Otherwise assume numeric. # Create root. This must happen after setting alphabet & symbol prior. self._root = CTSNode(self) def _check_context(self, context): """Verifies that the given context is of the expected length. Args: context: Context to be verified. """ if self.context_length != len(context): raise Error('Invalid context length, {} != {}' .format(self.context_length, len(context))) def update(self, context, symbol): """Updates the CTS model. Args: context: The context list, of size context_length, describing the variables on which CTS should condition. Context elements are assumed to be ranked in increasing order of importance. For example, in sequential prediction the most recent symbol should be context[-1]. symbol: The symbol observed in this context. Returns: The log-probability assigned to the symbol before the update. Raises: Error: Provided context is of incorrect length. """ # Set the switching parameters. self._time += 1.0 self.log_alpha = math.log(1.0 / (self._time + 1.0)) self.log_1_minus_alpha = math.log(self._time / (self._time + 1.0)) # Nothing in the code actually prevents invalid contexts, but the # math won't work out. self._check_context(context) # Add symbol to seen alphabet. self.alphabet.add(symbol) if len(self.alphabet) > self.alphabet_size: raise Error('Too many distinct symbols') log_prob = self._root.update(context, symbol) return log_prob def log_prob(self, context, symbol): """Queries the CTS model. Args: context: As per ``update()``. symbol: As per ``update()``. Returns: The log-probability of the symbol in the context. Raises: Error: Provided context is of incorrect length. """ self._check_context(context) return self._root.log_prob(context, symbol) def sample(self, context, rejection_sampling=True): """Samples a symbol from the model. Args: context: As per ``update()``. rejection_sampling: Whether to ignore samples from the prior. Returns: A symbol sampled according to the model. The default mode of operation is rejection sampling, which will ignore draws from the prior. This allows us to avoid providing an alphabet in full, and typically produces more pleasing samples (because they are never drawn from data for which we have no prior). If the full alphabet is provided (by setting self.alphabet) then `rejection_sampling` may be set to False. In this case, models may sample symbols in contexts they have never appeared in. This latter mode of operation is the mathematically correct one. """ if self._time == 0 and rejection_sampling: raise Error('Cannot do rejection sampling on prior') self._check_context(context) symbol = self._root.sample(context, rejection_sampling) num_rejections = 0 while rejection_sampling and symbol is None: num_rejections += 1 if num_rejections >= MAX_SAMPLE_REJECTIONS: symbol = self._root.estimator.sample(rejection_sampling=True) # There should be *some* symbol in the root estimator. assert symbol is not None else: symbol = self._root.sample(context, rejection_sampling=True) return symbol class ContextualSequenceModel(object): """A sequence model. This class maintains a context vector, i.e. a list of the most recent observations. It predicts by querying a contextual model (e.g. CTS) with this context vector. """ def __init__(self, model=None, context_length=None, start_symbol=0): """Constructor. Args: model: The model to be used for prediction. If this is none but context_length is not, defaults to CTS(context_length). context_length: If model == None, the length of context for the underlying CTS model. start_symbol: The symbol with which to pad the first context vectors. """ if model is None: if context_length is None: raise ValueError('Must specify model or model parameters') else: self.model = CTS(context_length) else: self.model = model self.context = [start_symbol] * self.model.context_length def observe(self, symbol): """Updates the current context without updating the model. The new context is generated by discarding the oldest symbol and inserting the new symbol in the rightmost position of the context vector. Args: symbol: Observed symbol. """ self.context.append(symbol) self.context = self.context[1:] def update(self, symbol): """Updates the model with the new symbol. The current context is subsequently updated, as per ``observe()``. Args: symbol: Observed symbol. Returns: The log probability of the observed symbol. """ log_prob = self.model.update(self.context, symbol) self.observe(symbol) return log_prob def log_prob(self, symbol): """Computes the log probability of the given symbol. Neither model nor context is subsequently updated. Args: symbol: Observed symbol. Returns: The log probability of the observed symbol. """ return self.model.log_prob(self.context, symbol) def sample(self, rejection_sampling=True): """Samples a symbol according to the current context. Neither model nor context are updated. This may be used in combination with ``observe()`` to generate sample sequences without updating the model (though a die-hard Bayesian would use ``update()`` instead!). Args: rejection_sampling: If set to True, symbols are not drawn from the prior: only observed symbols are output. Setting to False requires specifying the model's alphabet (see ``CTS.__init__`` above). Returns: The sampled symbol. """ return self.model.sample(self.context, rejection_sampling) __all__ = ["CTS", "ContextualSequenceModel"]
{ "repo_name": "mgbellemare/SkipCTS", "path": "python/cts/model.py", "copies": "1", "size": "20650", "license": "apache-2.0", "hash": -1822773059174891500, "line_mean": 37.2407407407, "line_max": 80, "alpha_frac": 0.5847457627, "autogenerated": false, "ratio": 4.50971827910024, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0003432478785404174, "num_lines": 540 }