Esempio n. 1
0
    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()
    def test_testcase5(self):
        """
        测试用例如下:
        implementation: s0 -but?-> s1, s1 -liq!-> s2, s1 -choc!-> s3
        specification: s0 -but?-> s1, s0 -but?-> s2, s1 -liq!-> s3, s2 -but?-> s4, s4 -choc!-> s5
        :return: None
        """
        # implementation
        imp_root = Node(None, State("s0"))
        node1 = Node(Action("but", ActionEnum.INPUT), State("s1"))
        node2 = Node(Action("liq", ActionEnum.OUTPUT), State("s2"))
        node3 = Node(Action("choc", ActionEnum.OUTPUT), State("s3"))
        imp_root.children = [node1]
        node1.children = [node2, node3]
        imp = LTSTree(imp_root)

        # specification
        spec_root = Node(None, State("s0"))
        node1 = Node(Action("but", ActionEnum.INPUT), State("s1"))
        node2 = Node(Action("but", ActionEnum.INPUT), State("s2"))
        spec_root.children = [node1, node2]
        node3 = Node(Action("liq", ActionEnum.OUTPUT), State("s3"))
        node1.children = [node3]
        node4 = Node(Action("but", ActionEnum.INPUT), State("s4"))
        node2.children = [node4]
        node5 = Node(Action("liq", ActionEnum.OUTPUT), State("s5"))
        node4.children = [node5]
        spec = LTSTree(spec_root)

        self.assertFalse(imp.io_conform(spec),
                         msg="Error, test result: io conform!")
Esempio n. 3
0
        def __init__(self, vs, imgOutput):
            self.__vs = vs
            self.__imgOutput = imgOutput
            self.image = None
            self.logger = Logger()
            self.state = State()
            self.tesseract = PyTessBaseAPI(psm=PSM.SINGLE_CHAR,
                                           oem=OEM.LSTM_ONLY,
                                           lang="digits")
            self.filter = Filter()

            self.signalThresholdY = 160
            self.LAPPatternSesibility = 5

            self.recordStamp = time.strftime(self.logger.timeFormat)
            self.recordNum = 0
            self.recordFolder = None
            self.cntNum = 0

            if (self.state.RecordImage):
                root = 'record'
                if not os.path.isdir(root):
                    os.mkdir(root)
                self.recordFolder = os.path.join(root, self.recordStamp)
                if not os.path.isdir(self.recordFolder):
                    os.mkdir(self.recordFolder)
 def test_first_character_chapter(self):
     """Insert a tab for first paragraph of a chapter."""
     rules = self._create_rules_prose_first_char()
     state = State()
     state.previous_line.is_blank = True
     state.is_first_paragraph = True
     state.markup.is_chapter = True
     state.markup.is_section = False
     self.assertEqual(rules.first_character(state), '\t')
     self.assertEqual(rules.first_character(state, use_spaces=True), '    ')
     rules.options.compile.paragraph.mode = 'justified'
     self.assertEqual(rules.first_character(state), '')
     self.assertEqual(rules.first_character(state, use_spaces=True), '')
 def test_first_character_not_first_line(self):
     """Don't insert a tab if the previous line isn't blank."""
     rules = self._create_rules_prose_first_char()
     state = State()
     state.previous_line.is_blank = False
     state.is_first_paragraph = False
     state.is_chapter = False
     state.is_section = False
     self.assertEqual(rules.first_character(state), '')
     self.assertEqual(rules.first_character(state, use_spaces=True), '')
     rules.options.compile.paragraph.mode = 'justified'
     self.assertEqual(rules.first_character(state), '')
     self.assertEqual(rules.first_character(state, use_spaces=True), '')
Esempio n. 6
0
def hyperloop():

    imageFolder = None
    imageNum = 0

    logger = Logger('relog')
    logger.setLogLevel('debug')
    logger.info('Started replay')

    state = State()
    for p in sys.argv:
        if (os.path.isdir(p)):
            imageFolder = p
        elif (p.isdigit()):
            imageNum = int(p)
        elif (p == "-lap"):
            state.Approaching = Signal.LAP
        elif (p == "-up"):
            state.Approaching = Signal.UPPER
        elif (p == "-lo"):
            state.Approaching = Signal.LOWER
        elif (p == "-s"):
            state.Approaching = Signal.UPPER

    if (state.Approaching != Signal.LAP):
        state.setStopSignal(1)

    camera = Camera(None, True)

    if imageFolder:
        # program loop
        files = sorted_aphanumeric(os.listdir(imageFolder))
        while True:
            try:
                file = os.path.join(imageFolder, files[imageNum])
                logger.info("[" + str(imageNum) + "] Loaded file: " + file)
                image = cv2.imread(file, 1)

                camera.capture(image)

                key = cv2.waitKey(0) & 0xFF

                if key == ord("n"):
                    # cv2.destroyAllWindows()
                    if (imageNum + 1 < len(files)):
                        imageNum += 1
                elif key == ord("b"):
                    # cv2.destroyAllWindows()
                    if (imageNum - 1 >= 0):
                        imageNum -= 1
                elif key == ord('q'):
                    break

            except KeyboardInterrupt:
                break
            except Exception as e:
                logger.logError(e)
                traceback.print_exc(limit=3, file=sys.stdout)

    logger.info('Stopped')
    def test_testcase2(self):
        """
        测试用例如下:
        implementation: s0 -but?-> s1, s1 -liq!-> s2
        specification: s0 -but?-> s1, s1 -liq!-> s2, s1 -choc-> s3
        :return: None
        """
        # implementation
        imp_root = Node(None, State("s0"))
        node1 = Node(Action("but", ActionEnum.INPUT), State("s1"))
        node2 = Node(Action("liq", ActionEnum.OUTPUT), State("s2"))
        imp_root.children = [node1]
        node1.children = [node2]
        imp = LTSTree(imp_root)

        # specification
        spec_root = Node(None, State("s0"))
        node1 = Node(Action("but", ActionEnum.INPUT), State("s1"))
        node2 = Node(Action("liq", ActionEnum.OUTPUT), State("s2"))
        node3 = Node(Action("choc", ActionEnum.OUTPUT), State("s3"))
        spec_root.children = [node1]
        node1.children = [node2, node3]
        spec = LTSTree(spec_root)

        self.assertTrue(imp.io_conform(spec), msg="io not conform")
 def test_testcase1(self):
     """
     测试用例如下:
     implementation:s0 -act1?-> s1
     specification: s0 -act1?-> s1
     :return: None
     """
     imp_root = Node(None, State("s0"))
     imp_root.children = [
         Node(Action("act1", ActionEnum.INPUT), State("s1"))
     ]
     spec_root = Node(None, State("s0"))
     spec_root.children = [
         Node(Action("act1", ActionEnum.INPUT), State("s1"))
     ]
     imp = LTSTree(imp_root)
     spec = LTSTree(spec_root)
     self.assertTrue(imp.io_conform(spec), msg="io not conform")
Esempio n. 9
0
        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
Esempio n. 10
0
    def __init__(self):
        self.state = State()
        self.arduino = Arduino()
        self.observation_space = SomeSpace(4)
        self.action_space = SomeSpace(1, 1.0, -1.0)
        self.episodeStartTime = datetime.datetime.now()
        self.arduino.resetRobot()

        # Pin Setup:
        self.buttonPin = 4
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
Esempio n. 11
0
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.')
Esempio n. 12
0
    def __init__(self, environment):
        self.states = {}
        self.stateManual = State(States.MANUAL, environment)
        self.stateChallenge1 = StateChallenge1(States.CHALLENGE1, environment)
        self.stateChallenge2 = LineFollower(States.CHALLENGE2, environment)
        self.stateChallenge3 = StateChallenge3(States.CHALLENGE3, environment)
        self.stateChallenge5 = StateDiscs(States.CHALLENGE5, environment)
        self.stateChallenge4 = StateChallenge4(States.CHALLENGE4, environment)
        self.stateChallenge6 = State(States.CHALLENGE6, environment)
        self.stateChallenge7 = State(States.CHALLENGE7, environment)
        self.stateTransit12 = StateTransit(States.TRANSIT12, environment)
        self.stateTransit23 = State(States.TRANSIT23, environment)
        self.stateTransit34 = State(States.TRANSIT34, environment)
        self.stateTransit45 = State(States.TRANSIT45, environment)
        self.stateTransit56 = State(States.TRANSIT56, environment)
        self.stateTransit67 = State(States.TRANSIT67, environment)

        self.states[States.MANUAL] = self.stateManual
        self.states[States.CHALLENGE1] = self.stateChallenge1
        self.states[States.CHALLENGE2] = self.stateChallenge2
        self.states[States.CHALLENGE3] = self.stateChallenge3
        self.states[States.CHALLENGE4] = self.stateChallenge4
        self.states[States.CHALLENGE5] = self.stateChallenge5
        self.states[States.CHALLENGE6] = self.stateChallenge6
        self.states[States.CHALLENGE7] = self.stateChallenge7
        self.states[States.TRANSIT12] = self.stateTransit12
        self.states[States.TRANSIT23] = self.stateTransit23
        self.states[States.TRANSIT34] = self.stateTransit34
        self.states[States.TRANSIT45] = self.stateTransit45
        self.states[States.TRANSIT56] = self.stateTransit56
        self.states[States.TRANSIT67] = self.stateTransit67

        self.stateChallenge1.NextState = States.TRANSIT12
        self.stateTransit12.NextState = States.CHALLENGE2
        self.stateChallenge2.NextState = States.TRANSIT23
        self.stateTransit23.NextState = States.CHALLENGE3
        self.stateChallenge3.NextState = States.TRANSIT34
        self.stateTransit34.NextState = States.CHALLENGE4
        self.stateChallenge4.NextState = States.TRANSIT45
        self.stateTransit45.NextState = States.CHALLENGE5
        self.stateChallenge5.NextState = States.TRANSIT56
        self.stateTransit56.NextState = States.CHALLENGE6
        self.stateChallenge6.NextState = States.TRANSIT67
        self.stateTransit67.NextState = States.CHALLENGE7

        self.currentState = self.stateManual
        self.currentState.Enter()
Esempio n. 13
0
        def __init__(self, logger):
            self.logger = logger
            self.bus = smbus.SMBus(1)
            self.x = 0.0
            self.y = 0.0
            self.z = 0.0
            self.busReady = True
            self.state = State()

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

            try:
                self.__initBus__()
            except Exception as e:
                self.busReady = False
                self.logger.logError(e)
Esempio n. 14
0
def parse_states(root: ET.Element) -> Set[State]:
    """Parses the JFLAP xml to get a dict of states

    Args:
        root (ET.Element): The root of the JFLAP xml document

    Returns:
        Dict[State]: A dict of all states
    """
    states = set()

    # Parse id, name, initial, and final
    for state in root.findall("automaton")[0].findall("state"):
        name = str(state.get("name"))
        identifier = int(str(state.get("id")))
        initial = len(state.findall("initial")) > 0
        final = len(state.findall("final")) > 0

        states.add(State(id=identifier, name=name,
                         initial=initial, final=final))

    return states
Esempio n. 15
0
# 5 October 2017, Benjamin Shanahan.

from lib.state import State
from lib.telemetry import Telemetry, PORT

import sys
import threading
import Queue
import argparse

# Default port for telemetry radio
DEFAULT_PORT = "/dev/ttyUSB0"

if __name__ == "__main__":

    state = State()

    ###########################################################################
    ## Functions
    ###########################################################################

    # Asynchronously add any screen input to a queue
    def add_input(input_queue):
        while True:
            input_queue.put(sys.stdin.read(1))

    # Write command to telemetry radio
    def broadcast(cmd=None):
        if cmd is not None:
            radio.write(chr(cmd))
It is advised to explore the program by following the call stack of executing one feature.
An IDE that can automatically show docstrings as a pop up on hover is strongly recommended,
as the documentation has been written with this in mind.


No author for the different files have been specified as there is only one.
"""
"""
The program state consists of:
    Raw data loaded in
    Aggregated data of the raw data
    Aggregation mode (period)
    Status messages
"""
#Initialize state of program
state = State()
"""
The following section defines the main menu of the program.
Menus are defined as lists of tuples,
where the first element in the tuple is the menu option text,
while the second element in the tuple is the function to call if the option is selected.

The state of the program is passed into each menu option function, 
except the "Quit" option as it does not need the program state.
"""

#Define main menu of the program. This is where the program starts.
main_menu = [
    #Parameter is program state
    ("Load data", lambda: display_load_data_menu(state)),
    ("Aggregate data", lambda: display_aggregate_menu(state)),
Esempio n. 17
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]
Esempio n. 18
0
def hyperloop():

    logger = Logger()
    logger.setLogLevel('info')
    logger.info('Started')

    state = State()
    for p in sys.argv:
        if (p == "--standalone" or p == "-s"):
            state.Standalone = True
            logger.info("Standalone mode activated")
        elif (p == "--nocamera" or p == "-n"):
            state.NoImageTransfer = True
            logger.info("Camera image transfer X11 disabled")
        elif (p == "--record" or p == "-r"):
            state.RecordImage = True
            logger.info("Record mode activated")
        elif (p == "--measure" or p == "-m"):
            state.MeasureMode = True
            logger.info("Measure mode activated")
        elif (p == "--invert" or p == "-i"):
            state.InvertCamera = True
            logger.info("Inverted camera activated")

    vs = PiVideoStream(resolution=(480, 368), framerate=32).start()
    piCamera = vs.camera
    piCamera.exposure_mode = 'sports'
    piCamera.ISO = 1600
    camera = Camera(vs, not state.NoImageTransfer)

    # camera warmup
    camera.warmup()

    communication = Communication(logger)
    acceleration = Acceleration(logger)

    # reads any input incoming over UART / i2c / GPIO
    communication.readThreadStart()
    # measure acceleration
    acceleration.measureThreadStart()

    fps = FPS().start()

    # program loop
    while True:
        try:
            if ((not state.Stopped and state.Loaded) or state.Standalone):

                # if (state.StopSignalNum == 0 or (state.Approaching and not state.StopSignalNum == 0) or state.Standalone):
                # capture image from videostream and analyze
                camera.capture()
                fps.update()

                if (state.StopSignalNum == 0 and state.LapSignalCount < 2 and not state.Approaching == Signal.UPPER):
                    communication.sendSpeedPercent(25)
                    state.Approaching = Signal.UPPER
                    logger.info("Approaching upper signal")
                # if we found our stop signal, announce it
                elif (state.StopSignalNum != 0 and not state.StopSignalAnnounced):
                    communication.sendSpeedPercent(100)
                    communication.buzzSignalNumber(state.StopSignalNum)
                    state.setStopSignalAnnounced(True)
                    state.Approaching = Signal.LAP
                    logger.info("Approaching lap signal")
                # if we passed the lap signal twice, deccelerate to X percent
                elif (state.StopSignalAnnounced and state.LapSignalCount >= 2 and not state.Approaching == Signal.LOWER):
                    communication.sendSpeedPercent(25)
                    state.Approaching = Signal.LOWER
                    logger.info("Approaching lower signal")
                elif (state.StopSignalAnnounced and state.StopSignalNum == state.CurrentNum and not state.ApproachStop):
                    communication.sendApproachStop()
                    communication.sendSpeedPercent(25)
                    state.ApproachStop = True
                    logger.info("Approaching stop")

            if (cv2.waitKey(1) & 0xFF) == ord('q'):
                break

        except KeyboardInterrupt:
            break
        except Exception as e:
            logger.logError(e)
            traceback.print_exc(limit=3, file=sys.stdout)
    fps.stop()

    communication.sendStartStop('stop')
    time.sleep(1)
    logger.info('FPS: ' + str(fps.fps()))
    logger.info('Aborting running threads')
    communication.readThreadStop()
    acceleration.measureThreadStop()
    logger.info('Stopped')
Esempio n. 19
0
    class __impl:
        def __init__(self, vs, imgOutput):
            self.__vs = vs
            self.__imgOutput = imgOutput
            self.image = None
            self.logger = Logger()
            self.state = State()
            self.tesseract = PyTessBaseAPI(psm=PSM.SINGLE_CHAR,
                                           oem=OEM.LSTM_ONLY,
                                           lang="digits")
            self.filter = Filter()

            self.signalThresholdY = 160
            self.LAPPatternSesibility = 5

            self.recordStamp = time.strftime(self.logger.timeFormat)
            self.recordNum = 0
            self.recordFolder = None
            self.cntNum = 0

            if (self.state.RecordImage):
                root = 'record'
                if not os.path.isdir(root):
                    os.mkdir(root)
                self.recordFolder = os.path.join(root, self.recordStamp)
                if not os.path.isdir(self.recordFolder):
                    os.mkdir(self.recordFolder)

        def showImg(self, window, image):
            if self.__imgOutput:
                cv2.imshow(window, image)

        def warmup(self):
            time.sleep(2.0)
            self.tesserOCR(np.zeros((1, 1, 3), np.uint8))

        def tesserOCR(self, image):
            self.tesseract.SetImage(Image.fromarray(image))
            return self.tesseract.GetUTF8Text(
            ), self.tesseract.AllWordConfidences()

        def dominantColor(self, img, clusters=2):
            data = np.reshape(img, (-1, 3))
            data = np.float32(data)

            criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10,
                        1.0)
            flags = cv2.KMEANS_RANDOM_CENTERS
            _, _, centers = cv2.kmeans(data, 1, None, criteria, 10, flags)
            return centers[0].astype(np.int32)

        def analyzeRect(self, image, warped, box, x, y):
            # find amount of color blue in warped area, assuming over X% is the lap signal
            if (self.getAmountOfColor(warped, Colors.lower_blue_color,
                                      Colors.upper_blue_color, True) > 0.1):
                self.logger.info("Rundensignal")
                self.state.setCurrentSignal(Signal.LAP)
                return "Rundensignal"

        def analyzeSquare(self, image, warped, box, x, y):

            #dominantColor, percent, _ = self.dominantColor(warped, 3)
            # dominantColor = self.dominantColor(
            #    cv2.cvtColor(warped, cv2.COLOR_BGR2HSV), 3)
            """  color = 'k'
             # find amount of color black in warped area, assuming over X% is a numeric signal
             if ((dominantColor <= 70).all()):
                 color = 'Black'

             elif ((dominantColor >= 180).all()):
                 color = 'White'

             if (color): """
            resizedWarp = cv2.resize(warped,
                                     None,
                                     fx=2.0,
                                     fy=2.0,
                                     interpolation=cv2.INTER_CUBIC)

            # gray
            optimized = cv2.cvtColor(resizedWarp, cv2.COLOR_BGR2GRAY)

            # blur
            optimized = cv2.GaussianBlur(optimized, (5, 5), 0)

            # binary image
            optimized = cv2.threshold(optimized, 0, 255,
                                      cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

            # binary inversion if dominant color is black
            """ if (color == 'Black'):
                optimized = cv2.bitwise_not(optimized) """

            # now check the frame (1px) of the image.. there shouldn't be any noise since its a clean signal background
            h, w = optimized.shape[0:2]
            clean = optimized[0, 0]
            for iFrame in range(0, 2):
                for iHeight in range(h):
                    if not (optimized[iHeight, iFrame] == clean) or not (
                            optimized[iHeight, w - 1 - iFrame] == clean):
                        return False
                for iWidth in range(w):
                    # or not(optimized[h - iFrame, iWidth])
                    if not (optimized[iFrame, iWidth] == clean):
                        return False

            # cv2.imwrite("records/opt/" + str(self.cntNum) + ".jpg", optimized)

            output, confidence = self.tesserOCR(optimized)

            # if the resulting text is below X% confidence threshold, we skip it
            if not output or confidence[0] < 95:
                return False

            # clean up output from tesseract
            output = output.replace('\n', '')
            output = output.replace(' ', '')

            if output.isdigit() and 0 < int(output) < 10:
                """ self.showImg("opt " + str(self.cntNum),
                                np.hstack((resizedWarp, cv2.cvtColor(optimized, cv2.COLOR_GRAY2BGR)))) """
                if y <= self.signalThresholdY:
                    self.logger.info('Stop Signal OCR: ' + output + ' X: ' +
                                     str(x) + ' Y: ' + str(y) +
                                     ' Confidence: ' + str(confidence[0]) +
                                     '%')  # + ' DC: ' + str(dominantColor))
                    self.state.setStopSignal(int(output))
                    return 'S: ' + output
                elif self.state.StopSignalNum != 0:
                    self.logger.info('Info Signal OCR: ' + output + ' X: ' +
                                     str(x) + ' Y: ' + str(y) +
                                     ' Confidence: ' + str(confidence[0]) +
                                     '%')  # + ' DC: ' + str(dominantColor))
                    self.state.setCurrentSignal(Signal.UPPER, int(output))
                    return 'I: ' + output

        def getAmountOfColor(self,
                             img,
                             lowerColor,
                             upperColor,
                             convert2hsv=True):
            if (convert2hsv):
                img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

            # create mask from color range
            maskColor = cv2.inRange(img, lowerColor, upperColor)
            # get ratio of active pixels
            ratio_color = cv2.countNonZero(maskColor) / (img.size)
            return ratio_color

        # color picker for manual debugging
        def pick_color(self, event, x, y, flags, param):
            if event == cv2.EVENT_LBUTTONDOWN:
                pixel = self.image[y, x]
                color = np.array([pixel[0], pixel[1], pixel[2]])
                self.logger.info(pixel)

        # capture frames from the camera
        def capture(self, savedImg=None):
            if (savedImg is not None):
                image = savedImg
            else:
                image = self.__vs.read()
                if (self.state.InvertCamera):
                    image = imutils.rotate(image, angle=180)

            self.image = image

            if (self.state.RecordImage):
                self.recordNum += 1
                cv2.imwrite(
                    os.path.join(self.recordFolder,
                                 str(self.recordNum) + ".jpg"), image)
                return

            if (self.state.Approaching == Signal.UPPER
                    or self.state.Approaching == Signal.LOWER):
                self.findNumberSignal(image)
            elif (self.state.Approaching == Signal.LAP):
                self.findLapSignal(image)

        def findLapSignal(self, image):
            contourImage = image.copy()

            blur = cv2.GaussianBlur(image, (3, 3), 0)
            hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)
            self.image = hsv
            mask = cv2.inRange(hsv, Colors.lower_blue_color,
                               Colors.upper_blue_color)

            cnts = imutils.grab_contours(
                cv2.findContours(mask.copy(), cv2.RETR_LIST,
                                 cv2.CHAIN_APPROX_SIMPLE))

            if len(cnts) > 0:

                # transform all contours to rects
                rects = [cv2.boundingRect(cnt) for cnt in cnts]

                # now iterate all of the rects, trying to find an approximated sibiling shifted in Y-direction
                for rect in rects:
                    (x, y, w, h) = rect
                    cv2.rectangle(contourImage, (x, y), (x + w, y + h),
                                  (0, 0, 255), 2)

                    # try to match the pattern from a given rect in all rects
                    counterPart = [
                        counterRect for counterRect in rects
                        if (counterRect != rect and x - 5 <= counterRect[0] <=
                            x + 5 and 2 * -(h + 5) <= y - counterRect[1] <= 2 *
                            (h + 5) and w - 5 <= counterRect[2] <= w + 5)
                        and h - 5 <= counterRect[3] <= h + 5
                    ]

                    if (counterPart):
                        (x, y, w, h) = counterPart[0]
                        cv2.rectangle(contourImage, (x, y), (x + w, y + h),
                                      (0, 255, 0), 2)
                        self.logger.info('LAP Signal')
                        self.state.captureLapSignal()
                        break

            self.showImg(
                'contourImage',
                np.hstack(
                    (hsv, contourImage, cv2.cvtColor(mask,
                                                     cv2.COLOR_GRAY2BGR))))
            cv2.setMouseCallback('contourImage', self.pick_color)

        def findNumberSignal(self, image):

            image_height = np.size(image, 0)
            image_width = np.size(image, 1)

            contourImage = image.copy()

            # focus only on the part of the image, where a signal could occur
            # image = image[int(image.shape[0] * 0.2):int(image.shape[0] * 0.8), 0:int(image.shape[1]*0.666)]

            mask = self.filter.autoCanny(image, 2, 3)

            # get a list of contours in the mask, chaining to just endpoints
            cnts = imutils.grab_contours(
                cv2.findContours(mask.copy(), cv2.RETR_LIST,
                                 cv2.CHAIN_APPROX_SIMPLE))

            # only proceed if at least one contour was found
            if len(cnts) > 0:
                # loop contours
                for self.cntNum, cnt in enumerate(cnts):

                    rect = cv2.minAreaRect(cnt)
                    _, _, angle = rect

                    # approximate shape
                    approx = cv2.approxPolyDP(cnt,
                                              0.02 * cv2.arcLength(cnt, True),
                                              True)

                    # the rectangle must not have a too big rotation (+/-10)
                    # and more than 3 connecting points
                    if len(approx) >= 3 and (-90 <= angle <= -80
                                             or angle >= -10):

                        box = cv2.boxPoints(rect)
                        box = np.int0(box)

                        (x, y, w, h) = cv2.boundingRect(approx)

                        # limit viewing range
                        if (y <= image_height * 0.2 or x >= image_width * 0.8):
                            continue

                        if (w <= 5 or h <= 5):
                            continue

                        # we are in approaching mode, thus we only care for the lower signals <= threshold
                        if ((self.state.Approaching == Signal.UPPER
                             and y >= self.signalThresholdY)
                                and not self.state.Standalone):
                            continue
                        elif ((self.state.Approaching == Signal.LOWER
                               and y <= self.signalThresholdY)
                              and not self.state.Standalone):
                            continue

                        sideRatio = w / float(h)

                        absoluteSizeToImageRatio = (
                            100 / (image_width * image_height)) * (w * h)

                        # calculate area of the bounding rectangle
                        rArea = w * float(h)

                        # calculate area of the contour
                        cArea = cv2.contourArea(cnt)
                        if (cArea):
                            rectContAreaRatio = (100 / rArea) * cArea
                        else:
                            continue

                        # cv2.drawContours(contourImage, [box], 0, (255, 0, 0), 1)
                        result = None

                        # is the rectangle sideways, check for lap signal
                        # if (h*2 < w and y <= self.signalThresholdY and rectContAreaRatio >= 80):
                        #result = self.analyzeRect(image, four_point_transform(image, [box][0]), box, x, y)
                        # find all contours looking like a signal with minimum area (1%)
                        if absoluteSizeToImageRatio >= 0.01:
                            # is it approx a square, or standing rect? then check for info or stop signal
                            if 0.2 <= sideRatio <= 1.1:
                                # transform ROI
                                if (sideRatio <= 0.9):
                                    coords, size, angle = rect
                                    size = size[0] + 8, size[1] + 4
                                    coords = coords[0] + 1, coords[1] + 1

                                    rect = coords, size, angle
                                    box = cv2.boxPoints(rect)
                                    box = np.int0(box)
                                """ cv2.drawContours(
                                    contourImage, [box], 0, (0, 255, 0), 1) """

                                warp = four_point_transform(image, [box][0])

                                result = self.analyzeSquare(
                                    image, warp, box, x, y)

                        if (result):
                            if (self.__imgOutput):
                                color = None
                                if (y >= self.signalThresholdY):
                                    color = (0, 0, 255)
                                else:
                                    color = (255, 0, 0)

                                cv2.drawContours(contourImage, [box], 0, color,
                                                 1)
                                cv2.drawContours(contourImage, [cnt], -1,
                                                 color, 2)
                                """ M = cv2.moments(cnt)
                                cX = int(M["m10"] / M["m00"])
                                cY = int(M["m01"] / M["m00"])
                                cv2.putText(contourImage, str(
                                    self.cntNum), (cX - 30, cY - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1) """

                                self.logger.debug(
                                    "[" + str(self.cntNum) + "] SideRatio: " +
                                    str(sideRatio) + " AreaRatio: " +
                                    str(rectContAreaRatio) + " ContArea: " +
                                    str(cArea) + " RectArea: " + str(rArea) +
                                    " AbsSize: " +
                                    str(absoluteSizeToImageRatio) +
                                    " CntPoints: " + str(len(approx)) +
                                    " Size: " + str(w) + "x" + str(h))
            """ if (self.__imgOutput):  # hsv img output
                hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
                cv2.namedWindow('contourImage')
                cv2.setMouseCallback('contourImage', self.pick_color)
                # self.showImg("hsv", hsv) """

            self.showImg(
                "contourImage",
                np.hstack((contourImage, cv2.cvtColor(mask,
                                                      cv2.COLOR_GRAY2BGR))))
Esempio n. 20
0
    arm = False
    logging = False
    deploy_chute = False
    power_off = False

    # Current state latches
    _armed = False  # Rocket is armed.
    _logging_on = False  # Data logging from IMU is on.
    _freefall_detected = False  # Rocket motor is not thrusting (rocket is in freefall).
    _chute_deployed = False  # Parachute is deployed.
    _nicrome_on = False  # Nicrome wire is heating.
    _apogee_detected = False  # Algorithm detects that apogee is reached.

    # Set current state of air controller and declare the time we last sent a
    # state update to the ground station
    state = State()
    state_last_sent = 0

    # Timing / counting variables
    time_chute_deployed = 0
    freefall_counter = 0
    apogee_counter = 0

    ###########################################################################
    ## Initialize our external devices
    ###########################################################################

    # Define logger but don't initialize a new log file here
    logger = lgr.Logger(init_log=False, init_camera=False, init_debug=True)

    # Define debug function
Esempio n. 21
0
        'ERROR': logging.ERROR,
        'CRITICAL': logging.CRITICAL
    }
    logging.basicConfig(format=(
        "[%(levelname)s] %(asctime)s %(filename)s:%(funcName)s:%(lineno)s %(message)s"
    ),
                        level=logging_level[options.logging_level])

    logging.info('Using configuration: {} | {}'.format(options.config_filename,
                                                       options.config_name))

    # Helpers
    bq = bqhandler.BQHandler()
    io = IO(gs_bucket=options.gs_bucket)
    viz = Viz(io)
    state = State()

    starttime, endtime = io.get_dates(options)
    logging.info('Using dataset {} and time range {} - {}'.format(
        options.feature_dataset, starttime.strftime('%Y-%m-%d'),
        endtime.strftime('%Y-%m-%d')))

    if options.save_data:
        tname = options.model + '_' + options.feature_dataset + '_' + options.config_name + '_train'
        tname = tname.replace('-', '_')
        bq.delete_table(options.project, options.feature_dataset, tname)
        tname = options.model + '_' + options.feature_dataset + '_' + options.config_name + '_test'
        tname = tname.replace('-', '_')
        bq.delete_table(options.project, options.feature_dataset, tname)

    if (options.station_specific_classifier
Esempio n. 22
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
Esempio n. 23
0
def main(args):
    config = Config(args.config)
    state = State(config)
    sgen = StreamGenerator(state)
    sgen.generate()