Esempio n. 1
0
def main():

    GPIO.setwarnings(False)
    print("\nResetting all pins..")

    gyroAddress = 0x68
    buzzerPin = 17
    hapticPin = 27
    buttonPin = 6
    laserPin = 5
    ledPin = 25

    gyroAddress = gyroAddress
    buzzerPin = buzzerPin
    hapticPin = hapticPin
    buttonPin = buttonPin
    laserPin = laserPin
    ledPin = ledPin

    state = State()
    gyro = MPU6050(gyroAddress)
    buzzer = OutputComponent(buzzerPin)
    haptic = OutputComponent(hapticPin)
    button = Button(buttonPin)
    laser = OutputComponent(laserPin)
    led = OutputComponent(ledPin)

    GPIO.cleanup()
    print("\t..done.\n")
Esempio n. 2
0
    def __init__(self, gyroAddress, buzzerPin, hapticPin, buttonPin, laserPin,
                 ledPin):

        self.gyroAddress = gyroAddress
        self.buzzerPin = buzzerPin
        self.hapticPin = hapticPin

        self.hapticPin2 = None
        if (settings.enableSecondHaptic):
            self.hapticPin2 = settings.secondaryHapticPin

        self.buttonPin = buttonPin
        self.laserPin = laserPin
        self.ledPin = ledPin

        self.state = State(State.StateType.PAUSED)
        self.gyro = MPU6050(self.gyroAddress)
        self.buzzer = Buzzer(self.buzzerPin)
        self.haptic = OutputComponent(self.hapticPin)

        self.haptic2 = None
        if (settings.enableSecondHaptic):
            self.haptic2 = OutputComponent(self.hapticPin2)

        self.button = Button(self.buttonPin)
        self.laser = OutputComponent(self.laserPin)
        self.led = LED(self.ledPin)

        self.metronomeDelay = ((float(60) / settings.numberOfSteps) -
                               (settings.stepdownDelay))

        if (self.metronomeDelay <= 0):
            print("\t**ERROR** Not a valid numberOfSteps defined in" +
                  " InitSettings.py. Exiting..")
            sys.exit(0)

        self.clf = joblib.load(
            '/home/pi/gaitmate/pi/MachineLearn/dTreeExport.pkl')
        self.predictedResult = None
        self.prevPredictedResult = None
Esempio n. 3
0
def build_LR0_automaton(grammar):
    assert len(grammar.startSymbol.productions) == 1, 'Grammar must be augmented'

    start_production = grammar.startSymbol.productions[0]
    start_item = Item(start_production, 0)

    automaton = State(start_item, True)

    pending = [start_item]
    visited = {start_item: automaton}

    while pending:
        current_item = pending.pop()
        if current_item.IsReduceItem:
            continue

        next_symbol = current_item.NextSymbol

        next_item = current_item.NextItem()
        if not next_item in visited:
            pending.append(next_item)
            visited[next_item] = State(next_item, True)

        if next_symbol.IsNonTerminal:
            for prod in next_symbol.productions:
                next_item = Item(prod, 0)
                if not next_item in visited:
                    pending.append(next_item)
                    visited[next_item] = State(next_item, True)

        current_state = visited[current_item]

        current_state.add_transition(next_symbol.Name, visited[current_item.NextItem()])

        if next_symbol.IsNonTerminal:
            for prod in next_symbol.productions:
                current_state.add_epsilon_transition(visited[Item(prod, 0)])

    return automaton
Esempio n. 4
0
def build_lr1_automaton(grammar):
    assert len(grammar.startSymbol.productions) == 1, 'Grammar must be augmented'

    firsts = compute_firsts(grammar)
    firsts[grammar.EOF] = ContainerSet(grammar.EOF)

    start_production = grammar.startSymbol.productions[0]
    start_item = Item(start_production, 0, lookaheads=(grammar.EOF,))
    start = frozenset([start_item])

    closure = closure_lr1(start, firsts)
    automaton = State(frozenset(closure), True)

    pending = [start]
    visited = {start: automaton}

    while pending:
        current = pending.pop()
        current_state = visited[current]

        for symbol in grammar.terminals + grammar.nonTerminals:

            kernels = goto_lr1(current_state.state, symbol, just_kernel=True)

            if not kernels:
                continue

            try:
                next_state = visited[kernels]
            except KeyError:
                pending.append(kernels)
                visited[pending[-1]] = next_state = State(frozenset(goto_lr1(current_state.state, symbol, firsts)),
                                                          True)

            current_state.add_transition(symbol.Name, next_state)

    automaton.set_formatter(multi_line_formatter)
    return automaton
Esempio n. 5
0
    def show_automaton(automaton: State, label: str, widget: QLabel,
                       image_tag: str):
        try:
            import pygraphviz as pgv
            dot = automaton.graph()

            (graph, ) = pydot.graph_from_dot_data(str(dot))
            graph.set_label(label)
            gr = pgv.AGraph().from_string(str(graph))
            gr.layout()
            gr.draw(image_tag)
            pix_map = QPixmap(image_tag)
            widget.setPixmap(pix_map)
            widget.show()
        except:
            return
Esempio n. 6
0
class Gaitmate:
    def __init__(self, gyroAddress, buzzerPin, hapticPin, buttonPin, laserPin,
                 ledPin):

        self.gyroAddress = gyroAddress
        self.buzzerPin = buzzerPin
        self.hapticPin = hapticPin

        self.hapticPin2 = None
        if (settings.enableSecondHaptic):
            self.hapticPin2 = settings.secondaryHapticPin

        self.buttonPin = buttonPin
        self.laserPin = laserPin
        self.ledPin = ledPin

        self.state = State(State.StateType.PAUSED)
        self.gyro = MPU6050(self.gyroAddress)
        self.buzzer = Buzzer(self.buzzerPin)
        self.haptic = OutputComponent(self.hapticPin)

        self.haptic2 = None
        if (settings.enableSecondHaptic):
            self.haptic2 = OutputComponent(self.hapticPin2)

        self.button = Button(self.buttonPin)
        self.laser = OutputComponent(self.laserPin)
        self.led = LED(self.ledPin)

        self.metronomeDelay = ((float(60) / settings.numberOfSteps) -
                               (settings.stepdownDelay))

        if (self.metronomeDelay <= 0):
            print("\t**ERROR** Not a valid numberOfSteps defined in" +
                  " InitSettings.py. Exiting..")
            sys.exit(0)

        self.clf = joblib.load(
            '/home/pi/gaitmate/pi/MachineLearn/dTreeExport.pkl')
        self.predictedResult = None
        self.prevPredictedResult = None

    # Component accessors.
    def buzzerAction(self):
        return self.buzzer

    def gyroAction(self):
        return self.gyro

    def hapticAction(self):
        return self.haptic

    def haptic2Action(self):
        return self.haptic2

    def buttonAction(self):
        return self.button

    def laserAction(self):
        return self.laser

    def ledAction(self):
        return self.led

    def writerAction(self):
        return self.writer

    #
    # Assigns/Retrives input integer to the the pin of the corresponding part.
    # Important for successful state operation.
    #
    def getBuzzerPin(self):
        return self.buzzerPin

    def getHapticPin(self):
        return self.hapticPin

    def getHaptic2Pin(self):
        return self.hapticPin2

    def getButtonPin(self):
        return self.buttonPin

    def getGyroAddress(self):
        return self.gyroAddress

    def getState(self):
        return self.state

    # Collects Data for a certain period of time at a certain frequency.
    # Returns true if the button is not pressed. Returns false if the button is
    # pressed.
    def collectData(self, duration, collectionFrequency, accuracy):

        if (collectionFrequency == 0):
            collectionFrequency = 1  # default to 1 collection per second

        if (duration == 0):
            return

        # Initializing write file to have the name of the local time and date.
        fileName = time.strftime("/home/pi/gaitmate/pi/logs/%m-%d-%y_%H%M%S",
                                 time.localtime())
        # print("Creating " + fileName + "..")

        self.writer = SaveFileHelper(fileName)

        timerEnd = time.time() + duration
        delay = 1.0 / float(collectionFrequency)

        while (time.time() < timerEnd):
            self.writerAction().appendToBuffer(
                self.gyroAction().getAccel_X(accuracy),
                self.gyroAction().getAccel_Y(accuracy),
                self.gyroAction().getAccel_Z(accuracy))

            # Code that stops script when button is pressed.
            if (self.buttonAction().isPressed()):
                self.ledAction().toggleOff()
                self.writerAction().dumpBuffer()
                return False

            time.sleep(delay)

        # print("Saving and creating a new filename..")
        self.writerAction().dumpBuffer()
        return True

    #
    # Test Code. Previously separate main() files, consolidated here.
    #
    def testBuzzer(self):
        print("Testing buzzer..")
        self.buzzerAction().metronome(self.metronomeDelay, 5,
                                      settings.stepdownDelay)
        print("\t.. done.\n")

    def testGyro(self):
        print("Testing Gyro..")

        timerEnd = time.time() + 5

        while time.time() < timerEnd:
            print(self.gyroAction().acceleration_toString(4))
            time.sleep(1)

        print("\t.. done.\n")

    def testHaptic(self):
        print("Testing haptics..")

        p1 = Process(target=self.hapticAction().metronome,
                     args=(self.metronomeDelay, 5, settings.stepdownDelay))
        p1.start()

        if (settings.enableSecondHaptic):
            p2 = Process(target=self.haptic2Action().metronome,
                         args=(self.metronomeDelay, 5, settings.stepdownDelay))
            p2.start()

            print("secondary haptic enabled. Joining processes..")

            p1.join()
            p2.join()

        print("\t.. done.\n")

    def testButton(self):
        print("Testing Button..")
        print("Will loop continuously. Press ctrl+c to exit.")
        try:

            while True:
                if (self.buttonAction().isPressed()):
                    print("Button is pressed!")
                else:
                    print("Button is not pressed.")
                time.sleep(0.2)

        except KeyboardInterrupt:
            print("\t.. done.\n")

    def testLaser(self):
        print("Testing Laser..")
        print("Will turn on/off continuously. Press ctrl+c to exit.")

        try:
            while True:
                if (settings.laserToggle):
                    self.laserAction().step(0.2)
                else:
                    print("\tLaserToggle is set to off in InitSettings.py. " +
                          "Exiting..")
                    break
        except KeyboardInterrupt:
            print("\t.. done.\n")

    def testLED(self):
        print("Testing LED..")
        print("Will pulse continuously. Press ctrl+c to exit.")

        try:
            self.ledAction().metronome(self.metronomeDelay, 5)
        except KeyboardInterrupt:
            print("\t.. done.\n")

    #
    # Main Execution loop of the Gaitmate.
    #
    def execute(self):
        while True:

            if (self.getState().isWalking()):
                self.doWalkingState()

            if (self.getState().isVibrating()):
                self.doVibratingState()

            if (self.getState().isRecovering()):
                self.doRecoveringState()

            if (self.getState().isPaused()):
                self.doPausedState()

    #
    # Walking State driver code
    #
    def doWalkingState(self):
        UI.box(["Entering Walking State"])
        time.sleep(settings.walkingState_entryDelay)
        self.state.changeState(self.state.StateType.WALKING)
        self.ledAction().toggleOn()
        self.laserAction().toggleOff()

        recv_end, send_end = Pipe(False)

        isWalkOk = self.checkWalking(send_end)

        if (isWalkOk):
            # If walking okay, do walking state.
            self.doWalkingState()
        else:
            # if walking badly, do vibrating state.
            self.doVibratingState()

    #
    # Vibrating State driver code
    #
    def doVibratingState(self):
        UI.box(["Entering Vibrating State"])
        time.sleep(settings.vibrationState_entryDelay)
        self.state.changeState(self.state.StateType.VIBRATING)
        self.ledAction().toggleOn()

        recv_end, send_end = Pipe(False)

        p1 = Process(target=self.hapticAction().metronome,
                     args=(self.metronomeDelay,
                           settings.vibrationState_Duration))
        p1.start()

        p2 = Process(target=self.checkWalking,
                     args=(send_end, settings.vibrationState_Duration))
        p2.start()

        if (settings.enableSecondHaptic):
            p3 = Process(target=self.haptic2Action().metronome,
                         args=(self.metronomeDelay,
                               settings.vibrationState_Duration))
            p3.start()

            p1.join()
            p2.join()
            p3.join()

        else:
            p1.join()
            p2.join()

        if (recv_end.recv()):
            # If walking okay, do walking state.
            self.doWalkingState()
        else:
            # If walking badly, do recovery state.
            self.doRecoveringState()

    #
    # Recovery State driver code
    #
    def doRecoveringState(self):
        UI.box(["Entering Recovering State"])
        self.state.changeState(self.state.StateType.RECOVERING)
        self.ledAction().toggleOn()

        if (settings.laserToggle):
            self.laserAction().toggleOn()
        else:
            self.laserAction().toggleOff()

        recv_end, send_end = Pipe(False)
        p1 = Process(target=self.hapticAndBuzzerMetronome,
                     args=(self.metronomeDelay, settings.stepdownDelay))
        p1.start()

        while True:
            p2 = self.checkWalking(send_end, process=p1)

            if (recv_end.recv()):
                # If walking okay, do walking state.
                p1.terminate()
                self.hapticAction().toggleOff()

                if (settings.enableSecondHaptic):
                    self.haptic2Action().toggleOff()

                self.buzzerAction().toggleOff()
                self.doWalkingState()
            else:
                # If walking badly, do recovery state.
                recv_end, send_end = Pipe(False)

    # Buzzer and haptic driver code as one singular process, to cut down on
    # multiprocessing time.
    def hapticAndBuzzerMetronome(self, delay, stepdownDelay=0.375):
        while True:

            GPIO.output(self.hapticPin, GPIO.HIGH)
            if (settings.enableSecondHaptic):
                GPIO.output(self.hapticPin2, GPIO.HIGH)
            GPIO.output(self.buzzerPin, GPIO.HIGH)

            time.sleep(stepdownDelay)

            GPIO.output(self.hapticPin, GPIO.LOW)
            if (settings.enableSecondHaptic):
                GPIO.output(self.hapticPin2, GPIO.LOW)
            GPIO.output(self.buzzerPin, GPIO.LOW)
            time.sleep(delay)

    #
    # Paused State driver code
    #
    def doPausedState(self):
        UI.box(["Entering Paused State"])
        self.ledAction().toggleOff()
        self.laserAction().toggleOff()
        time.sleep(settings.pausedState_entryDelay)
        self.state.changeState(self.state.StateType.PAUSED)

        # button checking time reduced because data collection is discarded
        # here. Only important thing is button press boolean
        buttonNotPressed = self.collectData(settings.checkDuration, 4, 4)

        while True:
            time.sleep(0.5)
            if (not buttonNotPressed):
                self.doWalkingState()
            else:
                buttonNotPressed = self.collectData(settings.checkDuration, 4,
                                                    4)

    def checkWalking(self,
                     send_end,
                     duration=settings.checkDuration,
                     process=None):
        print("\tChecking gait..")

        # Collect Data for 5 seconds.
        buttonNotPressed = self.collectData(duration, 4, 4)
        filename = self.writerAction().filename
        self.writerAction().closeWriter()

        # button not pressed returns true if the button wasn't pressed during
        # collection.
        if (buttonNotPressed):

            # Checking to see if patient is walking okay.
            loader = LoadFileHelper(filename)
            loader.parseData()
            X = [
                loader.getDataVariance_X(),
                loader.getDataVariance_Y(),
                loader.getDataVariance_Z()
            ]

            self.prevPredictedResult = self.predictedResult
            self.predictedResult = self.clf.predict(
                np.array(X).reshape(1, -1))[0]

            if ((self.predictedResult == "standing"
                 and self.prevPredictedResult == "standing")
                    or (self.predictedResult == "shuffling"
                        and self.prevPredictedResult == "shuffling")):
                send_end.send(False)
                return False
            else:
                send_end.send(True)
                return True

        # If button is pressed, change to paused state.
        else:
            if process is not None:
                process.terminate()
                self.hapticAction().toggleOff()
                if (settings.enableSecondHaptic):
                    self.haptic2Action().toggleOff()
                self.buzzerAction().toggleOff()
            self.doPausedState()
Esempio n. 7
0
    def compute_options(self, code, strings):
        if len(code) == 0:
            return
        tokens = Tokenizer.tokenize(code)
        grammar = Tokenizer.grammar_from_tokens(tokens)

        first, follow = first_follow.compute_first_follow(grammar)

        ll1_table, is_ll1 = ll1.build_ll1_table(grammar, first, follow)
        info = pprint(str(grammar), 'Gramatica:') + '\n\n'

        info += pprint(first, 'First:') + '\n\n'
        info += pprint(follow, 'Follow:') + '\n\n'
        info += pprint(str(is_ll1), 'Es LL1') + '\n\n'
        if is_ll1:
            info += pprint(ll1_table, 'Tabla ll1: ') + '\n\n'

            parsing_table = build_parsing_table(grammar, first, follow)
            parser = method_predicted_non_recursive(grammar, M=parsing_table)

            try:
                dfa = grammar.DFA()
                states = State.from_nfa(dfa, True)
                regex = regexp_from_automaton(states[1], grammar.terminals)
                info += pprint(str(True), 'Gramatica Regular: ') + '\n\n'
                info += pprint(regex, 'Expresion Regular Asociada: ') + '\n\n'
                try:
                    import pygraphviz as pgv
                    dot = states[0].graph()

                    (graph, ) = pydot.graph_from_dot_data(str(dot))
                    graph.set_label('Automata expresion Regular Asociada')
                    gr = pgv.AGraph().from_string(str(graph))
                    gr.layout()
                    gr.draw('graph.png')
                    self.image = QPixmap('graph.png')
                    self.lr_graph_label.setPixmap(self.image)
                    self.lr_graph_label.show()
                except:
                    info += 'No es posible mostrar el automata...Error' + '\n\n'

            except:
                info += pprint(str(False), 'Gramatica Regular: ') + '\n\n'

            if len(strings) > 0:
                for line in str.split(strings, '\n'):
                    if len(line) == 0:
                        continue
                    left_parse = self.run_pipeline(tokenize_input(line),
                                                   parser)
                    print('Left parser')
                    print(left_parse)
                    info += pprint(left_parse,
                                   f'Parse para cadena -> {line}:') + '\n\n'

        parser_lr1 = LR1Parser(grammar, verbose=True)
        parser_slr1 = SLR1Parser(grammar, verbose=True)

        if parser_slr1.is_slr1:
            info += 'La Gramatica es SLR(1):' + '\n\n'
            info += pprint(parser_slr1.action, 'Tabla de Actions:') + '\n\n'
            info += pprint(parser_slr1.goto, 'Tabla de Goto:') + '\n\n'
            info += self.full_run_pipeline(grammar, strings, parser_slr1)
            self.show_automaton(parser_slr1.automaton, 'Automata SLR1',
                                self.slr1_graph_label, 'slr.png')
        else:
            info += pprint(str(False), 'La Gramatica no es SLR(1):') + '\n\n'
            info += parser_slr1.error
            info += pprint(parser_slr1.action, 'Tabla de Actions:') + '\n\n'
            info += pprint(parser_slr1.goto, 'Tabla de Goto:') + '\n\n'

        if parser_lr1.is_lr1:
            info += 'La Gramatica es LR(1):' + '\n\n'
            info += pprint(parser_lr1.action, 'Tabla de Actions:') + '\n\n'
            info += pprint(parser_lr1.goto, 'Tabla de Goto:') + '\n\n'
            info += self.full_run_pipeline(grammar, strings, parser_lr1)
            self.show_automaton(parser_lr1.automaton, 'Automata LR1',
                                self.lr1_graph_label, 'lr.png')
        else:
            info += pprint(str(False), 'La Gramatica no es LR(1):') + '\n\n'
            info += parser_lr1.error
            info += pprint(parser_lr1.action, 'Tabla de Actions:') + '\n\n'
            info += pprint(parser_lr1.goto, 'Tabla de Goto:') + '\n\n'

        grammar_without_common_prefixes = deepcopy(grammar)
        rm_common_prefix(grammar_without_common_prefixes)
        grammar_without_immediate_left_recursion = deepcopy(grammar)
        rm_immediate_left_recursion(grammar_without_immediate_left_recursion)
        info += pprint(str(grammar_without_common_prefixes),
                       'Gramatica sin prefijos comunes:') + '\n\n'
        info += pprint(str(grammar_without_immediate_left_recursion),
                       'Gramatica sin recursion inmediata izquierda:') + '\n\n'

        self.all_info.setPlainText(info)
        self.all_info.setReadOnly(True)