def execute_strategy(strategy, args, options):
    """Compile the proze project using the strategy.
    @type  strategy: BaseStrategy
    @param strategy: Strategy to use.
    @type  args: object
    @param args: Parsed command line args.
    @type  options: DotMap
    @param options: Compile options parsed from the config file.
    """
    blocks = Blocks()
    names = Names(options)
    state = State()
    output_path = args.output + '.' + args.doctype
    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    with strategy.compile(output_path) as compiler:
        for filename in options.compile.order:
            path = args.path + '/' + filename
            try:
                with open(path, 'r') as proze_file:
                    blocks.reset()
                    state.reset()
                    line_number = 0
                    for raw_line in proze_file:
                        line_number = line_number + 1
                        line = blocks.remove(raw_line)
                        state.update(raw_line)
                        check_invalid_names(line, path, line_number, names)
                        if line:
                            compiler.write(line, state)
            except FileNotFoundError:
                print('MISSING: Cannot find file "{}". '.format(path) +
                      'Update the file names in your config file.')
Exemple #2
0
    class __impl:
        def __init__(self, logger):
            self.logger = logger
            self.state = State()
            self.serial = serial.Serial(
                port='/dev/serial0',
                baudrate=9600,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE,
                bytesize=serial.EIGHTBITS,
                timeout=0)
            self.buzzer = Buzzer(4)
            self.led = LED(26)
            self.button = Button(12, True)
            self.button.when_pressed = lambda: self.toggleHypertrain()

            self.buffer = ''
            self.jsonParsePattern = regex.compile(r'\{(?:[^{}]|(?R))*\}')

            self.thread = threading.Thread(target=self.readThread)
            self.threadStop = False

        def toggleHypertrain(self):
            self.state.Stopped = not self.state.Stopped
            # self.state.Loaded = not self.state.Loaded
            self.logger.info(
                "Button pressed, new state Stopped: " + str(self.state.Stopped))
            self.led.blink(1, 1, 1)
            if (self.state.Stopped):
                self.sendStartStop('stop')
                self.state.reset()
            else:
                self.sendStartStop('start')

        def sendStartStop(self, action):
            data = {}
            data['sender'] = 'raspberry'
            data['action'] = action
            self.write(json.dumps(data))

        def sendApproachStop(self):
            data = {}
            data['sender'] = 'raspberry'
            data['action'] = 'approachstop'
            self.write(json.dumps(data))

        def sendSpeedPercent(self, acceleration):
            if (acceleration != self.state.LastAccelerationPercent):
                self.state.LastAccelerationPercent = acceleration
                data = {}
                data['sender'] = 'raspberry'
                data['action'] = 'accelerate'
                data['payload'] = acceleration
                self.write(json.dumps(data))

        def buzzSignalNumber(self, num):
            self.buzzer.beep(0.3, 0.3, num)

        def readThreadStart(self):
            self.thread.start()

        def readThreadStop(self):
            self.threadStop = True

        def readThread(self):
            while (not self.threadStop):
                self.read()
                time.sleep(self.state.ThreadSleepingThreshold)

        def read(self):
            if (self.serial.in_waiting > 0):
                while self.serial.inWaiting():
                    asciiBytes = self.serial.read(self.serial.inWaiting())
                    if (asciiBytes):
                        self.buffer += asciiBytes.decode('ascii')

                for incoming in self.extractJSONObjects(self.buffer):
                    self.parse(str(incoming).replace("'", '"'))

        def write(self, message):
            if (message):
                self.logger.info("Sending: " + message)
                self.serial.write(message.encode())

        def parse(self, message):
            jsonObj = None
            try:
                jsonObj = json.loads(message)
                if (jsonObj["sender"] == "arduino"):
                    if (jsonObj["action"] == "loaded"):
                        self.led.blink(1, 1, 1)
                        self.buzzSignalNumber(1)
                        if (not self.state.Loaded):
                            self.state.Loaded = True
                    if (jsonObj["action"] == "speed"):
                        return
                    if (jsonObj["action"] == "way" and jsonObj["payload"]):
                        self.logger.debug("Way: " + message)
                        self.state.CoveredDistance = int(
                            jsonObj["payload"])
                        return

                self.logger.debug("Receiving: " + message)

            except AttributeError as e:
                self.logger.error(
                    "AttributeError in JSON: " + str(e))
            except Exception as e:
                self.logger.error("Unknown message: " + str(e))
                self.logger.error(message)

        def extractJSONObjects(self, text, decoder=JSONDecoder()):
            pos = 0
            while True:
                match = text.find('{', pos)
                if match == -1:
                    break
                try:
                    result, index = decoder.raw_decode(text[match:])
                    yield result
                    pos = match + index
                    # now strip the match from our buffer
                    self.buffer = self.buffer[pos:]
                except ValueError:
                    pos = match + 1
Exemple #3
0
class StocksEnv(gym.Env):
    """docstring for StockEnv"""
    metadata = {'render.modes': ['human']}

    def __init__(self,
                 prices,
                 bars_count=DEFAULT_BARS_COUNT,
                 commission=DEFAULT_COMMISSION_PERC,
                 reset_on_close=True,
                 state_1d=False,
                 random_ofs_on_reset=True,
                 reward_on_close=False,
                 volumes=False):
        assert isinstance(prices, dict)
        self._prices = prices
        if state_1d:
            self._state = State1D(bars_count, commission, reset_on_close,
                                  reward_on_close, volumes)
        else:
            self._state = State(bars_count, commission, reset_on_close,
                                reward_on_close, volumes)

        self.action_space = gym.spaces.Discrete(n=len(Actions))
        self.obs_space = gym.spaces.Box(low=-np.inf,
                                        high=np.inf,
                                        shape=self._state.shape,
                                        dtype=np.float32)
        self.random_ofs_on_reset = random_ofs_on_reset
        self.seed()

    @classmethod
    def from_dir(cls, data_dir, **kwargs):
        prices = {
            file: data.load_relative(file)
            for file in data.price_files(data_dir)
        }
        return StocksEnv(prices, **kwargs)

    def reset(self):
        # make selection of the instrument and it's offset. Then reset the state
        self._instrument = self.np_random.choice(list(self._prices.keys()))
        prices = self._prices[self._instrument]
        bars = self._state.bars_count
        if self.random_ofs_on_reset:
            offset = self.np_random.choice(prices.high.shape[0] -
                                           bars * 10) + bars
        else:
            offset = bars
        self._state.reset(prices, offset)
        return self._state.encode()

    def step(self, action_idx):
        action = Actions(action_idx)
        reward, done = self._state.step(action)
        obs = self._state.encode()
        info = {"instrument": self._instrument, "offset": self._state._offset}
        return obs, reward, done, info

    def render(self, mode='human', close=False):
        pass

    def close(self):
        pass

    def seed(self, seed=None):
        self.np_random, seed1 = seeding.np_random(seed)
        seed2 = seeding.hash_seed(seed1 + 1) % 2**31
        return [seed1, seed2]