fix linter errors and warnings

This commit is contained in:
James Tauber
2012-12-01 02:00:03 -05:00
parent cfaebd150f
commit 33cf41b585
24 changed files with 456 additions and 377 deletions

View File

@ -2,8 +2,9 @@ from workspaceStructure import WorkspaceStructure
from slipnet import slipnet from slipnet import slipnet
from workspace import workspace from workspace import workspace
class Bond(WorkspaceStructure): class Bond(WorkspaceStructure):
def __init__(self,source, destination, bondCategory, bondFacet, sourceDescriptor, destinationDescriptor): def __init__(self, source, destination, bondCategory, bondFacet, sourceDescriptor, destinationDescriptor):
WorkspaceStructure.__init__(self) WorkspaceStructure.__init__(self)
self.source = source self.source = source
self.string = self.source.string self.string = self.source.string
@ -38,18 +39,18 @@ class Bond(WorkspaceStructure):
return '<Bond: %s>' % self.__str__() return '<Bond: %s>' % self.__str__()
def __str__(self): def __str__(self):
return '%s bond between %s and %s' % ( self.category.name, self.leftObject, self.rightObject) return '%s bond between %s and %s' % (self.category.name, self.leftObject, self.rightObject)
def buildBond(self): def buildBond(self):
workspace.structures += [ self ] workspace.structures += [self]
self.string.bonds += [ self ] self.string.bonds += [self]
self.category.buffer = 100.0 self.category.buffer = 100.0
if self.directionCategory: if self.directionCategory:
self.directionCategory.buffer = 100.0 self.directionCategory.buffer = 100.0
self.leftObject.rightBond = self self.leftObject.rightBond = self
self.rightObject.leftBond = self self.rightObject.leftBond = self
self.leftObject.bonds += [ self ] self.leftObject.bonds += [self]
self.rightObject.bonds += [ self ] self.rightObject.bonds += [self]
def break_the_structure(self): def break_the_structure(self):
self.breakBond() self.breakBond()
@ -78,7 +79,7 @@ class Bond(WorkspaceStructure):
objekt = self.leftObject.correspondence.objectFromInitial objekt = self.leftObject.correspondence.objectFromInitial
if objekt.leftmost and objekt.rightBond: if objekt.leftmost and objekt.rightBond:
if objekt.rightBond.directionCategory and objekt.rightBond.directionCategory != self.directionCategory: if objekt.rightBond.directionCategory and objekt.rightBond.directionCategory != self.directionCategory:
incompatibles += [ correspondence ] incompatibles += [correspondence]
if self.rightObject.rightmost and self.rightObject.correspondence: if self.rightObject.rightmost and self.rightObject.correspondence:
correspondence = self.rightObject.correspondence correspondence = self.rightObject.correspondence
if self.string == workspace.initial: if self.string == workspace.initial:
@ -87,7 +88,7 @@ class Bond(WorkspaceStructure):
objekt = self.rightObject.correspondence.objectFromInitial objekt = self.rightObject.correspondence.objectFromInitial
if objekt.rightmost and objekt.leftBond: if objekt.rightmost and objekt.leftBond:
if objekt.leftBond.directionCategory and objekt.leftBond.directionCategory != self.directionCategory: if objekt.leftBond.directionCategory and objekt.leftBond.directionCategory != self.directionCategory:
incompatibles += [ correspondence ] incompatibles += [correspondence]
return incompatibles return incompatibles
def updateInternalStrength(self): def updateInternalStrength(self):
@ -104,7 +105,7 @@ class Bond(WorkspaceStructure):
facetFactor = 1.0 facetFactor = 1.0
else: else:
facetFactor = 0.7 facetFactor = 0.7
strength = min(100.0,memberCompatibility * facetFactor * self.category.bondDegreeOfAssociation()) strength = min(100.0, memberCompatibility * facetFactor * self.category.bondDegreeOfAssociation())
self.internalStrength = strength self.internalStrength = strength
def updateExternalStrength(self): def updateExternalStrength(self):
@ -114,21 +115,21 @@ class Bond(WorkspaceStructure):
density = self.localDensity() / 100.0 density = self.localDensity() / 100.0
density = density ** 0.5 * 100.0 density = density ** 0.5 * 100.0
supportFactor = 0.6 ** (1.0 / supporters ** 3) supportFactor = 0.6 ** (1.0 / supporters ** 3)
supportFactor = max(1.0,supportFactor) supportFactor = max(1.0, supportFactor)
strength = supportFactor * density strength = supportFactor * density
self.externalStrength = strength self.externalStrength = strength
def numberOfLocalSupportingBonds(self): def numberOfLocalSupportingBonds(self):
return len([ b for b in self.string.bonds if b.string == self.get_source().string and return len([b for b in self.string.bonds if b.string == self.get_source().string and
self.leftObject.letterDistance(b.leftObject) != 0 and self.leftObject.letterDistance(b.leftObject) != 0 and
self.rightObject.letterDistance(b.rightObject) != 0 and self.rightObject.letterDistance(b.rightObject) != 0 and
self.category == b.category and self.category == b.category and
self.directionCategory == b.directionCategory ]) self.directionCategory == b.directionCategory])
def sameCategories(self,other): def sameCategories(self, other):
return self.category == other.category and self.directionCategory == other.directionCategory return self.category == other.category and self.directionCategory == other.directionCategory
def myEnds(self,object1,object2): def myEnds(self, object1, object2):
if self.get_source() == object1 and self.destination == object2: if self.get_source() == object1 and self.destination == object2:
return True return True
return self.get_source() == object2 and self.destination == object1 return self.get_source() == object2 and self.destination == object1
@ -144,19 +145,19 @@ class Bond(WorkspaceStructure):
if object1.beside(object2): if object1.beside(object2):
slotSum += 1.0 slotSum += 1.0
for bond in self.string.bonds: for bond in self.string.bonds:
if bond != self and self.sameCategories(bond) and self.myEnds(object1,object2): if bond != self and self.sameCategories(bond) and self.myEnds(object1, object2):
supportSum += 1.0 supportSum += 1.0
if slotSum == 0.0: if slotSum == 0.0:
return 0.0 return 0.0
return 100.0 * supportSum / slotSum return 100.0 * supportSum / slotSum
def sameNeighbours(self,other): def sameNeighbours(self, other):
if self.leftObject == other.leftObject: if self.leftObject == other.leftObject:
return True return True
return self.rightObject == other.rightObject return self.rightObject == other.rightObject
def getIncompatibleBonds(self): def getIncompatibleBonds(self):
return [ b for b in self.string.bonds if self.sameNeighbours(b) ] return [b for b in self.string.bonds if self.sameNeighbours(b)]
def get_source(self): def get_source(self):
return self.source return self.source
@ -164,19 +165,20 @@ class Bond(WorkspaceStructure):
def set_source(self, value): def set_source(self, value):
self.source = value self.source = value
def possibleGroupBonds(bondCategory, directionCategory, bondFacet, bonds): def possibleGroupBonds(bondCategory, directionCategory, bondFacet, bonds):
result = [] result = []
for bond in bonds: for bond in bonds:
if bond.category == bondCategory and bond.directionCategory == directionCategory: if bond.category == bondCategory and bond.directionCategory == directionCategory:
result += [ bond ] result += [bond]
else: else:
# a modified bond might be made # a modified bond might be made
if bondCategory == slipnet.sameness: if bondCategory == slipnet.sameness:
return None # a different bond cannot be made here return None # a different bond cannot be made here
if bond.category == bondCategory or bond.directionCategory == directionCategory: if bond.category == bondCategory or bond.directionCategory == directionCategory:
return None # a different bond cannot be made here return None # a different bond cannot be made here
if bond.category == slipnet.sameness: if bond.category == slipnet.sameness:
return None return None
bond = Bond(bond.destination, bond.get_source(), bondCategory, bondFacet, bond.destinationDescriptor, bond.sourceDescriptor) bond = Bond(bond.destination, bond.get_source(), bondCategory, bondFacet, bond.destinationDescriptor, bond.sourceDescriptor)
result += [ bond ] result += [bond]
return result return result

View File

