Friday, 20 February 2015

introducing: similar[op] |x>

We finally have enough pieces in place to describe the similar function operator. This beasty being quite useful! Arrogantly enough, I'm calling this thing "pattern recognition". In this post just the code. Examples will follow in future posts.

Python:
-- in the new_context() class:
# just simm applied to relevant kets
def pattern_recognition(self,pattern,op,t=0):
if type(op) == ket:
op = op.label[4:]
result = superposition()
for label in self.ket_rules_dict:
if op in self.ket_rules_dict[label]:
candidate_pattern = self.recall(op,label,True)
value = silent_simm(pattern,candidate_pattern)
if value > t:
result.data.append(ket(label,value))  # "result += ket(label,value)" when we swap in fast_superposition
return result.coeff_sort()

-- in the ket() class:
# implements: similar[op] |x>
def similar(self,context,op):
f = self.apply_op(context,op)
return context.pattern_recognition(f,op).delete_ket(self)
Now, try to explain in English what is going on.
Consider: similar[example-operator] |x>

First, find the superposition resulting from "example-operator" applied to |x>.
f = self.apply_op(context,op)
Then find all the kets that support the "example-operator" operator.
for label in self.ket_rules_dict:
if op in self.ket_rules_dict[label]:
Then find the superpositions resulting from "example-operator" applied to each of them.
candidate_pattern = self.recall(op,label,True)
Then find how similar they are to f/pattern:
value = silent_simm(pattern,candidate_pattern)
Keep only the interesting ones:
if value > t:
result.data.append(ket(label,value))
Sort and return the result:
return result.coeff_sort()
Delete |x> since we are always 100% similar with ourselves:
return context.pattern_recognition(f,op).delete_ket(self)
Update: Tweaked the code so we have a version of similar[op] that doesn't delete |x>
-- in the ket() class:
# implements: self-similar[op] |x>
def self_similar(self,context,op):
f = self.apply_op(context,op)
return context.pattern_recognition(f,op)
Update: tweaked similar so that if we want, the operator we apply to |x> is different to the operator we use in looking for matching patterns.

The new python:
-- in the ket() class:
def similar(self,context,ops):
try:
op1,op2 = ops.split(',')
except:
op1 = ops
op2 = ops
f = self.apply_op(context,op1)
return context.pattern_recognition(f,op2).delete_ket(self)

def self_similar(self,context,ops):
try:
op1,op2 = ops.split(',')
except:
op1 = ops
op2 = ops
f = self.apply_op(context,op1)
return context.pattern_recognition(f,op2)
Update: It should be rather trivial to write a parallel version of context.pattern_recognition() in the case of large sw files. Roughly, partition the sw file. Calculate the resulting superposition for each. Add them up, do a coeff sort. Done.