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,6 +2,7 @@ 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)
@ -164,6 +165,7 @@ 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:

View File

@ -10,6 +10,7 @@ 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:
@ -21,6 +22,7 @@ def __showWhichStringObjectIsFrom(structure):
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): def __getScoutSource(slipnode, relevanceMethod, typeName):
initialRelevance = relevanceMethod(workspace.initial, slipnode) initialRelevance = relevanceMethod(workspace.initial, slipnode)
targetRelevance = relevanceMethod(workspace.target, slipnode) targetRelevance = relevanceMethod(workspace.target, slipnode)
@ -37,20 +39,24 @@ def __getScoutSource(slipnode,relevanceMethod,typeName):
source = chooseUnmodifiedObject('intraStringSalience', string.objects) source = chooseUnmodifiedObject('intraStringSalience', string.objects)
return source return source
def __getBondFacet(source, destination): def __getBondFacet(source, destination):
bondFacet = chooseBondFacet(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): def __allOppositeMappings(mappings):
return len([m for m in mappings if m.label != slipnet.opposite]) == 0 return len([m for m in mappings if m.label != slipnet.opposite]) == 0
def __structureVsStructure(structure1, weight1, structure2, weight2): def __structureVsStructure(structure1, weight1, structure2, weight2):
structure1.updateStrength() structure1.updateStrength()
structure2.updateStrength() structure2.updateStrength()
@ -60,6 +66,7 @@ def __structureVsStructure(structure1,weight1,structure2,weight2):
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,6 +77,7 @@ 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):
@ -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,6 +97,7 @@ 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
@ -112,6 +122,7 @@ def breaker():
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
@ -126,6 +137,7 @@ def bottom_up_description_scout(codelet):
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)
@ -138,6 +150,7 @@ def top_down_description_scout(codelet):
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
@ -147,6 +160,7 @@ def description_strength_tester(codelet):
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]
assert description.object in workspace.objects assert description.object in workspace.objects
@ -156,6 +170,7 @@ 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)
@ -175,6 +190,7 @@ def bottom_up_bond_scout(codelet):
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]
@ -230,6 +246,7 @@ def rule_scout(codelet):
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()
@ -237,6 +254,7 @@ def rule_strength_tester(codelet):
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)]
@ -266,6 +284,7 @@ def replacement_finder():
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]
@ -287,6 +306,7 @@ def top_down_bond_scout__category(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')
@ -301,6 +321,7 @@ def top_down_bond_scout__direction(codelet):
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)
@ -315,6 +336,7 @@ def bond_strength_tester(codelet):
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]
__showWhichStringObjectIsFrom(bond) __showWhichStringObjectIsFrom(bond)
@ -352,6 +374,7 @@ 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)
@ -422,6 +445,7 @@ def top_down_group_scout__category(codelet):
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')
@ -500,6 +524,7 @@ def top_down_group_scout__direction(codelet):
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
@ -537,6 +562,7 @@ def group_scout__whole_string(codelet):
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
group = codelet.arguments[0] group = codelet.arguments[0]
@ -551,6 +577,7 @@ def group_strength_tester(codelet):
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
group = codelet.arguments[0] group = codelet.arguments[0]
@ -618,6 +645,7 @@ def group_builder(codelet):
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):
@ -630,6 +658,7 @@ def rule_builder(codelet):
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]
@ -649,6 +678,7 @@ def __getCutOff(density):
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:
@ -668,6 +698,7 @@ 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)
@ -691,6 +722,7 @@ def bottom_up_correspondence_scout(codelet):
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()
@ -725,6 +757,7 @@ def important_object_correspondence_scout(codelet):
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]
objectFromInitial = correspondence.objectFromInitial objectFromInitial = correspondence.objectFromInitial
@ -742,6 +775,7 @@ def correspondence_strength_tester(codelet):
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]
objectFromInitial = correspondence.objectFromInitial objectFromInitial = correspondence.objectFromInitial

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__()')
@ -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
@ -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__()')

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()))

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,6 +2,7 @@ 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)
@ -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,6 +1,7 @@
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)
@ -52,5 +53,3 @@ class Description(WorkspaceStructure):
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

@ -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,6 +23,7 @@ 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
@ -32,11 +34,13 @@ def weightedAverage(values):
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:
return value return value
@ -51,15 +55,18 @@ def temperatureAdjustedProbability(value):
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
@ -73,6 +80,7 @@ def chooseObjectFromList(objects,attribute):
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:
@ -81,6 +89,7 @@ def chooseRelevantDescriptionByActivation(workspaceObject):
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:
@ -90,6 +99,7 @@ def similarPropertyLinks(slip_node):
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
@ -97,12 +107,15 @@ def chooseSlipnodeByConceptualDepth(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);
@ -118,14 +131,17 @@ def __localRelevance(string,slipnode,relevance):
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
@ -143,4 +159,3 @@ def getMappings(objectFromInitial,objectFromTarget, initialDescriptions, targetD
) )
mappings += [mapping] mappings += [mapping]
return mappings return mappings

View File

@ -1,10 +1,12 @@
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)
@ -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
@ -233,5 +234,3 @@ class Group(WorkspaceObject):
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,6 +1,7 @@
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)
@ -30,7 +31,7 @@ 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):
@ -45,4 +46,3 @@ class Letter(WorkspaceObject):
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,6 +3,7 @@ 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)
@ -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

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__()")

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))

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,15 +33,18 @@ class WorkspaceFormulas(object):
workspaceFormulas = WorkspaceFormulas() workspaceFormulas = WorkspaceFormulas()
def numberOfObjects(): def numberOfObjects():
return len(workspace.objects) return len(workspace.objects)
def chooseUnmodifiedObject(attribute, inObjects): def chooseUnmodifiedObject(attribute, inObjects):
objects = [o for o in inObjects if o.string != workspace.modified] 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 = []
for objekt in workspace.objects: for objekt in workspace.objects:
@ -52,6 +56,7 @@ def chooseNeighbour(source):
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')
@ -59,6 +64,7 @@ def chooseDirectedNeighbor(source,direction):
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:
@ -71,6 +77,7 @@ def __chooseLeftNeighbor(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
@ -78,6 +85,7 @@ def __chooseRightNeighbor(source):
] ]
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]
@ -87,9 +95,11 @@ def chooseBondFacet(source, destination):
i = formulas.selectListPosition(supports) i = formulas.selectListPosition(supports)
return bondFacets[i] return bondFacets[i]
def __supportForDescriptionType(descriptionType, string): def __supportForDescriptionType(descriptionType, string):
return (descriptionType.activation + __descriptionTypeSupport(descriptionType, string)) / 2 return (descriptionType.activation + __descriptionTypeSupport(descriptionType, string)) / 2
def __descriptionTypeSupport(descriptionType, string): 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
@ -101,6 +111,7 @@ 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
@ -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,6 +4,7 @@ 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)
@ -223,4 +224,3 @@ class WorkspaceObject(WorkspaceStructure):
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

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
@ -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()')