@ -10,56 +10,63 @@ from group import Group
from bond import Bond, possibleGroupBonds from bond import Bond, possibleGroupBonds
from correspondence import Correspondence from correspondence import Correspondence
# some methods common to the codelets # some methods common to the codelets
def __showWhichStringObjectIsFrom(structure): def __showWhichStringObjectIsFrom(structure):
if not structure: if not structure:
return return
whence = 'other' whence = 'other'
if isinstance(structure,WorkspaceObject): if isinstance(structure, WorkspaceObject):
whence='target' whence = 'target'
if structure.string == workspace.initial: if structure.string == workspace.initial:
whence='initial' whence = 'initial'
print 'object chosen = %s from %s string' % ( structure, whence ) print 'object chosen = %s from %s string' % (structure, whence)
def __getScoutSource(slipnode,relevanceMethod,typeName):
initialRelevance = relevanceMethod(workspace.initial,slipnode) def __getScoutSource(slipnode, relevanceMethod, typeName):
targetRelevance = relevanceMethod(workspace.target,slipnode) initialRelevance = relevanceMethod(workspace.initial, slipnode)
targetRelevance = relevanceMethod(workspace.target, slipnode)
initialUnhappiness = workspace.initial.intraStringUnhappiness initialUnhappiness = workspace.initial.intraStringUnhappiness
targetUnhappiness = workspace.target.intraStringUnhappiness targetUnhappiness = workspace.target.intraStringUnhappiness
logging.info('initial : relevance = %d, unhappiness=%d' % (initialRelevance,int(initialUnhappiness)) ) logging.info('initial : relevance = %d, unhappiness=%d' % (initialRelevance, int(initialUnhappiness)))
logging.info('target : relevance = %d, unhappiness=%d' % (targetRelevance,int(targetUnhappiness)) ) logging.info('target : relevance = %d, unhappiness=%d' % (targetRelevance, int(targetUnhappiness)))
string = workspace.initial string = workspace.initial
if utils.random() * (initialRelevance + initialUnhappiness+targetRelevance+targetUnhappiness) > (initialRelevance + initialUnhappiness): if utils.random() * (initialRelevance + initialUnhappiness + targetRelevance + targetUnhappiness) > (initialRelevance + initialUnhappiness):
string = workspace.target string = workspace.target
logging.info('target string selected: %s for %s' % (workspace.target,typeName)) logging.info('target string selected: %s for %s' % (workspace.target, typeName))
else: else:
logging.info('initial string selected: %s for %s' % (workspace.initial,typeName)) logging.info('initial string selected: %s for %s' % (workspace.initial, typeName))
source = chooseUnmodifiedObject('intraStringSalience',string.objects) source = chooseUnmodifiedObject('intraStringSalience', string.objects)
return source return source
def __getBondFacet(source,destination):
bondFacet = chooseBondFacet(source,destination) def __getBondFacet(source, destination):
bondFacet = chooseBondFacet(source, destination)
assert bondFacet assert bondFacet
return bondFacet return bondFacet
def __getDescriptors(bondFacet,source,destination):
def __getDescriptors(bondFacet, source, destination):
sourceDescriptor = source.getDescriptor(bondFacet) sourceDescriptor = source.getDescriptor(bondFacet)
destinationDescriptor = destination.getDescriptor(bondFacet) destinationDescriptor = destination.getDescriptor(bondFacet)
assert sourceDescriptor and destinationDescriptor assert sourceDescriptor and destinationDescriptor
return sourceDescriptor, destinationDescriptor return sourceDescriptor, destinationDescriptor
def __allOppositeMappings(mappings):
return len([ m for m in mappings if m.label != slipnet.opposite ]) == 0
def __structureVsStructure(structure1,weight1,structure2,weight2): def __allOppositeMappings(mappings):
return len([m for m in mappings if m.label != slipnet.opposite]) == 0
def __structureVsStructure(structure1, weight1, structure2, weight2):
structure1.updateStrength() structure1.updateStrength()
structure2.updateStrength() structure2.updateStrength()
weightedStrength1 = temperatureAdjustedValue(structure1.totalStrength * weight1) weightedStrength1 = temperatureAdjustedValue(structure1.totalStrength * weight1)
weightedStrength2 = temperatureAdjustedValue(structure2.totalStrength * weight2) weightedStrength2 = temperatureAdjustedValue(structure2.totalStrength * weight2)
rhs = (weightedStrength1 + weightedStrength2) * utils.random() rhs = (weightedStrength1 + weightedStrength2) * utils.random()
logging.info('%d > %d' % (weightedStrength1,rhs)) logging.info('%d > %d' % (weightedStrength1, rhs))
return weightedStrength1 > rhs return weightedStrength1 > rhs
def __fightItOut(structure, structureWeight, incompatibles, incompatibleWeight): def __fightItOut(structure, structureWeight, incompatibles, incompatibleWeight):
if not (incompatibles and len(incompatibles)): if not (incompatibles and len(incompatibles)):
return True return True
@ -70,9 +77,10 @@ def __fightItOut(structure, structureWeight, incompatibles, incompatibleWeight):
logging.info('won fight with %s' % incompatible) logging.info('won fight with %s' % incompatible)
return True return True
def __fightIncompatibles(incompatibles,structure,name,structureWeight,incompatibleWeight):
def __fightIncompatibles(incompatibles, structure, name, structureWeight, incompatibleWeight):
if len(incompatibles): if len(incompatibles):
if __fightItOut(structure,structureWeight,incompatibles,incompatibleWeight): if __fightItOut(structure, structureWeight, incompatibles, incompatibleWeight):
logging.info('broke the %s' % name) logging.info('broke the %s' % name)
return True return True
logging.info('failed to break %s: Fizzle' % name) logging.info('failed to break %s: Fizzle' % name)
@ -80,6 +88,7 @@ def __fightIncompatibles(incompatibles,structure,name,structureWeight,incompatib
logging.info('no incompatible %s' % name) logging.info('no incompatible %s' % name)
return True return True
def __slippability(conceptMappings): def __slippability(conceptMappings):
for mapping in conceptMappings: for mapping in conceptMappings:
slippiness = mapping.slipability() / 100.0 slippiness = mapping.slipability() / 100.0
@ -88,64 +97,69 @@ def __slippability(conceptMappings):
return True return True
return False return False
# start the actual codelets # start the actual codelets
def breaker(): def breaker():
probabilityOfFizzle = (100.0-Temperature)/100.0 probabilityOfFizzle = (100.0 - Temperature) / 100.0
assert not coinFlip(probabilityOfFizzle) assert not coinFlip(probabilityOfFizzle)
# choose a structure at random # choose a structure at random
structures = [ s for s in workspace.structures if structures = [s for s in workspace.structures if
isinstance(s,Group) or isinstance(s, Group) or
isinstance(s,Bond) or isinstance(s, Bond) or
isinstance(s,Correspondence) ] isinstance(s, Correspondence)]
assert len(structures) assert len(structures)
structure = utils.choice(structures) structure = utils.choice(structures)
__showWhichStringObjectIsFrom(structure) __showWhichStringObjectIsFrom(structure)
breakObjects = [ structure ] breakObjects = [structure]
if isinstance(structure,Bond): if isinstance(structure, Bond):
if structure.source.group and structure.source.group == structure.destination.group: if structure.source.group and structure.source.group == structure.destination.group:
breakObjects += [ structure.source.group ] breakObjects += [structure.source.group]
# try to break all objects # try to break all objects
for structure in breakObjects: for structure in breakObjects:
breakProbability = temperatureAdjustedProbability(structure.totalStrength/100.0) breakProbability = temperatureAdjustedProbability(structure.totalStrength / 100.0)
if coinFlip(breakProbability): if coinFlip(breakProbability):
return return
for structure in breakObjects: for structure in breakObjects:
structure.break_the_structure() structure.break_the_structure()
def bottom_up_description_scout(codelet): def bottom_up_description_scout(codelet):
chosenObject = chooseUnmodifiedObject('totalSalience',workspace.objects) chosenObject = chooseUnmodifiedObject('totalSalience', workspace.objects)
assert chosenObject assert chosenObject
__showWhichStringObjectIsFrom(chosenObject) __showWhichStringObjectIsFrom(chosenObject)
description = chooseRelevantDescriptionByActivation(chosenObject) description = chooseRelevantDescriptionByActivation(chosenObject)
assert description assert description
sliplinks = similarPropertyLinks(description.descriptor) sliplinks = similarPropertyLinks(description.descriptor)
assert sliplinks and len(sliplinks) assert sliplinks and len(sliplinks)
values = [ sliplink.degreeOfAssociation() * sliplink.destination.activation for sliplink in sliplinks ] values = [sliplink.degreeOfAssociation() * sliplink.destination.activation for sliplink in sliplinks]
i = selectListPosition(values) i = selectListPosition(values)
chosen = sliplinks[ i ] chosen = sliplinks[i]
chosenProperty = chosen.destination chosenProperty = chosen.destination
coderack.proposeDescription(chosenObject,chosenProperty.category(),chosenProperty,codelet) coderack.proposeDescription(chosenObject, chosenProperty.category(), chosenProperty, codelet)
def top_down_description_scout(codelet): def top_down_description_scout(codelet):
descriptionType = codelet.arguments[0] descriptionType = codelet.arguments[0]
chosenObject = chooseUnmodifiedObject('totalSalience',workspace.objects) chosenObject = chooseUnmodifiedObject('totalSalience', workspace.objects)
assert chosenObject assert chosenObject
__showWhichStringObjectIsFrom(chosenObject) __showWhichStringObjectIsFrom(chosenObject)
descriptions = chosenObject.getPossibleDescriptions(descriptionType) descriptions = chosenObject.getPossibleDescriptions(descriptionType)
assert descriptions and len(descriptions) assert descriptions and len(descriptions)
values = [ n.activation for n in descriptions ] values = [n.activation for n in descriptions]
i = selectListPosition(values) i = selectListPosition(values)
chosenProperty = descriptions[ i ] chosenProperty = descriptions[i]
coderack.proposeDescription(chosenObject,chosenProperty.category(), chosenProperty,codelet) coderack.proposeDescription(chosenObject, chosenProperty.category(), chosenProperty, codelet)
def description_strength_tester(codelet): def description_strength_tester(codelet):
description = codelet.arguments[0] description = codelet.arguments[0]
description.descriptor.buffer = 100.0 description.descriptor.buffer = 100.0
description.updateStrength() description.updateStrength()
strength = description.totalStrength strength = description.totalStrength
probability = temperatureAdjustedProbability(strength/100.0) probability = temperatureAdjustedProbability(strength / 100.0)
assert formulas.coinFlip(probability) assert formulas.coinFlip(probability)
coderack.newCodelet('description-builder',codelet,strength) coderack.newCodelet('description-builder', codelet, strength)
def description_builder(codelet): def description_builder(codelet):
description = codelet.arguments[0] description = codelet.arguments[0]
@ -156,16 +170,17 @@ def description_builder(codelet):
else: else:
description.build() description.build()
def bottom_up_bond_scout(codelet): def bottom_up_bond_scout(codelet):
source = chooseUnmodifiedObject('intraStringSalience',workspace.objects) source = chooseUnmodifiedObject('intraStringSalience', workspace.objects)
__showWhichStringObjectIsFrom(source) __showWhichStringObjectIsFrom(source)
destination = chooseNeighbour(source) destination = chooseNeighbour(source)
assert destination assert destination
logging.info('destination: %s' % destination) logging.info('destination: %s' % destination)
bondFacet = __getBondFacet(source,destination) bondFacet = __getBondFacet(source, destination)
logging.info('chosen bond facet: %s' % bondFacet.get_name()) logging.info('chosen bond facet: %s' % bondFacet.get_name())
logging.info('Source: %s, destination: %s' % (source,destination)) logging.info('Source: %s, destination: %s' % (source, destination))
sourceDescriptor, destinationDescriptor = __getDescriptors(bondFacet,source,destination) sourceDescriptor, destinationDescriptor = __getDescriptors(bondFacet, source, destination)
logging.info("source descriptor: " + sourceDescriptor.name.upper()) logging.info("source descriptor: " + sourceDescriptor.name.upper())
logging.info("destination descriptior: " + destinationDescriptor.name.upper()) logging.info("destination descriptior: " + destinationDescriptor.name.upper())
category = sourceDescriptor.getBondCategory(destinationDescriptor) category = sourceDescriptor.getBondCategory(destinationDescriptor)
@ -173,15 +188,16 @@ def bottom_up_bond_scout(codelet):
if category == slipnet.identity: if category == slipnet.identity:
category = slipnet.sameness category = slipnet.sameness
logging.info('proposing %s bond ' % category.name) logging.info('proposing %s bond ' % category.name)
coderack.proposeBond(source,destination,category,bondFacet,sourceDescriptor,destinationDescriptor,codelet) coderack.proposeBond(source, destination, category, bondFacet, sourceDescriptor, destinationDescriptor, codelet)
def rule_scout(codelet): def rule_scout(codelet):
assert workspace.numberOfUnreplacedObjects() == 0 assert workspace.numberOfUnreplacedObjects() == 0
changedObjects = [ o for o in workspace.initial.objects if o.changed ] changedObjects = [o for o in workspace.initial.objects if o.changed]
#assert len(changedObjects) < 2 #assert len(changedObjects) < 2
# if there are no changed objects, propose a rule with no changes # if there are no changed objects, propose a rule with no changes
if not changedObjects: if not changedObjects:
return coderack.proposeRule(None,None,None,None,codelet) return coderack.proposeRule(None, None, None, None, codelet)
changed = changedObjects[-1] changed = changedObjects[-1]
# generate a list of distinguishing descriptions for the first object # generate a list of distinguishing descriptions for the first object
@ -190,11 +206,11 @@ def rule_scout(codelet):
objectList = [] objectList = []
position = changed.getDescriptor(slipnet.stringPositionCategory) position = changed.getDescriptor(slipnet.stringPositionCategory)
if position: if position:
objectList += [ position ] objectList += [position]
letter = changed.getDescriptor(slipnet.letterCategory) letter = changed.getDescriptor(slipnet.letterCategory)
otherObjectsOfSameLetter = [ o for o in workspace.initial.objects if not o != changed and o.getDescriptionType(letter) ] otherObjectsOfSameLetter = [o for o in workspace.initial.objects if not o != changed and o.getDescriptionType(letter)]
if not len(otherObjectsOfSameLetter): # then the letter is a distinguishing feature if not len(otherObjectsOfSameLetter): # then the letter is a distinguishing feature
objectList += [ letter ] objectList += [letter]
# if this object corresponds to another object in the workspace # if this object corresponds to another object in the workspace
# objectList = the union of this and the distingushing descriptors # objectList = the union of this and the distingushing descriptors
if changed.correspondence: if changed.correspondence:
@ -204,49 +220,51 @@ def rule_scout(codelet):
for node in objectList: for node in objectList:
node = node.applySlippages(slippages) node = node.applySlippages(slippages)
if targetObject.hasDescription(node) and targetObject.distinguishingDescriptor(node): if targetObject.hasDescription(node) and targetObject.distinguishingDescriptor(node):
newList += [ node ] newList += [node]
objectList = newList # XXX surely this should be += ("the union of this and the distinguishing descriptors") objectList = newList # XXX surely this should be += ("the union of this and the distinguishing descriptors")
assert objectList and len(objectList) assert objectList and len(objectList)
# use conceptual depth to choose a description # use conceptual depth to choose a description
valueList = [] valueList = []
for node in objectList: for node in objectList:
depth = node.conceptualDepth depth = node.conceptualDepth
value = temperatureAdjustedValue(depth) value = temperatureAdjustedValue(depth)
valueList += [ value ] valueList += [value]
i = selectListPosition(valueList) i = selectListPosition(valueList)
descriptor = objectList[ i ] descriptor = objectList[i]
# choose the relation (change the letmost object to..xxxx) i.e. "successor" or "d" # choose the relation (change the letmost object to..xxxx) i.e. "successor" or "d"
objectList = [] objectList = []
if changed.replacement.relation: if changed.replacement.relation:
objectList += [ changed.replacement.relation ] objectList += [changed.replacement.relation]
objectList += [ changed.replacement.objectFromModified.getDescriptor(slipnet.letterCategory) ] objectList += [changed.replacement.objectFromModified.getDescriptor(slipnet.letterCategory)]
# use conceptual depth to choose a relation # use conceptual depth to choose a relation
valueList = [] valueList = []
for node in objectList: for node in objectList:
depth = node.conceptualDepth depth = node.conceptualDepth
value = temperatureAdjustedValue(depth) value = temperatureAdjustedValue(depth)
valueList += [ value ] valueList += [value]
i = selectListPosition(valueList) i = selectListPosition(valueList)
relation = objectList[ i ] relation = objectList[i]
coderack.proposeRule(slipnet.letterCategory,descriptor,slipnet.letter,relation,codelet) coderack.proposeRule(slipnet.letterCategory, descriptor, slipnet.letter, relation, codelet)
def rule_strength_tester(codelet): def rule_strength_tester(codelet):
rule = codelet.arguments[0] rule = codelet.arguments[0]
rule.updateStrength() rule.updateStrength()
probability = temperatureAdjustedProbability(rule.totalStrength / 100.0) probability = temperatureAdjustedProbability(rule.totalStrength / 100.0)
assert utils.random() <= probability assert utils.random() <= probability
coderack.newCodelet('rule-builder',codelet,rule.totalStrength,rule) coderack.newCodelet('rule-builder', codelet, rule.totalStrength, rule)
def replacement_finder(): def replacement_finder():
# choose random letter in initial string # choose random letter in initial string
letters = [ o for o in workspace.initial.objects if isinstance(o,Letter) ] letters = [o for o in workspace.initial.objects if isinstance(o, Letter)]
letterOfInitialString = utils.choice(letters) letterOfInitialString = utils.choice(letters)
logging.info('selected letter in initial string = %s' % letterOfInitialString) logging.info('selected letter in initial string = %s' % letterOfInitialString)
if letterOfInitialString.replacement: if letterOfInitialString.replacement:
logging.info("Replacement already found for %s, so fizzling" % letterOfInitialString) logging.info("Replacement already found for %s, so fizzling" % letterOfInitialString)
return return
position = letterOfInitialString.leftStringPosition position = letterOfInitialString.leftStringPosition
moreLetters = [ o for o in workspace.modified.objects if isinstance(o,Letter) and o.leftStringPosition == position ] moreLetters = [o for o in workspace.modified.objects if isinstance(o, Letter) and o.leftStringPosition == position]
letterOfModifiedString = moreLetters and moreLetters[0] or None letterOfModifiedString = moreLetters and moreLetters[0] or None
assert letterOfModifiedString assert letterOfModifiedString
position -= 1 position -= 1
@ -254,27 +272,28 @@ def replacement_finder():
modifiedAscii = ord(workspace.modifiedString[position]) modifiedAscii = ord(workspace.modifiedString[position])
diff = initialAscii - modifiedAscii diff = initialAscii - modifiedAscii
if abs(diff) < 2: if abs(diff) < 2:
relations = { 0:slipnet.sameness, -1:slipnet.successor, 1:slipnet.predecessor } relations = {0: slipnet.sameness, -1: slipnet.successor, 1: slipnet.predecessor}
relation = relations[diff] relation = relations[diff]
logging.info('Relation found: %s' % relation.name) logging.info('Relation found: %s' % relation.name)
else: else:
relation = None relation = None
logging.info('no relation found') logging.info('no relation found')
letterOfInitialString.replacement = Replacement(letterOfInitialString,letterOfModifiedString,relation) letterOfInitialString.replacement = Replacement(letterOfInitialString, letterOfModifiedString, relation)
if relation != slipnet.sameness: if relation != slipnet.sameness:
letterOfInitialString.changed = True letterOfInitialString.changed = True
workspace.changedObject = letterOfInitialString workspace.changedObject = letterOfInitialString
logging.info('building replacement') logging.info('building replacement')
def top_down_bond_scout__category(codelet): def top_down_bond_scout__category(codelet):
logging.info('top_down_bond_scout__category') logging.info('top_down_bond_scout__category')
category = codelet.arguments[0] category = codelet.arguments[0]
source = __getScoutSource(category,localBondCategoryRelevance,'bond') source = __getScoutSource(category, localBondCategoryRelevance, 'bond')
destination = chooseNeighbour(source) destination = chooseNeighbour(source)
logging.info('source: %s, destination: %s' % (source,destination)) logging.info('source: %s, destination: %s' % (source, destination))
assert destination assert destination
bondFacet = __getBondFacet(source,destination) bondFacet = __getBondFacet(source, destination)
sourceDescriptor, destinationDescriptor = __getDescriptors(bondFacet,source,destination) sourceDescriptor, destinationDescriptor = __getDescriptors(bondFacet, source, destination)
forwardBond = sourceDescriptor.getBondCategory(destinationDescriptor) forwardBond = sourceDescriptor.getBondCategory(destinationDescriptor)
if forwardBond == slipnet.identity: if forwardBond == slipnet.identity:
forwardBond = slipnet.sameness forwardBond = slipnet.sameness
@ -283,37 +302,40 @@ def top_down_bond_scout__category(codelet):
backwardBond = destinationDescriptor.getBondCategory(sourceDescriptor) backwardBond = destinationDescriptor.getBondCategory(sourceDescriptor)
assert category == forwardBond or category == backwardBond assert category == forwardBond or category == backwardBond
if category == forwardBond: if category == forwardBond:
coderack.proposeBond(source,destination,category,bondFacet,sourceDescriptor, destinationDescriptor,codelet) coderack.proposeBond(source, destination, category, bondFacet, sourceDescriptor, destinationDescriptor, codelet)
else: else:
coderack.proposeBond(destination,source,category,bondFacet,destinationDescriptor,sourceDescriptor,codelet) coderack.proposeBond(destination, source, category, bondFacet, destinationDescriptor, sourceDescriptor, codelet)
def top_down_bond_scout__direction(codelet): def top_down_bond_scout__direction(codelet):
direction = codelet.arguments[0] direction = codelet.arguments[0]
source = __getScoutSource(direction,localDirectionCategoryRelevance,'bond') source = __getScoutSource(direction, localDirectionCategoryRelevance, 'bond')
destination = chooseDirectedNeighbor(source,direction) destination = chooseDirectedNeighbor(source, direction)
assert destination assert destination
logging.info('to object: %s' % destination) logging.info('to object: %s' % destination)
bondFacet = __getBondFacet(source,destination) bondFacet = __getBondFacet(source, destination)
sourceDescriptor, destinationDescriptor = __getDescriptors(bondFacet,source,destination) sourceDescriptor, destinationDescriptor = __getDescriptors(bondFacet, source, destination)
category = sourceDescriptor.getBondCategory(destinationDescriptor) category = sourceDescriptor.getBondCategory(destinationDescriptor)
assert category assert category
if category == slipnet.identity: if category == slipnet.identity:
category = slipnet.sameness category = slipnet.sameness
coderack.proposeBond(source,destination,category,bondFacet,sourceDescriptor, destinationDescriptor,codelet) coderack.proposeBond(source, destination, category, bondFacet, sourceDescriptor, destinationDescriptor, codelet)
def bond_strength_tester(codelet): def bond_strength_tester(codelet):
bond = codelet.arguments[0] bond = codelet.arguments[0]
__showWhichStringObjectIsFrom(bond) __showWhichStringObjectIsFrom(bond)
bond.updateStrength() bond.updateStrength()
strength = bond.totalStrength strength = bond.totalStrength
probability = temperatureAdjustedProbability(strength/100.0) probability = temperatureAdjustedProbability(strength / 100.0)
logging.info('bond strength = %d for %s' % (strength,bond)) logging.info('bond strength = %d for %s' % (strength, bond))
assert formulas.coinFlip(probability) assert formulas.coinFlip(probability)
bond.facet.buffer = 100.0 bond.facet.buffer = 100.0
bond.sourceDescriptor.buffer = 100.0 bond.sourceDescriptor.buffer = 100.0
bond.destinationDescriptor.buffer = 100.0 bond.destinationDescriptor.buffer = 100.0
logging.info("succeeded: posting bond-builder") logging.info("succeeded: posting bond-builder")
coderack.newCodelet('bond-builder',codelet,strength) coderack.newCodelet('bond-builder', codelet, strength)
def bond_builder(codelet): def bond_builder(codelet):
bond = codelet.arguments[0] bond = codelet.arguments[0]
@ -331,9 +353,9 @@ def bond_builder(codelet):
logging.info('number of incompatibleBonds: %d' % len(incompatibleBonds)) logging.info('number of incompatibleBonds: %d' % len(incompatibleBonds))
if len(incompatibleBonds): if len(incompatibleBonds):
logging.info('%s' % incompatibleBonds[0]) logging.info('%s' % incompatibleBonds[0])
assert __fightIncompatibles(incompatibleBonds,bond,'bonds',1.0,1.0) assert __fightIncompatibles(incompatibleBonds, bond, 'bonds', 1.0, 1.0)
incompatibleGroups = bond.source.getCommonGroups(bond.destination) incompatibleGroups = bond.source.getCommonGroups(bond.destination)
assert __fightIncompatibles(incompatibleGroups,bond,'groups',1.0,1.0) assert __fightIncompatibles(incompatibleGroups, bond, 'groups', 1.0, 1.0)
# fight all incompatible correspondences # fight all incompatible correspondences
incompatibleCorrespondences = [] incompatibleCorrespondences = []
if bond.leftObject.leftmost or bond.rightObject.rightmost: if bond.leftObject.leftmost or bond.rightObject.rightmost:
@ -341,7 +363,7 @@ def bond_builder(codelet):
incompatibleCorrespondences = bond.getIncompatibleCorrespondences() incompatibleCorrespondences = bond.getIncompatibleCorrespondences()
if incompatibleCorrespondences: if incompatibleCorrespondences:
logging.info("trying to break incompatible correspondences") logging.info("trying to break incompatible correspondences")
assert __fightItOut(bond,2.0,incompatibleCorrespondences,3.0) assert __fightItOut(bond, 2.0, incompatibleCorrespondences, 3.0)
#assert __fightIncompatibles(incompatibleCorrespondences,bond,'correspondences',2.0,3.0) #assert __fightIncompatibles(incompatibleCorrespondences,bond,'correspondences',2.0,3.0)
for incompatible in incompatibleBonds: for incompatible in incompatibleBonds:
incompatible.break_the_structure() incompatible.break_the_structure()
@ -352,19 +374,20 @@ def bond_builder(codelet):
logging.info('building bond %s' % bond) logging.info('building bond %s' % bond)
bond.buildBond() bond.buildBond()
def top_down_group_scout__category(codelet): def top_down_group_scout__category(codelet):
groupCategory = codelet.arguments[0] groupCategory = codelet.arguments[0]
category = groupCategory.getRelatedNode(slipnet.bondCategory) category = groupCategory.getRelatedNode(slipnet.bondCategory)
assert category assert category
source = __getScoutSource(category,localBondCategoryRelevance,'group') source = __getScoutSource(category, localBondCategoryRelevance, 'group')
assert source and not source.spansString() assert source and not source.spansString()
if source.leftmost: if source.leftmost:
direction = slipnet.right direction = slipnet.right
elif source.rightmost: elif source.rightmost:
direction = slipnet.left direction = slipnet.left
else: else:
activations = [ slipnet.left.activation ] activations = [slipnet.left.activation]
activations += [ slipnet.right.activation ] activations += [slipnet.right.activation]
if not selectListPosition(activations): if not selectListPosition(activations):
direction = slipnet.left direction = slipnet.left
else: else:
@ -380,11 +403,11 @@ def top_down_group_scout__category(codelet):
else: else:
firstBond = source.rightBond firstBond = source.rightBond
if not firstBond or firstBond.category != category: if not firstBond or firstBond.category != category:
if category == slipnet.sameness and isinstance(source,Letter): if category == slipnet.sameness and isinstance(source, Letter):
group = Group(source.string,slipnet.samenessGroup, None,slipnet.letterCategory, [ source ], []) group = Group(source.string, slipnet.samenessGroup, None, slipnet.letterCategory, [source], [])
probability = group.singleLetterGroupProbability() probability = group.singleLetterGroupProbability()
assert utils.random() >= probability assert utils.random() >= probability
coderack.proposeSingleLetterGroup( source, codelet) coderack.proposeSingleLetterGroup(source, codelet)
return return
direction = firstBond.directionCategory direction = firstBond.directionCategory
search = True search = True
@ -414,26 +437,27 @@ def top_down_group_scout__category(codelet):
destination = destination.rightBond.rightObject destination = destination.rightBond.rightObject
search = True search = True
assert destination != source assert destination != source
objects = [ source ] objects = [source]
bonds = [] bonds = []
while source != destination: while source != destination:
bonds += [ source.rightBond ] bonds += [source.rightBond]
objects += [ source.rightBond.rightObject ] objects += [source.rightBond.rightObject]
source = source.rightBond.rightObject source = source.rightBond.rightObject
coderack.proposeGroup(objects,bonds,groupCategory,direction,bondFacet,codelet) coderack.proposeGroup(objects, bonds, groupCategory, direction, bondFacet, codelet)
def top_down_group_scout__direction(codelet): def top_down_group_scout__direction(codelet):
direction = codelet.arguments[0] direction = codelet.arguments[0]
source = __getScoutSource(direction,localDirectionCategoryRelevance,'direction') source = __getScoutSource(direction, localDirectionCategoryRelevance, 'direction')
logging.info('source chosen = %s' % source) logging.info('source chosen = %s' % source)
assert not source.spansString() assert not source.spansString()
if source.leftmost : if source.leftmost:
mydirection = slipnet.right mydirection = slipnet.right
elif source.rightmost: elif source.rightmost:
mydirection = slipnet.left mydirection = slipnet.left
else: else:
activations = [ slipnet.left.activation ] activations = [slipnet.left.activation]
activations += [ slipnet.right.activation ] activations += [slipnet.right.activation]
if not selectListPosition(activations): if not selectListPosition(activations):
mydirection = slipnet.left mydirection = slipnet.left
else: else:
@ -464,7 +488,7 @@ def top_down_group_scout__direction(codelet):
category = firstBond.category category = firstBond.category
assert category assert category
groupCategory = category.getRelatedNode(slipnet.groupCategory) groupCategory = category.getRelatedNode(slipnet.groupCategory)
logging.info('trying from %s to %s' % (source,category.name) ) logging.info('trying from %s to %s' % (source, category.name))
bondFacet = None bondFacet = None
# find leftmost object in group with these bonds # find leftmost object in group with these bonds
search = True search = True
@ -491,23 +515,24 @@ def top_down_group_scout__direction(codelet):
destination = destination.rightBond.rightObject destination = destination.rightBond.rightObject
search = True search = True
assert destination != source assert destination != source
logging.info('proposing group from %s to %s' % (source,destination) ) logging.info('proposing group from %s to %s' % (source, destination))
objects = [ source ] objects = [source]
bonds = [] bonds = []
while source != destination: while source != destination:
bonds += [ source.rightBond ] bonds += [source.rightBond]
objects += [ source.rightBond.rightObject ] objects += [source.rightBond.rightObject]
source = source.rightBond.rightObject source = source.rightBond.rightObject
coderack.proposeGroup(objects,bonds,groupCategory,direction,bondFacet,codelet) coderack.proposeGroup(objects, bonds, groupCategory, direction, bondFacet, codelet)
#noinspection PyStringFormat #noinspection PyStringFormat
def group_scout__whole_string(codelet): def group_scout__whole_string(codelet):
string = workspace.initial string = workspace.initial
if utils.random() > 0.5: if utils.random() > 0.5:
string = workspace.target string = workspace.target
logging.info('target string selected: %s' % workspace.target ) logging.info('target string selected: %s' % workspace.target)
else: else:
logging.info('initial string selected: %s' % workspace.initial ) logging.info('initial string selected: %s' % workspace.initial)
# find leftmost object & the highest group to which it belongs # find leftmost object & the highest group to which it belongs
leftmost = None leftmost = None
for objekt in string.objects: for objekt in string.objects:
@ -518,14 +543,14 @@ def group_scout__whole_string(codelet):
if leftmost.spansString(): if leftmost.spansString():
# the object already spans the string - propose this object # the object already spans the string - propose this object
group = leftmost group = leftmost
coderack.proposeGroup(group.objectList, group.bondList,group.groupCategory,group.directionCategory, group.facet,codelet) coderack.proposeGroup(group.objectList, group.bondList, group.groupCategory, group.directionCategory, group.facet, codelet)
return return
bonds = [] bonds = []
objects = [ leftmost ] objects = [leftmost]
while leftmost.rightBond: while leftmost.rightBond:
bonds += [ leftmost.rightBond ] bonds += [leftmost.rightBond]
leftmost = leftmost.rightBond.rightObject leftmost = leftmost.rightBond.rightObject
objects += [ leftmost ] objects += [leftmost]
assert leftmost.rightmost assert leftmost.rightmost
# choose a random bond from list # choose a random bond from list
chosenBond = utils.choice(bonds) chosenBond = utils.choice(bonds)
@ -535,7 +560,8 @@ def group_scout__whole_string(codelet):
bonds = possibleGroupBonds(category, directionCategory, bondFacet, bonds) bonds = possibleGroupBonds(category, directionCategory, bondFacet, bonds)
assert bonds assert bonds
groupCategory = category.getRelatedNode(slipnet.groupCategory) groupCategory = category.getRelatedNode(slipnet.groupCategory)
coderack.proposeGroup(objects,bonds,groupCategory,directionCategory,bondFacet,codelet) coderack.proposeGroup(objects, bonds, groupCategory, directionCategory, bondFacet, codelet)
def group_strength_tester(codelet): def group_strength_tester(codelet):
# update strength value of the group # update strength value of the group
@ -543,13 +569,14 @@ def group_strength_tester(codelet):
__showWhichStringObjectIsFrom(group) __showWhichStringObjectIsFrom(group)
group.updateStrength() group.updateStrength()
strength = group.totalStrength strength = group.totalStrength
probability = temperatureAdjustedProbability(strength/100.0) probability = temperatureAdjustedProbability(strength / 100.0)
assert utils.random() <= probability assert utils.random() <= probability
# it is strong enough - post builder & activate nodes # it is strong enough - post builder & activate nodes
group.groupCategory.getRelatedNode(slipnet.bondCategory).buffer = 100.0 group.groupCategory.getRelatedNode(slipnet.bondCategory).buffer = 100.0
if group.directionCategory: if group.directionCategory:
group.directionCategory.buffer=100.0 group.directionCategory.buffer = 100.0
coderack.newCodelet('group-builder',codelet,strength) coderack.newCodelet('group-builder', codelet, strength)
def group_builder(codelet): def group_builder(codelet):
# update strength value of the group # update strength value of the group
@ -557,7 +584,7 @@ def group_builder(codelet):
#print '%s' % group #print '%s' % group
__showWhichStringObjectIsFrom(group) __showWhichStringObjectIsFrom(group)
equivalent = group.string.equivalentGroup(group) equivalent = group.string.equivalentGroup(group)
if equivalent : if equivalent:
logging.info('already exists...activate descriptors & fizzle') logging.info('already exists...activate descriptors & fizzle')
group.activateDescriptions() group.activateDescriptions()
equivalent.addDescriptions(group.descriptions) equivalent.addDescriptions(group.descriptions)
@ -575,7 +602,7 @@ def group_builder(codelet):
if leftBond: if leftBond:
lefty = leftBond.leftObject lefty = leftBond.leftObject
if lefty != previous or leftBond.directionCategory != group.directionCategory: if lefty != previous or leftBond.directionCategory != group.directionCategory:
incompatibleBonds += [ leftBond ] incompatibleBonds += [leftBond]
previous = objekt previous = objekt
next = group.objectList[-1] next = group.objectList[-1]
for objekt in reversed(group.objectList[:-1]): for objekt in reversed(group.objectList[:-1]):
@ -583,20 +610,20 @@ def group_builder(codelet):
if rightBond: if rightBond:
righty = rightBond.rightObject righty = rightBond.rightObject
if righty != next or rightBond.directionCategory != group.directionCategory: if righty != next or rightBond.directionCategory != group.directionCategory:
incompatibleBonds += [ rightBond ] incompatibleBonds += [rightBond]
next = objekt next = objekt
# if incompatible bonds exist - fight # if incompatible bonds exist - fight
group.updateStrength() group.updateStrength()
assert __fightIncompatibles(incompatibleBonds,group,'bonds',1.0,1.0) assert __fightIncompatibles(incompatibleBonds, group, 'bonds', 1.0, 1.0)
# fight incompatible groups # fight incompatible groups
# fight all groups containing these objects # fight all groups containing these objects
incompatibleGroups = group.getIncompatibleGroups() incompatibleGroups = group.getIncompatibleGroups()
assert __fightIncompatibles(incompatibleGroups,group,'Groups',1.0,1.0) assert __fightIncompatibles(incompatibleGroups, group, 'Groups', 1.0, 1.0)
for incompatible in incompatibleBonds: for incompatible in incompatibleBonds:
incompatible.break_the_structure() incompatible.break_the_structure()
# create new bonds # create new bonds
group.bondList = [] group.bondList = []
for i in range(1,len(group.objectList)): for i in range(1, len(group.objectList)):
#print 803 #print 803
object1 = group.objectList[i - 1] object1 = group.objectList[i - 1]
object2 = group.objectList[i] object2 = group.objectList[i]
@ -609,15 +636,16 @@ def group_builder(codelet):
destination = object1 destination = object1
category = group.groupCategory.getRelatedNode(slipnet.bondCategory) category = group.groupCategory.getRelatedNode(slipnet.bondCategory)
facet = group.facet facet = group.facet
newBond = Bond(source,destination,category,facet,source.getDescriptor(facet),destination.getDescriptor(facet)) newBond = Bond(source, destination, category, facet, source.getDescriptor(facet), destination.getDescriptor(facet))
newBond.buildBond() newBond.buildBond()
group.bondList += [ object1.rightBond ] group.bondList += [object1.rightBond]
for incompatible in incompatibleGroups: for incompatible in incompatibleGroups:
incompatible.break_the_structure() incompatible.break_the_structure()
group.buildGroup() group.buildGroup()
group.activateDescriptions() group.activateDescriptions()
logging.info('building group') logging.info('building group')
def rule_builder(codelet): def rule_builder(codelet):
rule = codelet.arguments[0] rule = codelet.arguments[0]
if rule.ruleEqual(workspace.rule): if rule.ruleEqual(workspace.rule):
@ -627,28 +655,30 @@ def rule_builder(codelet):
assert rule.totalStrength assert rule.totalStrength
# fight against other rules # fight against other rules
if workspace.rule: if workspace.rule:
assert __structureVsStructure(rule,1.0,workspace.rule,1.0) assert __structureVsStructure(rule, 1.0, workspace.rule, 1.0)
workspace.buildRule(rule) workspace.buildRule(rule)
def __getCutOff(density): def __getCutOff(density):
if density > 0.8: if density > 0.8:
distribution = [ 5.0,150.0,5.0,2.0,1.0,1.0,1.0,1.0,1.0,1.0 ] distribution = [5.0, 150.0, 5.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
elif density > 0.6: elif density > 0.6:
distribution = [ 2.0,5.0,150.0,5.0,2.0,1.0,1.0,1.0,1.0,1.0 ] distribution = [2.0, 5.0, 150.0, 5.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0]
elif density > 0.4: elif density > 0.4:
distribution = [ 1.0,2.0,5.0,150.0,5.0,2.0,1.0,1.0,1.0,1.0 ] distribution = [1.0, 2.0, 5.0, 150.0, 5.0, 2.0, 1.0, 1.0, 1.0, 1.0]
elif density > 0.2: elif density > 0.2:
distribution = [ 1.0,1.0,2.0,5.0,150.0,5.0,2.0,1.0,1.0,1.0 ] distribution = [1.0, 1.0, 2.0, 5.0, 150.0, 5.0, 2.0, 1.0, 1.0, 1.0]
else: else:
distribution = [ 1.0,1.0,1.0,2.0,5.0,150.0,5.0,2.0,1.0,1.0 ] distribution = [1.0, 1.0, 1.0, 2.0, 5.0, 150.0, 5.0, 2.0, 1.0, 1.0]
stop = sum(distribution) * utils.random() stop = sum(distribution) * utils.random()
total = 0.0 total = 0.0
for i in range(0,len(distribution)): for i in range(0, len(distribution)):
total += distribution[i] total += distribution[i]
if total >= stop: if total >= stop:
return i + 1 return i + 1
return len(distribution) return len(distribution)
def rule_translator(): def rule_translator():
assert workspace.rule assert workspace.rule
if len(workspace.initial) == 1 and len(workspace.target) == 1: if len(workspace.initial) == 1 and len(workspace.target) == 1:
@ -657,7 +687,7 @@ def rule_translator():
numberOfBonds = len(workspace.initial.bonds) + len(workspace.target.bonds) numberOfBonds = len(workspace.initial.bonds) + len(workspace.target.bonds)
nearlyTotalLength = len(workspace.initial) + len(workspace.target) - 2 nearlyTotalLength = len(workspace.initial) + len(workspace.target) - 2
bondDensity = numberOfBonds / nearlyTotalLength bondDensity = numberOfBonds / nearlyTotalLength
if bondDensity>1.0: if bondDensity > 1.0:
bondDensity = 1.0 bondDensity = 1.0
cutoff = __getCutOff(bondDensity) * 10.0 cutoff = __getCutOff(bondDensity) * 10.0
assert cutoff >= formulas.actualTemperature assert cutoff >= formulas.actualTemperature
@ -668,31 +698,33 @@ def rule_translator():
temperature.clamped = True temperature.clamped = True
formulas.Temperature = 100.0 formulas.Temperature = 100.0
def bottom_up_correspondence_scout(codelet): def bottom_up_correspondence_scout(codelet):
objectFromInitial = chooseUnmodifiedObject('interStringSalience',workspace.initial.objects) objectFromInitial = chooseUnmodifiedObject('interStringSalience', workspace.initial.objects)
objectFromTarget = chooseUnmodifiedObject('interStringSalience',workspace.target.objects) objectFromTarget = chooseUnmodifiedObject('interStringSalience', workspace.target.objects)
assert objectFromInitial.spansString() == objectFromTarget.spansString() assert objectFromInitial.spansString() == objectFromTarget.spansString()
# get the posible concept mappings # get the posible concept mappings
conceptMappings = getMappings( objectFromInitial, objectFromTarget, objectFromInitial.relevantDescriptions(), objectFromTarget.relevantDescriptions()) conceptMappings = getMappings(objectFromInitial, objectFromTarget, objectFromInitial.relevantDescriptions(), objectFromTarget.relevantDescriptions())
assert conceptMappings and __slippability(conceptMappings) assert conceptMappings and __slippability(conceptMappings)
#find out if any are distinguishing #find out if any are distinguishing
distinguishingMappings = [ m for m in conceptMappings if m.distinguishing() ] distinguishingMappings = [m for m in conceptMappings if m.distinguishing()]
assert distinguishingMappings assert distinguishingMappings
# if both objects span the strings, check to see if the # if both objects span the strings, check to see if the
# string description needs to be flipped # string description needs to be flipped
oppositeMappings = [ m for m in distinguishingMappings oppositeMappings = [m for m in distinguishingMappings
if m.initialDescriptionType == slipnet.stringPositionCategory and if m.initialDescriptionType == slipnet.stringPositionCategory and
m.initialDescriptionType != slipnet.bondFacet ] m.initialDescriptionType != slipnet.bondFacet]
initialDescriptionTypes = [ m.initialDescriptionType for m in oppositeMappings ] initialDescriptionTypes = [m.initialDescriptionType for m in oppositeMappings]
flipTargetObject = False flipTargetObject = False
if objectFromInitial.spansString() and objectFromTarget.spansString() and slipnet.directionCategory in initialDescriptionTypes and __allOppositeMappings(oppositeMappings) and slipnet.opposite.activation != 100.0: if objectFromInitial.spansString() and objectFromTarget.spansString() and slipnet.directionCategory in initialDescriptionTypes and __allOppositeMappings(oppositeMappings) and slipnet.opposite.activation != 100.0:
objectFromTarget = objectFromTarget.flippedVersion() objectFromTarget = objectFromTarget.flippedVersion()
conceptMappings = getMappings( objectFromInitial, objectFromTarget, objectFromInitial.relevantDescriptions(), objectFromTarget.relevantDescriptions()) conceptMappings = getMappings(objectFromInitial, objectFromTarget, objectFromInitial.relevantDescriptions(), objectFromTarget.relevantDescriptions())
flipTargetObject = True flipTargetObject = True
coderack.proposeCorrespondence(objectFromInitial,objectFromTarget,conceptMappings,flipTargetObject,codelet) coderack.proposeCorrespondence(objectFromInitial, objectFromTarget, conceptMappings, flipTargetObject, codelet)
def important_object_correspondence_scout(codelet): def important_object_correspondence_scout(codelet):
objectFromInitial = chooseUnmodifiedObject('relativeImportance',workspace.initial.objects) objectFromInitial = chooseUnmodifiedObject('relativeImportance', workspace.initial.objects)
descriptors = objectFromInitial.relevantDistinguishingDescriptors() descriptors = objectFromInitial.relevantDistinguishingDescriptors()
slipnode = chooseSlipnodeByConceptualDepth(descriptors) slipnode = chooseSlipnodeByConceptualDepth(descriptors)
assert slipnode assert slipnode
@ -704,26 +736,27 @@ def important_object_correspondence_scout(codelet):
for objekt in workspace.target.objects: for objekt in workspace.target.objects:
for description in objekt.relevantDescriptions(): for description in objekt.relevantDescriptions():
if description.descriptor == initialDescriptor: if description.descriptor == initialDescriptor:
targetCandidates += [ objekt ] targetCandidates += [objekt]
assert targetCandidates assert targetCandidates
objectFromTarget = chooseUnmodifiedObject('interStringSalience',targetCandidates) objectFromTarget = chooseUnmodifiedObject('interStringSalience', targetCandidates)
assert objectFromInitial.spansString() == objectFromTarget.spansString() assert objectFromInitial.spansString() == objectFromTarget.spansString()
# get the posible concept mappings # get the posible concept mappings
conceptMappings = getMappings( objectFromInitial, objectFromTarget, objectFromInitial.relevantDescriptions(), objectFromTarget.relevantDescriptions()) conceptMappings = getMappings(objectFromInitial, objectFromTarget, objectFromInitial.relevantDescriptions(), objectFromTarget.relevantDescriptions())
assert conceptMappings and __slippability(conceptMappings) assert conceptMappings and __slippability(conceptMappings)
#find out if any are distinguishing #find out if any are distinguishing
distinguishingMappings = [ m for m in conceptMappings if m.distinguishing() ] distinguishingMappings = [m for m in conceptMappings if m.distinguishing()]
assert distinguishingMappings assert distinguishingMappings
# if both objects span the strings, check to see if the # if both objects span the strings, check to see if the
# string description needs to be flipped # string description needs to be flipped
oppositeMappings = [ m for m in distinguishingMappings if m.initialDescriptionType == slipnet.stringPositionCategory and m.initialDescriptionType != slipnet.bondFacet ] oppositeMappings = [m for m in distinguishingMappings if m.initialDescriptionType == slipnet.stringPositionCategory and m.initialDescriptionType != slipnet.bondFacet]
initialDescriptionTypes = [ m.initialDescriptionType for m in oppositeMappings ] initialDescriptionTypes = [m.initialDescriptionType for m in oppositeMappings]
flipTargetObject = False flipTargetObject = False
if objectFromInitial.spansString() and objectFromTarget.spansString() and slipnet.directionCategory in initialDescriptionTypes and __allOppositeMappings(oppositeMappings) and slipnet.opposite.activation != 100.0: if objectFromInitial.spansString() and objectFromTarget.spansString() and slipnet.directionCategory in initialDescriptionTypes and __allOppositeMappings(oppositeMappings) and slipnet.opposite.activation != 100.0:
objectFromTarget = objectFromTarget.flippedVersion() objectFromTarget = objectFromTarget.flippedVersion()
conceptMappings = getMappings( objectFromInitial, objectFromTarget,objectFromInitial.relevantDescriptions(), objectFromTarget.relevantDescriptions()) conceptMappings = getMappings(objectFromInitial, objectFromTarget, objectFromInitial.relevantDescriptions(), objectFromTarget.relevantDescriptions())
flipTargetObject = True flipTargetObject = True
coderack.proposeCorrespondence(objectFromInitial,objectFromTarget,conceptMappings,flipTargetObject,codelet) coderack.proposeCorrespondence(objectFromInitial, objectFromTarget, conceptMappings, flipTargetObject, codelet)
def correspondence_strength_tester(codelet): def correspondence_strength_tester(codelet):
correspondence = codelet.arguments[0] correspondence = codelet.arguments[0]
@ -732,7 +765,7 @@ def correspondence_strength_tester(codelet):
assert objectFromInitial in workspace.objects and (objectFromTarget in workspace.objects or correspondence.flipTargetObject and not workspace.target.equivalentGroup(objectFromTarget.flipped_version())) assert objectFromInitial in workspace.objects and (objectFromTarget in workspace.objects or correspondence.flipTargetObject and not workspace.target.equivalentGroup(objectFromTarget.flipped_version()))
correspondence.updateStrength() correspondence.updateStrength()
strength = correspondence.totalStrength strength = correspondence.totalStrength
probability = temperatureAdjustedProbability(strength/100.0) probability = temperatureAdjustedProbability(strength / 100.0)
assert utils.random() <= probability assert utils.random() <= probability
# activate some concepts # activate some concepts
for mapping in correspondence.conceptMappings: for mapping in correspondence.conceptMappings:
@ -740,7 +773,8 @@ def correspondence_strength_tester(codelet):
mapping.initialDescriptor.buffer = 100.0 mapping.initialDescriptor.buffer = 100.0
mapping.targetDescriptionType.buffer = 100.0 mapping.targetDescriptionType.buffer = 100.0
mapping.targetDescriptor.buffer = 100.0 mapping.targetDescriptor.buffer = 100.0
coderack.newCodelet('correspondence-builder',codelet,strength,correspondence) coderack.newCodelet('correspondence-builder', codelet, strength, correspondence)
def correspondence_builder(codelet): def correspondence_builder(codelet):
correspondence = codelet.arguments[0] correspondence = codelet.arguments[0]
@ -763,7 +797,7 @@ def correspondence_builder(codelet):
if mapping.label: if mapping.label:
mapping.label.buffer = 100.0 mapping.label.buffer = 100.0
if not mapping.isContainedBy(existing.conceptMappings): if not mapping.isContainedBy(existing.conceptMappings):
existing.conceptMappings += [ mapping ] existing.conceptMappings += [mapping]
return return
incompatibleCorrespondences = correspondence.getIncompatibleCorrespondences() incompatibleCorrespondences = correspondence.getIncompatibleCorrespondences()
# fight against all correspondences # fight against all correspondences
@ -771,7 +805,7 @@ def correspondence_builder(codelet):
correspondenceSpans = correspondence.objectFromInitial.letterSpan() + correspondence.objectFromTarget.letterSpan() correspondenceSpans = correspondence.objectFromInitial.letterSpan() + correspondence.objectFromTarget.letterSpan()
for incompatible in incompatibleCorrespondences: for incompatible in incompatibleCorrespondences:
incompatibleSpans = incompatible.objectFromInitial.letterSpan() + incompatible.objectFromTarget.letterSpan() incompatibleSpans = incompatible.objectFromInitial.letterSpan() + incompatible.objectFromTarget.letterSpan()
assert __structureVsStructure(correspondence,correspondenceSpans,incompatible,incompatibleSpans) assert __structureVsStructure(correspondence, correspondenceSpans, incompatible, incompatibleSpans)
incompatibleBond = None incompatibleBond = None
incompatibleGroup = None incompatibleGroup = None
# if there is an incompatible bond then fight against it # if there is an incompatible bond then fight against it
@ -780,16 +814,16 @@ def correspondence_builder(codelet):
incompatibleBond = correspondence.getIncompatibleBond() incompatibleBond = correspondence.getIncompatibleBond()
if incompatibleBond: if incompatibleBond:
# bond found - fight against it # bond found - fight against it
assert __structureVsStructure(correspondence,3.0,incompatibleBond,2.0) assert __structureVsStructure(correspondence, 3.0, incompatibleBond, 2.0)
# won against incompatible bond # won against incompatible bond
incompatibleGroup = correspondence.objectFromTarget.group incompatibleGroup = correspondence.objectFromTarget.group
if incompatibleGroup: if incompatibleGroup:
assert __structureVsStructure(correspondence,1.0,incompatibleGroup,1.0) assert __structureVsStructure(correspondence, 1.0, incompatibleGroup, 1.0)
# if there is an incompatible rule, fight against it # if there is an incompatible rule, fight against it
incompatibleRule = None incompatibleRule = None
if workspace.rule and workspace.rule.incompatibleRuleCorrespondence(correspondence): if workspace.rule and workspace.rule.incompatibleRuleCorrespondence(correspondence):
incompatibleRule = workspace.rule incompatibleRule = workspace.rule
assert __structureVsStructure( correspondence,1.0,incompatibleRule,1.0) assert __structureVsStructure(correspondence, 1.0, incompatibleRule, 1.0)
for incompatible in incompatibleCorrespondences: for incompatible in incompatibleCorrespondences:
incompatible.break_the_structure() incompatible.break_the_structure()
# break incompatible group and bond if they exist # break incompatible group and bond if they exist

View File

@ -1,4 +1,7 @@
import re, inspect, math, logging import re
import inspect
import math
import logging
import utils import utils
import formulas import formulas
@ -12,6 +15,7 @@ MAX_NUMBER_OF_CODELETS = 100
codeletsUsed = {} codeletsUsed = {}
class CodeRack(object): class CodeRack(object):
def __init__(self): def __init__(self):
#logging.debug('coderack.__init__()') #logging.debug('coderack.__init__()')
@ -21,7 +25,7 @@ class CodeRack(object):
self.pressures = CoderackPressures() self.pressures = CoderackPressures()
self.pressures.initialisePressures() self.pressures.initialisePressures()
self.reset() self.reset()
self.initialCodeletNames = ( 'bottom-up-bond-scout', 'replacement-finder', 'bottom-up-correspondence-scout' ) self.initialCodeletNames = ('bottom-up-bond-scout', 'replacement-finder', 'bottom-up-correspondence-scout')
self.codeletMethodsDir = None self.codeletMethodsDir = None
self.runCodelets = {} self.runCodelets = {}
self.postings = {} self.postings = {}
@ -166,7 +170,7 @@ class CodeRack(object):
def proposeSingleLetterGroup(self, source, codelet): def proposeSingleLetterGroup(self, source, codelet):
self.proposeGroup([source], [], slipnet.samenessGroup, None, slipnet.letterCategory, codelet) self.proposeGroup([source], [], slipnet.samenessGroup, None, slipnet.letterCategory, codelet)
def proposeGroup(self, objects, bondList, groupCategory, directionCategory, bondFacet, oldCodelet ): def proposeGroup(self, objects, bondList, groupCategory, directionCategory, bondFacet, oldCodelet):
from group import Group from group import Group
bondCategory = groupCategory.getRelatedNode(slipnet.bondCategory) bondCategory = groupCategory.getRelatedNode(slipnet.bondCategory)
@ -177,7 +181,7 @@ class CodeRack(object):
urgency = bondCategory.bondDegreeOfAssociation() urgency = bondCategory.bondDegreeOfAssociation()
self.newCodelet('group-strength-tester', oldCodelet, urgency, group) self.newCodelet('group-strength-tester', oldCodelet, urgency, group)
def proposeBond(self, source, destination, bondCategory, bondFacet, sourceDescriptor, destinationDescriptor, oldCodelet ): def proposeBond(self, source, destination, bondCategory, bondFacet, sourceDescriptor, destinationDescriptor, oldCodelet):
from bond import Bond from bond import Bond
bondFacet.buffer = 100.0 bondFacet.buffer = 100.0
@ -255,7 +259,7 @@ class CodeRack(object):
for codeletName in knownCodeletNames: for codeletName in knownCodeletNames:
methodName = re.sub('[ -]', '_', codeletName) methodName = re.sub('[ -]', '_', codeletName)
if methodName not in self.codeletMethodsDir: if methodName not in self.codeletMethodsDir:
raise NotImplementedError, 'Cannot find %s in codeletMethods' % methodName raise NotImplementedError('Cannot find %s in codeletMethods' % methodName)
method = getattr(codeletMethods, methodName) method = getattr(codeletMethods, methodName)
self.methods[methodName] = method self.methods[methodName] = method
@ -270,7 +274,7 @@ class CodeRack(object):
if not self.codelets: if not self.codelets:
return None return None
temp = formulas.Temperature temp = formulas.Temperature
scale = ( 100.0 - temp + 10.0 ) / 15.0 scale = (100.0 - temp + 10.0) / 15.0
# threshold = sum( [ c.urgency ** scale for c in self.codelets ] ) * utils.random() # threshold = sum( [ c.urgency ** scale for c in self.codelets ] ) * utils.random()
urgsum = 0.0 urgsum = 0.0
for codelet in self.codelets: for codelet in self.codelets:
@ -321,9 +325,9 @@ class CodeRack(object):
#if not self.codeletMethodsDir: #if not self.codeletMethodsDir:
method = self.methods[methodName] method = self.methods[methodName]
if not method: if not method:
raise ValueError, 'Found %s in codeletMethods, but cannot get it' % methodName raise ValueError('Found %s in codeletMethods, but cannot get it' % methodName)
if not callable(method): if not callable(method):
raise RuntimeError, 'Cannot call %s()' % methodName raise RuntimeError('Cannot call %s()' % methodName)
args, varargs, varkw, defaults = inspect.getargspec(method) args, varargs, varkw, defaults = inspect.getargspec(method)
#global codeletsUsed #global codeletsUsed
#codeletsUsed[methodName] = codeletsUsed.get(methodName,0) + 1 #codeletsUsed[methodName] = codeletsUsed.get(methodName,0) + 1

View File

@ -2,6 +2,7 @@ import logging
from formulas import Temperature from formulas import Temperature
from slipnet import slipnet from slipnet import slipnet
class CoderackPressure(object): class CoderackPressure(object):
def __init__(self, name): def __init__(self, name):
self.name = name self.name = name
@ -11,6 +12,7 @@ class CoderackPressure(object):
self.values = [] self.values = []
self.codelets = [] self.codelets = []
class CoderackPressures(object): class CoderackPressures(object):
def __init__(self): def __init__(self):
#logging.debug('coderackPressures.__init__()') #logging.debug('coderackPressures.__init__()')
@ -41,7 +43,7 @@ class CoderackPressures(object):
def calculatePressures(self): def calculatePressures(self):
#logging.debug('coderackPressures.calculatePressures()') #logging.debug('coderackPressures.calculatePressures()')
scale = ( 100.0 - Temperature + 10.0 ) / 15.0 scale = (100.0 - Temperature + 10.0) / 15.0
values = [] values = []
for pressure in self.pressures: for pressure in self.pressures:
value = sum([c.urgency ** scale for c in pressure.codelets]) value = sum([c.urgency ** scale for c in pressure.codelets])
@ -117,7 +119,7 @@ class CoderackPressures(object):
if i >= 0: if i >= 0:
self.pressures[i].codelets += [codelet] self.pressures[i].codelets += [codelet]
if codelet.pressure: if codelet.pressure:
codelet.pressure.codelets += [codelet] # XXX why do this codelet.pressure.codelets += [codelet] # XXX why do this
if i >= 0: if i >= 0:
codelet.pressure = self.pressures[i] # when following with this ? codelet.pressure = self.pressures[i] # when following with this ?
logging.info('Add %s: %d' % (codelet.name, i)) logging.info('Add %s: %d' % (codelet.name, i))

View File

@ -1,6 +1,7 @@
import logging import logging
from slipnet import slipnet from slipnet import slipnet
class ConceptMapping(object): class ConceptMapping(object):
def __init__(self, initialDescriptionType, targetDescriptionType, initialDescriptor, targetDescriptor, initialObject, targetObject): def __init__(self, initialDescriptionType, targetDescriptionType, initialDescriptor, targetDescriptor, initialObject, targetObject):
logging.info('make a map: %s-%s' % (initialDescriptionType.get_name(), targetDescriptionType.get_name())) logging.info('make a map: %s-%s' % (initialDescriptionType.get_name(), targetDescriptionType.get_name()))
@ -23,7 +24,7 @@ class ConceptMapping(object):
if association == 100.0: if association == 100.0:
return 100.0 return 100.0
depth = self.__conceptualDepth() / 100.0 depth = self.__conceptualDepth() / 100.0
return association * ( 1 - depth * depth ) return association * (1 - depth * depth)
def __degreeOfAssociation(self): def __degreeOfAssociation(self):
#assumes the 2 descriptors are connected in the slipnet by at most 1 link #assumes the 2 descriptors are connected in the slipnet by at most 1 link
@ -39,10 +40,10 @@ class ConceptMapping(object):
if association == 100.0: if association == 100.0:
return 100.0 return 100.0
depth = self.__conceptualDepth() / 100.0 depth = self.__conceptualDepth() / 100.0
return association * ( 1 + depth * depth ) return association * (1 + depth * depth)
def __conceptualDepth(self): def __conceptualDepth(self):
return (self.initialDescriptor.conceptualDepth + self.targetDescriptor.conceptualDepth ) / 2.0 return (self.initialDescriptor.conceptualDepth + self.targetDescriptor.conceptualDepth) / 2.0
def distinguishing(self): def distinguishing(self):
if self.initialDescriptor == slipnet.whole and self.targetDescriptor == slipnet.whole: if self.initialDescriptor == slipnet.whole and self.targetDescriptor == slipnet.whole:

View File

@ -15,6 +15,7 @@ from temperature import temperature
from coderack import coderack from coderack import coderack
from coderackPressure import coderackPressures from coderackPressure import coderackPressures
def updateEverything(): def updateEverything():
workspace.updateEverything() workspace.updateEverything()
coderack.updateCodelets() coderack.updateCodelets()
@ -53,6 +54,7 @@ def runTrial():
for answer, count in answers.iteritems(): for answer, count in answers.iteritems():
print '%s:%d' % (answer, count) print '%s:%d' % (answer, count)
def run(initial, modified, target): def run(initial, modified, target):
workspace.setStrings(initial, modified, target) workspace.setStrings(initial, modified, target)
runTrial() runTrial()

View File

@ -2,8 +2,9 @@ from workspace import workspace
from workspaceStructure import WorkspaceStructure from workspaceStructure import WorkspaceStructure
from formulas import getMappings from formulas import getMappings
class Correspondence(WorkspaceStructure): class Correspondence(WorkspaceStructure):
def __init__(self,objectFromInitial,objectFromTarget,conceptMappings,flipTargetObject): def __init__(self, objectFromInitial, objectFromTarget, conceptMappings, flipTargetObject):
WorkspaceStructure.__init__(self) WorkspaceStructure.__init__(self)
self.objectFromInitial = objectFromInitial self.objectFromInitial = objectFromInitial
self.objectFromTarget = objectFromTarget self.objectFromTarget = objectFromTarget
@ -15,13 +16,13 @@ class Correspondence(WorkspaceStructure):
return '<%s>' % self.__str__() return '<%s>' % self.__str__()
def __str__(self): def __str__(self):
return 'Correspondence between %s and %s' % (self.objectFromInitial,self.objectFromTarget) return 'Correspondence between %s and %s' % (self.objectFromInitial, self.objectFromTarget)
def distinguishingConceptMappings(self): def distinguishingConceptMappings(self):
return [ m for m in self.conceptMappings if m.distinguishing() ] return [m for m in self.conceptMappings if m.distinguishing()]
def relevantDistinguishingConceptMappings(self): def relevantDistinguishingConceptMappings(self):
return [ m for m in self.conceptMappings if m.distinguishing() and m.relevant() ] return [m for m in self.conceptMappings if m.distinguishing() and m.relevant()]
def extract_target_bond(self): def extract_target_bond(self):
targetBond = False targetBond = False
@ -63,9 +64,9 @@ class Correspondence(WorkspaceStructure):
return None return None
def getIncompatibleCorrespondences(self): def getIncompatibleCorrespondences(self):
return [ o.correspondence for o in workspace.initial.objects if o and self.incompatible(o.correspondence) ] return [o.correspondence for o in workspace.initial.objects if o and self.incompatible(o.correspondence)]
def incompatible(self,other): def incompatible(self, other):
if not other: if not other:
return False return False
if self.objectFromInitial == other.objectFromInitial: if self.objectFromInitial == other.objectFromInitial:
@ -78,7 +79,7 @@ class Correspondence(WorkspaceStructure):
return True return True
return False return False
def supporting(self,other): def supporting(self, other):
if self == other: if self == other:
return False return False
if self.objectFromInitial == other.objectFromInitial: if self.objectFromInitial == other.objectFromInitial:
@ -95,12 +96,12 @@ class Correspondence(WorkspaceStructure):
def support(self): def support(self):
from letter import Letter from letter import Letter
if isinstance(self.objectFromInitial,Letter) and self.objectFromInitial.spansString(): if isinstance(self.objectFromInitial, Letter) and self.objectFromInitial.spansString():
return 100.0 return 100.0
if isinstance(self.objectFromTarget,Letter) and self.objectFromTarget.spansString(): if isinstance(self.objectFromTarget, Letter) and self.objectFromTarget.spansString():
return 100.0 return 100.0
total = sum([ c.totalStrength for c in workspace.correspondences() if self.supporting(c) ]) total = sum([c.totalStrength for c in workspace.correspondences() if self.supporting(c)])
total = min(total,100.0) total = min(total, 100.0)
return total return total
def updateInternalStrength(self): def updateInternalStrength(self):
@ -110,7 +111,7 @@ class Correspondence(WorkspaceStructure):
if numberOfConceptMappings < 1: if numberOfConceptMappings < 1:
self.internalStrength = 0.0 self.internalStrength = 0.0
return return
totalStrength = sum([ m.strength() for m in relevantDistinguishingMappings ]) totalStrength = sum([m.strength() for m in relevantDistinguishingMappings])
averageStrength = totalStrength / numberOfConceptMappings averageStrength = totalStrength / numberOfConceptMappings
if numberOfConceptMappings == 1.0: if numberOfConceptMappings == 1.0:
numberOfConceptMappingsFactor = 0.8 numberOfConceptMappingsFactor = 0.8
@ -123,7 +124,7 @@ class Correspondence(WorkspaceStructure):
else: else:
internalCoherenceFactor = 1.0 internalCoherenceFactor = 1.0
internalStrength = averageStrength * internalCoherenceFactor * numberOfConceptMappingsFactor internalStrength = averageStrength * internalCoherenceFactor * numberOfConceptMappingsFactor
self.internalStrength = min(internalStrength,100.0) self.internalStrength = min(internalStrength, 100.0)
def updateExternalStrength(self): def updateExternalStrength(self):
self.externalStrength = self.support() self.externalStrength = self.support()
@ -131,16 +132,16 @@ class Correspondence(WorkspaceStructure):
def internallyCoherent(self): def internallyCoherent(self):
"""Whether any pair of relevant distinguishing mappings support each other""" """Whether any pair of relevant distinguishing mappings support each other"""
mappings = self.relevantDistinguishingConceptMappings() mappings = self.relevantDistinguishingConceptMappings()
for i in range(0,len(mappings)): for i in range(0, len(mappings)):
for j in range(0,len(mappings)): for j in range(0, len(mappings)):
if i != j: if i != j:
if mappings[i].supports(mappings[j]): if mappings[i].supports(mappings[j]):
return True return True
return False return False
def slippages(self): def slippages(self):
mappings = [ m for m in self.conceptMappings if m.slippage() ] mappings = [m for m in self.conceptMappings if m.slippage()]
mappings += [ m for m in self.accessoryConceptMappings if m.slippage() ] mappings += [m for m in self.accessoryConceptMappings if m.slippage()]
return mappings return mappings
def reflexive(self): def reflexive(self):
@ -151,7 +152,7 @@ class Correspondence(WorkspaceStructure):
return False return False
def buildCorrespondence(self): def buildCorrespondence(self):
workspace.structures += [ self ] workspace.structures += [self]
if self.objectFromInitial.correspondence: if self.objectFromInitial.correspondence:
self.objectFromInitial.correspondence.breakCorrespondence() self.objectFromInitial.correspondence.breakCorrespondence()
if self.objectFromTarget.correspondence: if self.objectFromTarget.correspondence:
@ -162,9 +163,9 @@ class Correspondence(WorkspaceStructure):
relevantMappings = self.relevantDistinguishingConceptMappings() relevantMappings = self.relevantDistinguishingConceptMappings()
for mapping in relevantMappings: for mapping in relevantMappings:
if mapping.slippage(): if mapping.slippage():
self.accessoryConceptMappings += [ mapping.symmetricVersion() ] self.accessoryConceptMappings += [mapping.symmetricVersion()]
from group import Group from group import Group
if isinstance(self.objectFromInitial,Group) and isinstance(self.objectFromTarget,Group): if isinstance(self.objectFromInitial, Group) and isinstance(self.objectFromTarget, Group):
bondMappings = getMappings( bondMappings = getMappings(
self.objectFromInitial, self.objectFromInitial,
self.objectFromTarget, self.objectFromTarget,
@ -172,9 +173,9 @@ class Correspondence(WorkspaceStructure):
self.objectFromTarget.bondDescriptions self.objectFromTarget.bondDescriptions
) )
for mapping in bondMappings: for mapping in bondMappings:
self.accessoryConceptMappings += [ mapping ] self.accessoryConceptMappings += [mapping]
if mapping.slippage(): if mapping.slippage():
self.accessoryConceptMappings += [ mapping.symmetricVersion() ] self.accessoryConceptMappings += [mapping.symmetricVersion()]
for mapping in self.conceptMappings: for mapping in self.conceptMappings:
if mapping.label: if mapping.label:
mapping.label.activation = 100.0 mapping.label.activation = 100.0
@ -186,4 +187,3 @@ class Correspondence(WorkspaceStructure):
workspace.structures.remove(self) workspace.structures.remove(self)
self.objectFromInitial.correspondence = None self.objectFromInitial.correspondence = None
self.objectFromTarget.correspondence = None self.objectFromTarget.correspondence = None

View File

@ -1,8 +1,9 @@
import logging import logging
from workspaceStructure import WorkspaceStructure from workspaceStructure import WorkspaceStructure
class Description(WorkspaceStructure): class Description(WorkspaceStructure):
def __init__(self,workspaceObject,descriptionType,descriptor): def __init__(self, workspaceObject, descriptionType, descriptor):
WorkspaceStructure.__init__(self) WorkspaceStructure.__init__(self)
self.object = workspaceObject self.object = workspaceObject
self.string = workspaceObject.string self.string = workspaceObject.string
@ -13,7 +14,7 @@ class Description(WorkspaceStructure):
return '<Description: %s>' % self.__str__() return '<Description: %s>' % self.__str__()
def __str__(self): def __str__(self):
s = 'description(%s) of %s' % (self.descriptor.get_name(),self.object) s = 'description(%s) of %s' % (self.descriptor.get_name(), self.object)
from workspace import workspace from workspace import workspace
if self.object.string == workspace.initial: if self.object.string == workspace.initial:
s += ' in initial string' s += ' in initial string'
@ -29,13 +30,13 @@ class Description(WorkspaceStructure):
def localSupport(self): def localSupport(self):
from workspace import workspace from workspace import workspace
supporters = 0 # number of objects in the string with a descriptionType like self supporters = 0 # number of objects in the string with a descriptionType like self
for other in workspace.otherObjects(self.object): for other in workspace.otherObjects(self.object):
if not ( self.object.isWithin(other) or other.isWithin(self.object) ): if not (self.object.isWithin(other) or other.isWithin(self.object)):
for description in other.descriptions: for description in other.descriptions:
if description.descriptionType == self.descriptionType: if description.descriptionType == self.descriptionType:
supporters += 1 supporters += 1
results = { 0:0.0, 1:20.0, 2:60.0, 3:90.0 } results = {0: 0.0, 1: 20.0, 2: 60.0, 3: 90.0}
if supporters in results: if supporters in results:
return results[supporters] return results[supporters]
return 100.0 return 100.0
@ -45,12 +46,10 @@ class Description(WorkspaceStructure):
self.descriptor.buffer = 100.0 self.descriptor.buffer = 100.0
if not self.object.hasDescription(self.descriptor): if not self.object.hasDescription(self.descriptor):
logging.info('Add %s to descriptions' % self) logging.info('Add %s to descriptions' % self)
self.object.descriptions += [ self ] self.object.descriptions += [self]
def breakDescription(self): def breakDescription(self):
from workspace import workspace from workspace import workspace
if self in workspace.structures: if self in workspace.structures:
workspace.structures.remove(self) workspace.structures.remove(self)
self.object.descriptions.remove(self) self.object.descriptions.remove(self)

View File

@ -1,4 +1,4 @@
import math #, random import math # , random
import logging import logging
import utils import utils
@ -7,6 +7,7 @@ from temperature import temperature
actualTemperature = Temperature = 100.0 actualTemperature = Temperature = 100.0
def selectListPosition(probabilities): def selectListPosition(probabilities):
total = sum(probabilities) total = sum(probabilities)
#logging.info('total: %s' % total) #logging.info('total: %s' % total)
@ -22,20 +23,23 @@ def selectListPosition(probabilities):
index += 1 index += 1
return 0 return 0
def weightedAverage(values): def weightedAverage(values):
total = 0.0 total = 0.0
totalWeights = 0.0 totalWeights = 0.0
for value,weight in values: for value, weight in values:
total += value * weight total += value * weight
totalWeights += weight totalWeights += weight
if not totalWeights: if not totalWeights:
return 0.0 return 0.0
return total / totalWeights return total / totalWeights
def temperatureAdjustedValue(value): def temperatureAdjustedValue(value):
#logging.info('Temperature: %s' % Temperature) #logging.info('Temperature: %s' % Temperature)
#logging.info('actualTemperature: %s' % actualTemperature) #logging.info('actualTemperature: %s' % actualTemperature)
return value ** (((100.0-Temperature)/30.0)+0.5) return value ** (((100.0 - Temperature) / 30.0) + 0.5)
def temperatureAdjustedProbability(value): def temperatureAdjustedProbability(value):
if not value or value == 0.5 or not temperature.value: if not value or value == 0.5 or not temperature.value:
@ -46,64 +50,73 @@ def temperatureAdjustedProbability(value):
a = math.sqrt(coldness) a = math.sqrt(coldness)
b = 10.0 - a b = 10.0 - a
c = b / 100 c = b / 100
d = c * ( 1.0 - ( 1.0 - value ) ) # aka c * value, but we're following the java d = c * (1.0 - (1.0 - value)) # aka c * value, but we're following the java
e = ( 1.0 - value ) + d e = (1.0 - value) + d
f = 1.0 - e f = 1.0 - e
return max(f,0.5) return max(f, 0.5)
def coinFlip(chance=0.5): def coinFlip(chance=0.5):
return utils.random() < chance return utils.random() < chance
def blur(value): def blur(value):
root = math.sqrt(value) root = math.sqrt(value)
if coinFlip(): if coinFlip():
return value + root return value + root
return value - root return value - root
def chooseObjectFromList(objects,attribute):
def chooseObjectFromList(objects, attribute):
if not objects: if not objects:
return None return None
probabilities = [] probabilities = []
for object in objects: for object in objects:
value = getattr(object,attribute) value = getattr(object, attribute)
probability = temperatureAdjustedValue(value) probability = temperatureAdjustedValue(value)
logging.info('Object: %s, value: %d, probability: %d' % (object,value,probability)) logging.info('Object: %s, value: %d, probability: %d' % (object, value, probability))
probabilities += [ probability ] probabilities += [probability]
index = selectListPosition(probabilities) index = selectListPosition(probabilities)
logging.info("Selected: %d" % index) logging.info("Selected: %d" % index)
return objects[index] return objects[index]
def chooseRelevantDescriptionByActivation(workspaceObject): def chooseRelevantDescriptionByActivation(workspaceObject):
descriptions = workspaceObject.relevantDescriptions() descriptions = workspaceObject.relevantDescriptions()
if not descriptions: if not descriptions:
return None return None
activations = [ description.descriptor.activation for description in descriptions ] activations = [description.descriptor.activation for description in descriptions]
index = selectListPosition(activations) index = selectListPosition(activations)
return descriptions[ index ] return descriptions[index]
def similarPropertyLinks(slip_node): def similarPropertyLinks(slip_node):
result = [] result = []
for slip_link in slip_node.propertyLinks: for slip_link in slip_node.propertyLinks:
association = slip_link.degreeOfAssociation() / 100.0 association = slip_link.degreeOfAssociation() / 100.0
probability = temperatureAdjustedProbability( association ) probability = temperatureAdjustedProbability(association)
if coinFlip(probability): if coinFlip(probability):
result += [ slip_link ] result += [slip_link]
return result return result
def chooseSlipnodeByConceptualDepth(slip_nodes): def chooseSlipnodeByConceptualDepth(slip_nodes):
if not slip_nodes: if not slip_nodes:
return None return None
depths = [ temperatureAdjustedValue(n.conceptualDepth) for n in slip_nodes ] depths = [temperatureAdjustedValue(n.conceptualDepth) for n in slip_nodes]
i = selectListPosition(depths) i = selectListPosition(depths)
return slip_nodes[ i ] return slip_nodes[i]
def __relevantCategory(objekt,slipnode):
def __relevantCategory(objekt, slipnode):
return objekt.rightBond and objekt.rightBond.category == slipnode return objekt.rightBond and objekt.rightBond.category == slipnode
def __relevantDirection(objekt,slipnode):
def __relevantDirection(objekt, slipnode):
return objekt.rightBond and objekt.rightBond.directionCategory == slipnode return objekt.rightBond and objekt.rightBond.directionCategory == slipnode
def __localRelevance(string,slipnode,relevance):
def __localRelevance(string, slipnode, relevance):
numberOfObjectsNotSpanning = numberOfMatches = 0.0 numberOfObjectsNotSpanning = numberOfMatches = 0.0
#logging.info("find relevance for a string: %s" % string); #logging.info("find relevance for a string: %s" % string);
for objekt in string.objects: for objekt in string.objects:
@ -111,22 +124,25 @@ def __localRelevance(string,slipnode,relevance):
if not objekt.spansString(): if not objekt.spansString():
#logging.info('non spanner: %s' % objekt) #logging.info('non spanner: %s' % objekt)
numberOfObjectsNotSpanning += 1.0 numberOfObjectsNotSpanning += 1.0
if relevance(objekt,slipnode): if relevance(objekt, slipnode):
numberOfMatches += 1.0 numberOfMatches += 1.0
#logging.info("matches: %d, not spanning: %d" % (numberOfMatches,numberOfObjectsNotSpanning)) #logging.info("matches: %d, not spanning: %d" % (numberOfMatches,numberOfObjectsNotSpanning))
if numberOfObjectsNotSpanning == 1: if numberOfObjectsNotSpanning == 1:
return 100.0 * numberOfMatches return 100.0 * numberOfMatches
return 100.0 * numberOfMatches / (numberOfObjectsNotSpanning - 1.0) return 100.0 * numberOfMatches / (numberOfObjectsNotSpanning - 1.0)
def localBondCategoryRelevance(string, category): def localBondCategoryRelevance(string, category):
if len(string.objects) == 1: if len(string.objects) == 1:
return 0.0 return 0.0
return __localRelevance(string,category,__relevantCategory) return __localRelevance(string, category, __relevantCategory)
def localDirectionCategoryRelevance(string, direction): def localDirectionCategoryRelevance(string, direction):
return __localRelevance(string,direction,__relevantDirection) return __localRelevance(string, direction, __relevantDirection)
def getMappings(objectFromInitial,objectFromTarget, initialDescriptions, targetDescriptions):
def getMappings(objectFromInitial, objectFromTarget, initialDescriptions, targetDescriptions):
mappings = [] mappings = []
from conceptMapping import ConceptMapping from conceptMapping import ConceptMapping
for initialDescription in initialDescriptions: for initialDescription in initialDescriptions:
@ -141,6 +157,5 @@ def getMappings(objectFromInitial,objectFromTarget, initialDescriptions, targetD
objectFromInitial, objectFromInitial,
objectFromTarget objectFromTarget
) )
mappings += [ mapping ] mappings += [mapping]
return mappings return mappings

View File

@ -1,13 +1,15 @@
import utils, logging import utils
import logging
from workspace import workspace from workspace import workspace
from workspaceObject import WorkspaceObject from workspaceObject import WorkspaceObject
from slipnet import slipnet from slipnet import slipnet
import formulas import formulas
class Group(WorkspaceObject): class Group(WorkspaceObject):
def __init__(self,string,groupCategory,directionCategory,facet,objectList,bondList): def __init__(self, string, groupCategory, directionCategory, facet, objectList, bondList):
WorkspaceObject.__init__(self,string) WorkspaceObject.__init__(self, string)
self.groupCategory = groupCategory self.groupCategory = groupCategory
self.directionCategory = directionCategory self.directionCategory = directionCategory
self.facet = facet self.facet = facet
@ -36,7 +38,6 @@ class Group(WorkspaceObject):
self.clampSalience = False self.clampSalience = False
self.name = '' self.name = ''
from description import Description from description import Description
if self.bondList and len(self.bondList): if self.bondList and len(self.bondList):
firstFacet = self.bondList[0].facet firstFacet = self.bondList[0].facet
@ -71,18 +72,18 @@ class Group(WorkspaceObject):
s = self.string.__str__() s = self.string.__str__()
l = self.leftStringPosition - 1 l = self.leftStringPosition - 1
r = self.rightStringPosition r = self.rightStringPosition
return 'group[%d:%d] == %s' % ( l, r - 1, s[l: r ]) return 'group[%d:%d] == %s' % (l, r - 1, s[l:r])
def getIncompatibleGroups(self): def getIncompatibleGroups(self):
result = [] result = []
for objekt in self.objectList: for objekt in self.objectList:
while objekt.group: while objekt.group:
result += [ objekt.group ] result += [objekt.group]
objekt = objekt.group objekt = objekt.group
return result return result
def addBondDescription(self,description): def addBondDescription(self, description):
self.bondDescriptions += [ description ] self.bondDescriptions += [description]
def singleLetterGroupProbability(self): def singleLetterGroupProbability(self):
numberOfSupporters = self.numberOfLocalSupportingGroups() numberOfSupporters = self.numberOfLocalSupportingGroups()
@ -100,15 +101,15 @@ class Group(WorkspaceObject):
return formulas.temperatureAdjustedProbability(supportedActivation) return formulas.temperatureAdjustedProbability(supportedActivation)
def flippedVersion(self): def flippedVersion(self):
flippedBonds = [ b.flippedversion() for b in self.bondList ] flippedBonds = [b.flippedversion() for b in self.bondList]
flippedGroup = self.groupCategory.getRelatedNode(slipnet.flipped) flippedGroup = self.groupCategory.getRelatedNode(slipnet.flipped)
flippedDirection = self.directionCategory.getRelatedNode(slipnet.flipped) flippedDirection = self.directionCategory.getRelatedNode(slipnet.flipped)
return Group(self.string, flippedGroup, flippedDirection, self.facet, self.objectList, flippedBonds) return Group(self.string, flippedGroup, flippedDirection, self.facet, self.objectList, flippedBonds)
def buildGroup(self): def buildGroup(self):
workspace.objects += [ self ] workspace.objects += [self]
workspace.structures += [ self ] workspace.structures += [self]
self.string.objects += [ self ] self.string.objects += [self]
for objekt in self.objectList: for objekt in self.objectList:
objekt.group = self objekt.group = self
workspace.buildDescriptions(self) workspace.buildDescriptions(self)
@ -128,7 +129,7 @@ class Group(WorkspaceObject):
probability = 0.5 ** fred probability = 0.5 ** fred
value = formulas.temperatureAdjustedProbability(probability) value = formulas.temperatureAdjustedProbability(probability)
if value < 0.06: if value < 0.06:
value = 0.0 # otherwise 1/20 chance always value = 0.0 # otherwise 1/20 chance always
return value return value
def break_the_structure(self): def break_the_structure(self):
@ -168,7 +169,7 @@ class Group(WorkspaceObject):
else: else:
lengthFactor = 90.0 lengthFactor = 90.0
lengthWeight = 100.0 - bondWeight lengthWeight = 100.0 - bondWeight
weightList = ( (relatedBondAssociation, bondWeight), (lengthFactor, lengthWeight) ) weightList = ((relatedBondAssociation, bondWeight), (lengthFactor, lengthWeight))
self.internalStrength = formulas.weightedAverage(weightList) self.internalStrength = formulas.weightedAverage(weightList)
def updateExternalStrength(self): def updateExternalStrength(self):
@ -181,14 +182,14 @@ class Group(WorkspaceObject):
numberOfSupporters = self.numberOfLocalSupportingGroups() numberOfSupporters = self.numberOfLocalSupportingGroups()
if numberOfSupporters == 0.0: if numberOfSupporters == 0.0:
return 0.0 return 0.0
supportFactor = min(1.0,0.6 ** (1 / (numberOfSupporters ** 3 ))) supportFactor = min(1.0, 0.6 ** (1 / (numberOfSupporters ** 3)))
densityFactor = 100.0 * ((self.localDensity() / 100.0) ** 0.5) densityFactor = 100.0 * ((self.localDensity() / 100.0) ** 0.5)
return densityFactor * supportFactor return densityFactor * supportFactor
def numberOfLocalSupportingGroups(self): def numberOfLocalSupportingGroups(self):
count = 0 count = 0
for objekt in self.string.objects: for objekt in self.string.objects:
if isinstance(objekt,Group): if isinstance(objekt, Group):
if objekt.rightStringPosition < self.leftStringPosition or objekt.leftStringPosition > self.rightStringPosition: if objekt.rightStringPosition < self.leftStringPosition or objekt.leftStringPosition > self.rightStringPosition:
if objekt.groupCategory == self.groupCategory and objekt.directionCategory == self.directionCategory: if objekt.groupCategory == self.groupCategory and objekt.directionCategory == self.directionCategory:
count += 1 count += 1
@ -199,7 +200,7 @@ class Group(WorkspaceObject):
halfLength = len(self.string) / 2.0 halfLength = len(self.string) / 2.0
return 100.0 * numberOfSupporters / halfLength return 100.0 * numberOfSupporters / halfLength
def sameGroup(self,other): def sameGroup(self, other):
if self.leftStringPosition != other.leftStringPosition: if self.leftStringPosition != other.leftStringPosition:
return False return False
if self.rightStringPosition != other.rightStringPosition: if self.rightStringPosition != other.rightStringPosition:
@ -212,26 +213,24 @@ class Group(WorkspaceObject):
return False return False
return True return True
def morePossibleDescriptions(self,node): def morePossibleDescriptions(self, node):
result = [] result = []
i = 1 i = 1
for number in slipnet.numbers: for number in slipnet.numbers:
if node == number and len(self.objects) == i: if node == number and len(self.objects) == i:
result += [ node ] result += [node]
i += 1 i += 1
return result return result
def distinguishingDescriptor(self,descriptor): def distinguishingDescriptor(self, descriptor):
"""Whether no other object of the same type (group) has the same descriptor""" """Whether no other object of the same type (group) has the same descriptor"""
if not WorkspaceObject.distinguishingDescriptor(self,descriptor): if not WorkspaceObject.distinguishingDescriptor(self, descriptor):
return False return False
for objekt in self.string.objects: for objekt in self.string.objects:
# check to see if they are of the same type # check to see if they are of the same type
if isinstance(objekt,Group) and objekt != self: if isinstance(objekt, Group) and objekt != self:
# check all descriptions for the descriptor # check all descriptions for the descriptor
for description in objekt.descriptions: for description in objekt.descriptions:
if description.descriptor == descriptor: if description.descriptor == descriptor:
return False return False
return True return True

View File

@ -1,5 +1,6 @@
from workspace import workspace from workspace import workspace
class GroupRun(object): class GroupRun(object):
def __init__(self): def __init__(self):
self.name = 'xxx' self.name = 'xxx'

View File

@ -1,26 +1,27 @@
from workspaceObject import WorkspaceObject from workspaceObject import WorkspaceObject
from slipnet import slipnet from slipnet import slipnet
class Letter(WorkspaceObject): class Letter(WorkspaceObject):
def __init__(self,string,position,length): def __init__(self, string, position, length):
WorkspaceObject.__init__(self,string) WorkspaceObject.__init__(self, string)
from workspace import workspace from workspace import workspace
workspace.objects += [ self ] workspace.objects += [self]
string.objects += [self ] string.objects += [self]
self.leftStringPosition = position self.leftStringPosition = position
self.leftmost = self.leftStringPosition == 1 self.leftmost = self.leftStringPosition == 1
self.rightStringPosition = position self.rightStringPosition = position
self.rightmost = self.rightStringPosition == length self.rightmost = self.rightStringPosition == length
def describe(self,position,length): def describe(self, position, length):
if length == 1: if length == 1:
self.addDescription(slipnet.stringPositionCategory,slipnet.single) self.addDescription(slipnet.stringPositionCategory, slipnet.single)
if self.leftmost and length > 1: # ? why check length ? if self.leftmost and length > 1: # ? why check length ?
self.addDescription(slipnet.stringPositionCategory,slipnet.leftmost) self.addDescription(slipnet.stringPositionCategory, slipnet.leftmost)
if self.rightmost and length > 1: # ? why check length ? if self.rightmost and length > 1: # ? why check length ?
self.addDescription(slipnet.stringPositionCategory,slipnet.rightmost) self.addDescription(slipnet.stringPositionCategory, slipnet.rightmost)
if length > 2 and position * 2 == length + 1: if length > 2 and position * 2 == length + 1:
self.addDescription(slipnet.stringPositionCategory,slipnet.middle) self.addDescription(slipnet.stringPositionCategory, slipnet.middle)
def __repr__(self): def __repr__(self):
return '<Letter: %s>' % self.__str__() return '<Letter: %s>' % self.__str__()
@ -30,19 +31,18 @@ class Letter(WorkspaceObject):
return '' return ''
i = self.leftStringPosition - 1 i = self.leftStringPosition - 1
if len(self.string) <= i: if len(self.string) <= i:
raise ValueError, 'len(self.string) <= self.leftStringPosition :: %d <= %d' % (len(self.string),self.leftStringPosition) raise ValueError('len(self.string) <= self.leftStringPosition :: %d <= %d' % (len(self.string), self.leftStringPosition))
return self.string[ i ] return self.string[i]
def distinguishingDescriptor(self,descriptor): def distinguishingDescriptor(self, descriptor):
"""Whether no other object of the same type (letter) has the same descriptor""" """Whether no other object of the same type (letter) has the same descriptor"""
if not WorkspaceObject.distinguishingDescriptor(self,descriptor): if not WorkspaceObject.distinguishingDescriptor(self, descriptor):
return False return False
for objekt in self.string.objects: for objekt in self.string.objects:
# check to see if they are of the same type # check to see if they are of the same type
if isinstance(objekt,Letter) and objekt != self: if isinstance(objekt, Letter) and objekt != self:
# check all descriptions for the descriptor # check all descriptions for the descriptor
for description in objekt.descriptions: for description in objekt.descriptions:
if description.descriptor == descriptor: if description.descriptor == descriptor:
return False return False
return True return True

View File

@ -1,9 +1,9 @@
from workspaceStructure import WorkspaceStructure from workspaceStructure import WorkspaceStructure
class Replacement(WorkspaceStructure): class Replacement(WorkspaceStructure):
def __init__(self, objectFromInitial, objectFromModified, relation): def __init__(self, objectFromInitial, objectFromModified, relation):
WorkspaceStructure.__init__(self) WorkspaceStructure.__init__(self)
self.objectFromInitial = objectFromInitial self.objectFromInitial = objectFromInitial
self.objectFromModified = objectFromModified self.objectFromModified = objectFromModified
self.relation = relation self.relation = relation

View File

@ -3,8 +3,9 @@ from workspace import workspace
from workspaceStructure import WorkspaceStructure from workspaceStructure import WorkspaceStructure
from formulas import * from formulas import *
class Rule(WorkspaceStructure): class Rule(WorkspaceStructure):
def __init__(self,facet,descriptor,category,relation): def __init__(self, facet, descriptor, category, relation):
WorkspaceStructure.__init__(self) WorkspaceStructure.__init__(self)
self.facet = facet self.facet = facet
self.descriptor = descriptor self.descriptor = descriptor
@ -20,15 +21,15 @@ class Rule(WorkspaceStructure):
self.externalStrength = self.internalStrength self.externalStrength = self.internalStrength
def updateInternalStrength(self): def updateInternalStrength(self):
if not ( self.descriptor and self.relation ): if not (self.descriptor and self.relation):
self.internalStrength = 0.0 self.internalStrength = 0.0
return return
averageDepth = ( self.descriptor.conceptualDepth + self.relation.conceptualDepth ) / 2.0 averageDepth = (self.descriptor.conceptualDepth + self.relation.conceptualDepth) / 2.0
averageDepth **= 1.1 averageDepth **= 1.1
# see if the object corresponds to an object # see if the object corresponds to an object
# if so, see if the descriptor is present (modulo slippages) in the # if so, see if the descriptor is present (modulo slippages) in the
# corresponding object # corresponding object
changedObjects = [ o for o in workspace.initial.objects if o.changed ] changedObjects = [o for o in workspace.initial.objects if o.changed]
changed = changedObjects[0] changed = changedObjects[0]
sharedDescriptorTerm = 0.0 sharedDescriptorTerm = 0.0
if changed and changed.correspondence: if changed and changed.correspondence:
@ -36,17 +37,17 @@ class Rule(WorkspaceStructure):
slippages = workspace.slippages() slippages = workspace.slippages()
slipnode = self.descriptor.applySlippages(slippages) slipnode = self.descriptor.applySlippages(slippages)
if not targetObject.hasDescription(slipnode): if not targetObject.hasDescription(slipnode):
self.internalStrength = 0.0 self.internalStrength = 0.0
return return
sharedDescriptorTerm = 100.0 sharedDescriptorTerm = 100.0
sharedDescriptorWeight = ((100.0 - self.descriptor.conceptualDepth) / 10.0) ** 1.4 sharedDescriptorWeight = ((100.0 - self.descriptor.conceptualDepth) / 10.0) ** 1.4
depthDifference = 100.0 - abs(self.descriptor.conceptualDepth - self.relation.conceptualDepth) depthDifference = 100.0 - abs(self.descriptor.conceptualDepth - self.relation.conceptualDepth)
weights = ( (depthDifference,12), (averageDepth,18), (sharedDescriptorTerm,sharedDescriptorWeight) ) weights = ((depthDifference, 12), (averageDepth, 18), (sharedDescriptorTerm, sharedDescriptorWeight))
self.internalStrength = weightedAverage( weights ) self.internalStrength = weightedAverage(weights)
if self.internalStrength > 100.0: if self.internalStrength > 100.0:
self.internalStrength = 100.0 self.internalStrength = 100.0
def ruleEqual(self,other): def ruleEqual(self, other):
if not other: if not other:
return False return False
if self.relation != other.relation: if self.relation != other.relation:
@ -73,18 +74,18 @@ class Rule(WorkspaceStructure):
if not correspondence: if not correspondence:
return False return False
# find changed object # find changed object
changeds = [ o for o in workspace.initial.objects if o.changed ] changeds = [o for o in workspace.initial.objects if o.changed]
if not changeds: if not changeds:
return False return False
changed = changeds[0] changed = changeds[0]
if correspondence.objectFromInitial != changed: if correspondence.objectFromInitial != changed:
return False return False
# it is incompatible if the rule descriptor is not in the mapping list # it is incompatible if the rule descriptor is not in the mapping list
if len([ m for m in correspondence.conceptMappings if m.initialDescriptor == self.descriptor ]): if len([m for m in correspondence.conceptMappings if m.initialDescriptor == self.descriptor]):
return False return False
return True return True
def __changeString(self,string): def __changeString(self, string):
# applies the changes to self string ie. successor # applies the changes to self string ie. successor
if self.facet == slipnet.length: if self.facet == slipnet.length:
if self.relation == slipnet.predecessor: if self.relation == slipnet.predecessor:
@ -96,11 +97,11 @@ class Rule(WorkspaceStructure):
if self.relation == slipnet.predecessor: if self.relation == slipnet.predecessor:
if 'a' in string: if 'a' in string:
return None return None
return ''.join([ chr(ord(c) - 1) for c in string]) return ''.join([chr(ord(c) - 1) for c in string])
elif self.relation == slipnet.successor: elif self.relation == slipnet.successor:
if 'z' in string: if 'z' in string:
return None return None
return ''.join([ chr(ord(c) + 1) for c in string]) return ''.join([chr(ord(c) + 1) for c in string])
else: else:
return self.relation.name.lower() return self.relation.name.lower()
@ -112,9 +113,9 @@ class Rule(WorkspaceStructure):
self.relation = self.relation.applySlippages(slippages) self.relation = self.relation.applySlippages(slippages)
# generate the final string # generate the final string
self.finalAnswer = workspace.targetString self.finalAnswer = workspace.targetString
changeds = [ o for o in workspace.target.objects if changeds = [o for o in workspace.target.objects if
o.hasDescription(self.descriptor) and o.hasDescription(self.descriptor) and
o.hasDescription(self.category) ] o.hasDescription(self.category)]
changed = changeds and changeds[0] or None changed = changeds and changeds[0] or None
logging.debug('changed object = %s' % changed) logging.debug('changed object = %s' % changed)
if changed: if changed:
@ -131,4 +132,3 @@ class Rule(WorkspaceStructure):
endString = self.finalAnswer[right:] endString = self.finalAnswer[right:]
self.finalAnswer = startString + middleString + endString self.finalAnswer = startString + middleString + endString
return True return True

View File

@ -1,5 +1,6 @@
#from slipnode import Slipnode #from slipnode import Slipnode
class Sliplink(object): class Sliplink(object):
def __init__(self, source, destination, label=None, length=0.0): def __init__(self, source, destination, label=None, length=0.0):
self.source = source self.source = source
@ -25,4 +26,4 @@ class Sliplink(object):
self.destination.buffer += self.intrinsicDegreeOfAssociation() self.destination.buffer += self.intrinsicDegreeOfAssociation()
def points_at(self, other): def points_at(self, other):
return self.destination == other return self.destination == other

View File

@ -3,6 +3,7 @@ import logging
from slipnode import Slipnode from slipnode import Slipnode
from sliplink import Sliplink from sliplink import Sliplink
class SlipNet(object): class SlipNet(object):
def __init__(self): def __init__(self):
logging.debug("SlipNet.__init__()") logging.debug("SlipNet.__init__()")
@ -242,7 +243,7 @@ class SlipNet(object):
self.slipnodes += [slipnode] self.slipnodes += [slipnode]
return slipnode return slipnode
def __link_items_to_their_neighbours(self,items): def __link_items_to_their_neighbours(self, items):
previous = items[0] previous = items[0]
for item in items[1:]: for item in items[1:]:
self.__addNonSlipLink(previous, item, label=self.successor) self.__addNonSlipLink(previous, item, label=self.successor)

View File

@ -2,12 +2,15 @@ import math
import utils import utils
import logging import logging
def full_activation(): def full_activation():
return 100 return 100
def jump_threshold(): def jump_threshold():
return 55.0 return 55.0
class Slipnode(object): class Slipnode(object):
def __init__(self, name, depth, length=0.0): def __init__(self, name, depth, length=0.0):
# logging.info('depth to %s for %s' % (depth,name)) # logging.info('depth to %s for %s' % (depth,name))
@ -57,7 +60,7 @@ class Slipnode(object):
def fully_active(self): def fully_active(self):
"""Whether this node has full activation""" """Whether this node has full activation"""
return self.activation > full_activation() - 0.00001 # allow a little leeway for floats return self.activation > full_activation() - 0.00001 # allow a little leeway for floats
def activate_fully(self): def activate_fully(self):
"""Make this node fully active""" """Make this node fully active"""
@ -79,7 +82,7 @@ class Slipnode(object):
def update(self): def update(self):
act = self.activation act = self.activation
self.oldActivation = act self.oldActivation = act
self.buffer -= self.activation * ( 100.0 - self.conceptual_depth) / 100.0 self.buffer -= self.activation * (100.0 - self.conceptual_depth) / 100.0
def linked(self, other): def linked(self, other):
"""Whether the other is among the outgoing links""" """Whether the other is among the outgoing links"""
@ -141,7 +144,7 @@ class Slipnode(object):
def spread_activation(self): def spread_activation(self):
if self.fully_active(): if self.fully_active():
[ link.spread_activation() for link in self.outgoingLinks ] [link.spread_activation() for link in self.outgoingLinks]
def addBuffer(self): def addBuffer(self):
if not self.clamped: if not self.clamped:

View File

@ -1,5 +1,6 @@
import logging import logging
class Temperature(object): class Temperature(object):
def __init__(self): def __init__(self):
self.value = 100.0 self.value = 100.0

View File

@ -1,4 +1,3 @@
def any(things): def any(things):
"""Return True if any of the things are True. """Return True if any of the things are True.
@ -57,6 +56,7 @@ def any(things):
return True return True
return False return False
def all(things): def all(things):
"""Return True if all of the things are True. """Return True if all of the things are True.
@ -114,6 +114,8 @@ import logging
seed = 999.0 seed = 999.0
count = 0 count = 0
testably_random = True testably_random = True
def random(): def random():
global testably_random global testably_random
if testably_random: if testably_random:
@ -130,6 +132,7 @@ def random():
# sys.exit(1) # sys.exit(1)
return seed / 2000.0 return seed / 2000.0
def choice(aList): def choice(aList):
i = int(random() * len(aList)) i = int(random() * len(aList))
return aList[i] return aList[i]
@ -137,4 +140,3 @@ def choice(aList):
if __name__ == '__main__': if __name__ == '__main__':
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -4,6 +4,7 @@ from workspaceString import WorkspaceString
unknownAnswer = '?' unknownAnswer = '?'
class Workspace(object): class Workspace(object):
def __init__(self): def __init__(self):
#logging.debug('workspace.__init__()') #logging.debug('workspace.__init__()')
@ -155,4 +156,3 @@ class Workspace(object):
workspace = Workspace() workspace = Workspace()

View File

@ -5,6 +5,7 @@ from temperature import temperature
from slipnet import slipnet from slipnet import slipnet
import formulas import formulas
class WorkspaceFormulas(object): class WorkspaceFormulas(object):
def __init__(self): def __init__(self):
self.clampTemperature = False self.clampTemperature = False
@ -16,7 +17,7 @@ class WorkspaceFormulas(object):
if workspace.rule: if workspace.rule:
workspace.rule.updateStrength() workspace.rule.updateStrength()
ruleWeakness = 100.0 - workspace.rule.totalStrength ruleWeakness = 100.0 - workspace.rule.totalStrength
values = ( (workspace.totalUnhappiness, 0.8), (ruleWeakness, 0.2), ) values = ((workspace.totalUnhappiness, 0.8), (ruleWeakness, 0.2))
slightly_above_actual_temperature = formulas.actualTemperature + 0.001 slightly_above_actual_temperature = formulas.actualTemperature + 0.001
logging.info('actualTemperature: %f' % slightly_above_actual_temperature) logging.info('actualTemperature: %f' % slightly_above_actual_temperature)
formulas.actualTemperature = formulas.weightedAverage(values) formulas.actualTemperature = formulas.weightedAverage(values)
@ -32,14 +33,17 @@ class WorkspaceFormulas(object):
workspaceFormulas = WorkspaceFormulas() workspaceFormulas = WorkspaceFormulas()
def numberOfObjects(): def numberOfObjects():
return len(workspace.objects) return len(workspace.objects)
def chooseUnmodifiedObject(attribute,inObjects):
objects = [ o for o in inObjects if o.string != workspace.modified ] def chooseUnmodifiedObject(attribute, inObjects):
objects = [o for o in inObjects if o.string != workspace.modified]
if not len(objects): if not len(objects):
print 'no objects available in initial or target strings' print 'no objects available in initial or target strings'
return formulas.chooseObjectFromList(objects,attribute) return formulas.chooseObjectFromList(objects, attribute)
def chooseNeighbour(source): def chooseNeighbour(source):
objects = [] objects = []
@ -47,50 +51,56 @@ def chooseNeighbour(source):
if objekt.string != source.string: if objekt.string != source.string:
continue continue
if objekt.leftStringPosition == source.rightStringPosition + 1: if objekt.leftStringPosition == source.rightStringPosition + 1:
objects += [ objekt ] objects += [objekt]
elif source.leftStringPosition == objekt.rightStringPosition + 1: elif source.leftStringPosition == objekt.rightStringPosition + 1:
objects += [ objekt ] objects += [objekt]
return formulas.chooseObjectFromList(objects,"intraStringSalience") return formulas.chooseObjectFromList(objects, "intraStringSalience")
def chooseDirectedNeighbor(source,direction):
def chooseDirectedNeighbor(source, direction):
if direction == slipnet.left: if direction == slipnet.left:
logging.info('Left') logging.info('Left')
return __chooseLeftNeighbor(source) return __chooseLeftNeighbor(source)
logging.info('Right') logging.info('Right')
return __chooseRightNeighbor(source) return __chooseRightNeighbor(source)
def __chooseLeftNeighbor(source): def __chooseLeftNeighbor(source):
objects = [] objects = []
for o in workspace.objects: for o in workspace.objects:
if o.string == source.string : if o.string == source.string:
if source.leftStringPosition == o.rightStringPosition + 1: if source.leftStringPosition == o.rightStringPosition + 1:
logging.info('%s is on left of %s' % (o,source)) logging.info('%s is on left of %s' % (o, source))
objects += [ o ] objects += [o]
else: else:
logging.info('%s is not on left of %s' % (o,source)) logging.info('%s is not on left of %s' % (o, source))
logging.info('Number of left objects: %s' % len(objects)) logging.info('Number of left objects: %s' % len(objects))
return formulas.chooseObjectFromList(objects,'intraStringSalience') return formulas.chooseObjectFromList(objects, 'intraStringSalience')
def __chooseRightNeighbor(source): def __chooseRightNeighbor(source):
objects = [ o for o in workspace.objects if objects = [o for o in workspace.objects if
o.string == source.string and o.string == source.string and
o.leftStringPosition == source.rightStringPosition + 1 o.leftStringPosition == source.rightStringPosition + 1
] ]
return formulas.chooseObjectFromList(objects,'intraStringSalience') return formulas.chooseObjectFromList(objects, 'intraStringSalience')
def chooseBondFacet(source, destination): def chooseBondFacet(source, destination):
sourceFacets = [ d.descriptionType for d in source.descriptions if d.descriptionType in slipnet.bondFacets ] sourceFacets = [d.descriptionType for d in source.descriptions if d.descriptionType in slipnet.bondFacets]
bondFacets = [ d.descriptionType for d in destination.descriptions if d.descriptionType in sourceFacets ] bondFacets = [d.descriptionType for d in destination.descriptions if d.descriptionType in sourceFacets]
if not bondFacets: if not bondFacets:
return None return None
supports = [ __supportForDescriptionType(f,source.string) for f in bondFacets ] supports = [__supportForDescriptionType(f, source.string) for f in bondFacets]
i = formulas.selectListPosition(supports) i = formulas.selectListPosition(supports)
return bondFacets[ i ] return bondFacets[i]
def __supportForDescriptionType(descriptionType,string):
return ( descriptionType.activation + __descriptionTypeSupport(descriptionType,string) ) / 2
def __descriptionTypeSupport(descriptionType,string): def __supportForDescriptionType(descriptionType, string):
return (descriptionType.activation + __descriptionTypeSupport(descriptionType, string)) / 2
def __descriptionTypeSupport(descriptionType, string):
"""The proportion of objects in the string that have a description with this descriptionType""" """The proportion of objects in the string that have a description with this descriptionType"""
numberOfObjects = totalNumberOfObjects = 0.0 numberOfObjects = totalNumberOfObjects = 0.0
for objekt in workspace.objects: for objekt in workspace.objects:
@ -101,11 +111,12 @@ def __descriptionTypeSupport(descriptionType,string):
numberOfObjects += 1.0 numberOfObjects += 1.0
return numberOfObjects / totalNumberOfObjects return numberOfObjects / totalNumberOfObjects
def probabilityOfPosting(codeletName): def probabilityOfPosting(codeletName):
if codeletName == 'breaker': if codeletName == 'breaker':
return 1.0 return 1.0
if 'description' in codeletName: if 'description' in codeletName:
result = ( formulas.Temperature / 100.0 ) ** 2 result = (formulas.Temperature / 100.0) ** 2
else: else:
result = workspace.intraStringUnhappiness / 100.0 result = workspace.intraStringUnhappiness / 100.0
if 'correspondence' in codeletName: if 'correspondence' in codeletName:
@ -126,6 +137,7 @@ def probabilityOfPosting(codeletName):
return 1.0 return 1.0
return result return result
def howManyToPost(codeletName): def howManyToPost(codeletName):
if codeletName == 'breaker': if codeletName == 'breaker':
return 1 return 1
@ -156,5 +168,3 @@ def howManyToPost(codeletName):
if number < formulas.blur(4.0): if number < formulas.blur(4.0):
return 2 return 2
return 3 return 3

View File

@ -4,8 +4,9 @@ from description import Description
from slipnet import slipnet from slipnet import slipnet
from workspaceStructure import WorkspaceStructure from workspaceStructure import WorkspaceStructure
class WorkspaceObject(WorkspaceStructure): class WorkspaceObject(WorkspaceStructure):
def __init__(self,workspaceString): def __init__(self, workspaceString):
WorkspaceStructure.__init__(self) WorkspaceStructure.__init__(self)
self.string = workspaceString self.string = workspaceString
#self.string.objects += [ self ] #self.string.objects += [ self ]
@ -42,21 +43,21 @@ class WorkspaceObject(WorkspaceStructure):
def spansString(self): def spansString(self):
return self.leftmost and self.rightmost return self.leftmost and self.rightmost
def addDescription(self,descriptionType,descriptor): def addDescription(self, descriptionType, descriptor):
description = Description(self,descriptionType,descriptor) description = Description(self, descriptionType, descriptor)
logging.info("Adding description: %s to %s" % (description,self)) logging.info("Adding description: %s to %s" % (description, self))
self.descriptions += [ description ] self.descriptions += [description]
def addDescriptions(self,descriptions): def addDescriptions(self, descriptions):
#print 'addDescriptions 1' #print 'addDescriptions 1'
#print 'add %d to %d of %s' % (len(descriptions),len(self.descriptions), self.string.string) #print 'add %d to %d of %s' % (len(descriptions),len(self.descriptions), self.string.string)
copy = descriptions[:] # in case we add to our own descriptions, which turns the loop infinite copy = descriptions[:] # in case we add to our own descriptions, which turns the loop infinite
for description in copy: for description in copy:
#print '%d addDescriptions 2 %s ' % (len(descriptions),description) #print '%d addDescriptions 2 %s ' % (len(descriptions),description)
logging.info('might add: %s' % description) logging.info('might add: %s' % description)
if not self.containsDescription(description): if not self.containsDescription(description):
#print '%d addDescriptions 3 %s ' % (len(descriptions),description) #print '%d addDescriptions 3 %s ' % (len(descriptions),description)
self.addDescription(description.descriptionType,description.descriptor) self.addDescription(description.descriptionType, description.descriptor)
#print '%d addDescriptions 4 %s ' % (len(descriptions),description) #print '%d addDescriptions 4 %s ' % (len(descriptions),description)
else: else:
logging.info("Won't add it") logging.info("Won't add it")
@ -73,7 +74,7 @@ class WorkspaceObject(WorkspaceStructure):
for bond in self.bonds: for bond in self.bonds:
bondStrength += bond.totalStrength bondStrength += bond.totalStrength
divisor = 6.0 divisor = 6.0
if self.spansString(): # XXX then we have already returned if self.spansString(): # XXX then we have already returned
divisor = 3.0 divisor = 3.0
return bondStrength / divisor return bondStrength / divisor
@ -104,7 +105,7 @@ class WorkspaceObject(WorkspaceStructure):
self.interStringUnhappiness = 100.0 - interStringHappiness self.interStringUnhappiness = 100.0 - interStringHappiness
#logging.info("Unhappy: %s"%self.interStringUnhappiness) #logging.info("Unhappy: %s"%self.interStringUnhappiness)
averageHappiness = ( intraStringHappiness + interStringHappiness ) / 2 averageHappiness = (intraStringHappiness + interStringHappiness) / 2
self.totalUnhappiness = 100.0 - averageHappiness self.totalUnhappiness = 100.0 - averageHappiness
if self.clampSalience: if self.clampSalience:
@ -112,45 +113,45 @@ class WorkspaceObject(WorkspaceStructure):
self.interStringSalience = 100.0 self.interStringSalience = 100.0
else: else:
from formulas import weightedAverage from formulas import weightedAverage
self.intraStringSalience = weightedAverage( ((self.relativeImportance,0.2), (self.intraStringUnhappiness,0.8)) ) self.intraStringSalience = weightedAverage(((self.relativeImportance, 0.2), (self.intraStringUnhappiness, 0.8)))
self.interStringSalience = weightedAverage( ((self.relativeImportance,0.8), (self.interStringUnhappiness,0.2)) ) self.interStringSalience = weightedAverage(((self.relativeImportance, 0.8), (self.interStringUnhappiness, 0.2)))
self.totalSalience = (self.intraStringSalience + self.interStringSalience) / 2.0 self.totalSalience = (self.intraStringSalience + self.interStringSalience) / 2.0
logging.info('Set salience of %s to %f = (%f + %f)/2' % ( logging.info('Set salience of %s to %f = (%f + %f)/2' % (
self.__str__(),self.totalSalience, self.intraStringSalience, self.interStringSalience)) self.__str__(), self.totalSalience, self.intraStringSalience, self.interStringSalience))
def isWithin(self,other): def isWithin(self, other):
return self.leftStringPosition >= other.leftStringPosition and self.rightStringPosition <= other.rightStringPosition return self.leftStringPosition >= other.leftStringPosition and self.rightStringPosition <= other.rightStringPosition
def relevantDescriptions(self): def relevantDescriptions(self):
return [ d for d in self.descriptions if d.descriptionType.fully_active() ] return [d for d in self.descriptions if d.descriptionType.fully_active()]
def morePossibleDescriptions(self,node): def morePossibleDescriptions(self, node):
return [] return []
def getPossibleDescriptions(self,descriptionType): def getPossibleDescriptions(self, descriptionType):
logging.info('getting possible descriptions for %s' % self) logging.info('getting possible descriptions for %s' % self)
descriptions = [ ] descriptions = []
from group import Group from group import Group
for link in descriptionType.instanceLinks: for link in descriptionType.instanceLinks:
node = link.destination node = link.destination
if node == slipnet.first and self.hasDescription(slipnet.letters[0]): if node == slipnet.first and self.hasDescription(slipnet.letters[0]):
descriptions += [ node ] descriptions += [node]
if node == slipnet.last and self.hasDescription(slipnet.letters[-1]): if node == slipnet.last and self.hasDescription(slipnet.letters[-1]):
descriptions += [ node ] descriptions += [node]
i = 1 i = 1
for number in slipnet.numbers: for number in slipnet.numbers:
if node == number and isinstance(self,Group) and len(self.objectList) == i: if node == number and isinstance(self, Group) and len(self.objectList) == i:
descriptions += [ node ] descriptions += [node]
i += 1 i += 1
if node == slipnet.middle and self.middleObject(): if node == slipnet.middle and self.middleObject():
descriptions += [ node ] descriptions += [node]
s = '' s = ''
for d in descriptions: for d in descriptions:
s = '%s, %s' % (s,d.get_name()) s = '%s, %s' % (s, d.get_name())
logging.info(s) logging.info(s)
return descriptions return descriptions
def containsDescription(self,sought): def containsDescription(self, sought):
soughtType = sought.descriptionType soughtType = sought.descriptionType
soughtDescriptor = sought.descriptor soughtDescriptor = sought.descriptor
for d in self.descriptions: for d in self.descriptions:
@ -158,8 +159,8 @@ class WorkspaceObject(WorkspaceStructure):
return True return True
return False return False
def hasDescription(self,slipnode): def hasDescription(self, slipnode):
return [ d for d in self.descriptions if d.descriptor == slipnode ] and True or False return [d for d in self.descriptions if d.descriptor == slipnode] and True or False
def middleObject(self): def middleObject(self):
# XXX only works if string is 3 chars long # XXX only works if string is 3 chars long
@ -172,7 +173,7 @@ class WorkspaceObject(WorkspaceStructure):
objectOnMyRightIsRightmost = True objectOnMyRightIsRightmost = True
return objectOnMyRightIsRightmost and objectOnMyLeftIsLeftmost return objectOnMyRightIsRightmost and objectOnMyLeftIsLeftmost
def distinguishingDescriptor(self,descriptor): def distinguishingDescriptor(self, descriptor):
"""Whether no other object of the same type (ie. letter or group) has the same descriptor""" """Whether no other object of the same type (ie. letter or group) has the same descriptor"""
if descriptor == slipnet.letter: if descriptor == slipnet.letter:
return False return False
@ -184,19 +185,19 @@ class WorkspaceObject(WorkspaceStructure):
return True return True
def relevantDistinguishingDescriptors(self): def relevantDistinguishingDescriptors(self):
return [ d.descriptor for d in self.relevantDescriptions() if self.distinguishingDescriptor(d.descriptor) ] return [d.descriptor for d in self.relevantDescriptions() if self.distinguishingDescriptor(d.descriptor)]
def getDescriptor(self,descriptionType): def getDescriptor(self, descriptionType):
"""The description attached to this object of the specified description type.""" """The description attached to this object of the specified description type."""
descriptor = None descriptor = None
logging.info("\nIn %s, trying for type: %s" % (self,descriptionType.get_name())) logging.info("\nIn %s, trying for type: %s" % (self, descriptionType.get_name()))
for description in self.descriptions: for description in self.descriptions:
logging.info("Trying description: %s" % description) logging.info("Trying description: %s" % description)
if description.descriptionType == descriptionType: if description.descriptionType == descriptionType:
return description.descriptor return description.descriptor
return descriptor return descriptor
def getDescriptionType(self,sought_description): def getDescriptionType(self, sought_description):
"""The description_type attached to this object of the specified description""" """The description_type attached to this object of the specified description"""
for description in self.descriptions: for description in self.descriptions:
if description.descriptor == sought_description: if description.descriptor == sought_description:
@ -204,10 +205,10 @@ class WorkspaceObject(WorkspaceStructure):
description = None description = None
return description return description
def getCommonGroups(self,other): def getCommonGroups(self, other):
return [ o for o in self.string.objects if self.isWithin(o) and other.isWithin(o) ] return [o for o in self.string.objects if self.isWithin(o) and other.isWithin(o)]
def letterDistance(self,other): def letterDistance(self, other):
if other.leftStringPosition > self.rightStringPosition: if other.leftStringPosition > self.rightStringPosition:
return other.leftStringPosition - self.rightStringPosition return other.leftStringPosition - self.rightStringPosition
if self.leftStringPosition > other.rightStringPosition: if self.leftStringPosition > other.rightStringPosition:
@ -217,10 +218,9 @@ class WorkspaceObject(WorkspaceStructure):
def letterSpan(self): def letterSpan(self):
return self.rightStringPosition - self.leftStringPosition + 1 return self.rightStringPosition - self.leftStringPosition + 1
def beside(self,other): def beside(self, other):
if self.string != other.string: if self.string != other.string:
return False return False
if self.leftStringPosition == other.rightStringPosition + 1: if self.leftStringPosition == other.rightStringPosition + 1:
return True return True
return other.leftStringPosition == self.rightStringPosition + 1 return other.leftStringPosition == self.rightStringPosition + 1

View File

@ -2,6 +2,7 @@ import logging
from letter import Letter from letter import Letter
from slipnet import slipnet from slipnet import slipnet
class WorkspaceString(object): class WorkspaceString(object):
def __init__(self, s): def __init__(self, s):
self.string = s self.string = s
@ -60,7 +61,7 @@ class WorkspaceString(object):
else: else:
for o in self.objects: for o in self.objects:
logging.info('object: %s, relative: %d = raw: %d / total: %d' % ( logging.info('object: %s, relative: %d = raw: %d / total: %d' % (
o, o.relativeImportance * 1000, o.rawImportance, total )) o, o.relativeImportance * 1000, o.rawImportance, total))
o.relativeImportance = o.rawImportance / total o.relativeImportance = o.rawImportance / total
def updateIntraStringUnhappiness(self): def updateIntraStringUnhappiness(self):

View File

@ -1,5 +1,6 @@
import formulas import formulas
class WorkspaceStructure(object): class WorkspaceStructure(object):
def __init__(self): def __init__(self):
self.string = None self.string = None
@ -14,7 +15,7 @@ class WorkspaceStructure(object):
def updateTotalStrength(self): def updateTotalStrength(self):
"""Recalculate the total strength based on internal and external strengths""" """Recalculate the total strength based on internal and external strengths"""
weights = ( (self.internalStrength, self.internalStrength), (self.externalStrength, 100 - self.internalStrength) ) weights = ((self.internalStrength, self.internalStrength), (self.externalStrength, 100 - self.internalStrength))
strength = formulas.weightedAverage(weights) strength = formulas.weightedAverage(weights)
self.totalStrength = strength self.totalStrength = strength
@ -24,14 +25,14 @@ class WorkspaceStructure(object):
def updateInternalStrength(self): def updateInternalStrength(self):
"""How internally cohesive the structure is""" """How internally cohesive the structure is"""
raise NotImplementedError, 'call of abstract method: WorkspaceStructure.updateInternalStrength()' raise NotImplementedError('call of abstract method: WorkspaceStructure.updateInternalStrength()')
def updateExternalStrength(self): def updateExternalStrength(self):
raise NotImplementedError, 'call of abstract method: WorkspaceStructure.updateExternalStrength()' raise NotImplementedError('call of abstract method: WorkspaceStructure.updateExternalStrength()')
def break_the_structure(self): def break_the_structure(self):
"""Break this workspace structure """Break this workspace structure
Exactly what is broken depends on sub-class Exactly what is broken depends on sub-class
""" """
raise NotImplementedError, 'call of abstract method: WorkspaceStructure.break_the_structure()' raise NotImplementedError('call of abstract method: WorkspaceStructure.break_the_structure()')