Last active
August 29, 2015 14:19
-
-
Save dfroger/14b3d1b985eabae87879 to your computer and use it in GitHub Desktop.
Automatic detection of required variable to make a restart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Variable: | |
""" | |
Determine required variables to restaure a state: | |
0: Go to state A | |
1: Go from state A to state B with an operation O. | |
2: Dump required variables. | |
3: Go to state A, and load required variables to be at state B. | |
4: Go from state B to state C with the same operation O. | |
""" | |
instances = {} | |
record_required = False | |
def __init__(self,value,name): | |
self._value = value | |
self._erased = False | |
self._used = False | |
self._required = False | |
self.name = name | |
Variable.instances[name] = self | |
@property | |
def value(self): | |
if Variable.record_required and not self._erased: | |
self._used = True | |
return self._value | |
@value.setter | |
def value(self, value): | |
self._value = value | |
if Variable.record_required: | |
self._erased = True | |
if self._used: | |
self._required = True | |
@property | |
def required(self): | |
return self._required | |
@staticmethod | |
def dump(): | |
return {name: var for name,var in Variable.instances.items() | |
if var.required} | |
class Fib(): | |
""" | |
Compute Fibonacci sequence | |
""" | |
def __init__(self,a,b): | |
self.n = Variable(5,'n') | |
self.a = Variable(a,'a') | |
self.b = Variable(b,'b') | |
self.i = Variable(0,'i') | |
self.a_backup = Variable(None,'a_backup') | |
def compute(self): | |
print(self.i.value, self.a.value, self.b.value, self.n.value) | |
self.a_backup.value = self.a.value | |
self.a.value = self.b.value | |
self.b.value += self.a_backup.value | |
self.i.value += 1 | |
def main(): | |
f = Fib(1,1) | |
Variable.record_required = True | |
f.compute() | |
Variable.record_required = False | |
f.compute() | |
backup = Variable.dump() | |
g = Fib(1,1) | |
for name, var in backup.items(): | |
# a, b and i are set. n and a_backup are not required. | |
print('set %s' % name) | |
setattr(g,name,var) | |
while g.i.value < g.n.value-1: | |
g.compute() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment