I keep having to write state machines that depend on time for various experiments I run and I'd like to know how to write them better. This state machine is for training a neural network by feeding in keys and expected values.
import numpy as np
dt = 0.001
period = 0.1
class SimpleEnv(object):
def __init__(self, keys, values, env_period=0.1):
self.keys = keys
self.values = values
self.env_idx = np.arange(len(keys))
self.idx = 0
self.shuffled = False
self.i_every = int(round(env_period/dt))
if self.i_every != env_period/dt:
raise ValueError("dt (%s) does not divide period (%s)" % (dt, period))
def get_key(self):
return self.keys[self.idx]
def get_val(self):
return self.values[self.idx]
def step(self, t):
i = int(round((t - dt)/dt)) # t starts at dt
ix = (i/self.i_every) % len(self.keys)
if ix == 0 and not self.shuffled:
print("shuffling")
np.random.shuffle(self.env_idx)
self.shuffled = True
elif ix == 1:
self.shuffled = False
self.idx = self.env_idx[ix]
return ix
# note the toy keys and values for testing purposes
s_env = SimpleEnv(np.arange(4), np.arange(1, 5), env_period=period)
key = -1
val = -1
ix = -1
# iterate through keys and values twice
run_time = 4 * period * 2
# the event loop
# starts at dt because of reasons
for t in np.arange(dt, run_time, dt):
last_ix = ix
ix = s_env.step(t)
key = s_env.get_key()
val = s_env.get_val()
assert key + 1 == val
if last_ix != ix:
print("Key: %s, Value: %s" %(key, val))
The results should look something like:
shuffling
Key: 2, Value: 3
Key: 0, Value: 1
Key: 3, Value: 4
Key: 1, Value: 2
shuffling
Key: 2, Value: 3
Key: 1, Value: 2
Key: 3, Value: 4
Key: 0, Value: 1
How can I write this better or more efficiently? Is there a state machine library in Python that would stop me from having to rewrite variations of this class all the time?