Ejemplo n.º 1
0
 def _run_jobs(self):
     """
     Runs the control script with the selected json file
     """
     self.is_controlling = True
     with open(self.window.filename, "r", encoding='utf-8') as f:
         events = Event.schema().load(json.load(f), many=True)
         ctrlr = Controller(events, self.controller_terminate)
         iterations = int(self.spinbox.get())
         t = Thread(target=ctrlr.run, args=[iterations])
         t.start()
Ejemplo n.º 2
0
def simulate(arm, traj, tf, dt_dyn, dt_control=None, u_inj=None):
    """
    Inputs:
        arm: arm object
        traj: desired trajectory
        tf: desired final simulation time
        dt: desired dt for control
        u_inj: control injection
    """

    dynamics = Dynamics(arm, dt_dyn)
    # dynamics = Dynamics(arm, dt_dyn, noise_torsion=[1e-3,0], noise_bending=[1e-3,0,0,0])

    if dt_control is None:
        dt_control = dt_dyn
    else:
        dt_control = max(np.floor(dt_control / dt_dyn) * dt_dyn, dt_dyn)
    T = int(dt_control / dt_dyn)

    dyn_reduced = Dynamics(arm, dt_control, n=arm.state.n)
    controller = Controller(dyn_reduced)

    state_list = []
    control_list = []

    t_steps = int(np.floor(tf / dt_dyn))
    t_arr = np.linspace(0, tf, t_steps + 1)
    for i, t in enumerate(t_arr):
        print('Progress: {:.2f}%'.format(float(i) / (len(t_arr) - 1) * 100),
              end='\r')

        # mode = finiteStateMachine(y,wp)
        # mode = 'none'
        # mode = 'damping'
        mode = 'mpc'

        if i % T == 0:
            j = i // T
            if j not in u_inj:
                wp = traj[:, j]
                y = simulateMeasurements(arm)
                u = controller.controlStep(y, wp, mode)
            else:
                u = {}
                u['rot'] = u_inj[j]['rot']
                u['lat'] = u_inj[j]['lat']

        arm = dynamics.dynamicsStep(arm, u)

        state_list.append(copy.copy(arm.state))
        control_list.append(u)

    return state_list, control_list, t_arr
Ejemplo n.º 3
0
def main():
    """Main function."""
    # Create an instance of QApplication
    pycalc = QApplication(sys.argv)
    # Show the calculator's GUI
    view = GUI()
    view.show()

    # Create instances of the model and the controller
    Model = evaluateExpression
    Controller(model=Model, view=view)

    # Execute the calculator's main loop
    sys.exit(pycalc.exec_())
Ejemplo n.º 4
0
def est_final_params(gt_observations):

    # use dummy controller to run EM
    num_w, num_q = gt_observations.shape
    c = Controller(method=None, platform=None,
                   num_workers=num_w, num_questions=num_q)

    params,_ = c.run_em(gt_observations)

    
        
    d = params['difficulties']
    s = params['skills']
        
    parse.params_to_file('gold_params.csv',params)
    return d,s
Ejemplo n.º 5
0
    def Startup(self):
        # Importing takes sometime, therefore it will be done
        # while splash is being shown
        from gui.frame import Frame
        from control import Controller
        from project import Project

        self.main = Frame(None)
        self.control = Controller(self.main)

        self.fc = wx.FutureCall(1, self.ShowMain)
        wx.FutureCall(1, parse_comand_line)

        # Check for updates
        from threading import Thread
        p = Thread(target=utils.UpdateCheck, args=())
        p.start()
Ejemplo n.º 6
0
    def __init__(self, grid, astar, plan_and_drive):
        # other classes
        self.grid = grid
        self.astar = astar
        self.controller = Controller()

        # visual display
        self.fig, self.ax = plt.subplots()

        if plan_and_drive:
            self.display(False)
        else:
            self.display(True)

        self.l = 0.1
        self.wait = 0.01

        # threshold distance goal/waypoint
        self.threshold = 0.15
Ejemplo n.º 7
0
def main(screen):
    app_log = startLog(LOGFILE)
    screen.addstr(0, 0, 'Loading Nutmeg...')
    screen.refresh()

    with open('testuser-password', 'r') as passFile:
        PASSWORD = passFile.read().strip()
    HOMESERVER = 'lrizika.com'
    USERNAME = '******'
    ROOMNAME = '#test4:lrizika.com'
    app_log.info('Building Controller...')
    controller = Controller(screen,
                            HOMESERVER,
                            username=USERNAME,
                            password=PASSWORD)
    inputController = InputController(controller)
    controller.stateManager.joinRoom(ROOMNAME)

    inputController.listen()
Ejemplo n.º 8
0
def main():
    tf.compat.v1.disable_eager_execution()

    # dataset
    dset = Dataset(config)
    dset.build()
    config.vocab_size = len(dset.word2id)
    config.pos_size = len(dset.pos2id)
    config.ner_size = len(dset.ner2id)
    config.dec_start_id = dset.word2id["_GOO"]
    config.dec_end_id = dset.word2id["_EOS"]
    config.pad_id = dset.pad_id
    config.stop_words = dset.stop_words

    model = LatentBow(config)
    with tf.compat.v1.variable_scope(config.model_name):
        model.build()

    # controller
    controller = Controller(config)
    controller.train(model, dset)
Ejemplo n.º 9
0
 def setUp(self) -> None:
     self.controller = Controller()
     self.controller.click_on_rel_pos(
         self.controller.start_button_rel_coord)
Ejemplo n.º 10
0
    await websocket.send(json.dumps(web_config))


async def consumer_handler(websocket, path):
    logger.info("Client connected")
    await send_web_config(websocket)
    async for message in websocket:
        logger.info("Message received: {}".format(message))
        try:
            data = json.loads(message)
            controller.parse(data)
        except ValueError:
            logger.warning("Message could not be parsed")

__name__ = "start"
# logging
FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
logging.basicConfig(filename='app.log', filemode='a', format=FORMAT, level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("Application started")

# configuration
CONFIG_PATH = "config.json"
controller = Controller(CONFIG_PATH)
web_config = controller.get_webconfig()

# websocket
start_server = websockets.serve(consumer_handler, "0.0.0.0", 6789)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Ejemplo n.º 11
0
                        help='List of hosts')
    parser.add_argument('--clear',
                        required=False,
                        type=int,
                        help='Clear control backup file')

    args = parser.parse_args()

    if (args.clear == 1):
        # Remove control layer data
        try:
            os.remove(args.control)
        except:
            pass

    controller = Controller(args.control)

    hosts = []
    #hosts = [("172.17.0.2", 18861), ("172.17.0.3", 18861)]  # IP,PORT TUPLE
    for host in args.hosts:
        hosts.append((host, args.port))

    hasActiveHost = controller.generateNodes(hosts)
    if (not hasActiveHost):
        exit(0)

    k = Thread(target=t, args=(controller, ))
    k.start()

    print(f"Mounting {args.real} on {args.virtual}")
    FUSE(Passthrough(controller, args.real),
Ejemplo n.º 12
0
from threading import Thread
import os
import socket
from control import Controller
from time import sleep
ip = (([
    ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
    if not ip.startswith("127.")
] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close())
       for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) +
      ["no IP found"])[0]

app = Flask(__name__)
api = Api(app)
socketio = SocketIO(app, cors_allowed_origins="*")
controller = Controller()
x = 0
y = 0
connectedCount = 0
controller.Setup()


def control():
    print("is here")
    global x, y, controller
    while True:
        controller.set(x, y)
        sleep(0.01)


thread = Thread(target=control)
Ejemplo n.º 13
0
# Django specific settings
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")

# Ensure settings are read
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

from control import Controller

inst = Controller()
Ejemplo n.º 14
0
@author: Leon Bonde Larsen

This is a quick test of the algorithm developed to generate s-curves in a system
with varying setpoints. Most implementations are based on systems where the entire
curve can be calculated on beforehand, but this is not possible in a system where
the setpoint varies over time.

The actual ode implemented in C++ is an exact copy of the code running in this 
simulation.

Being just an internal test, the settings are placed in the init method on the
Controller class. The controller is based on the constant jerk principle leading
to linear accelerations and second order velocities.

In the current test, the initial velocity is -1m/s and the user setpoint is +2m/s.
What is seen in the plot is that the system first brakes with  ramp to velocity 0m/S
and then accelerates and decelerates to hit the 2m/s velocity.
'''
from matplotlib import pyplot as plt
from control import Controller

plt.figure(num=None, figsize=(10, 6), dpi=80, facecolor='w', edgecolor='k')
ctrl = Controller()
           
ctrl.simulate()

plt.plot(ctrl.time,ctrl.pos)
plt.plot(ctrl.time,ctrl.vel)
plt.plot(ctrl.time,ctrl.acc)
plt.legend(["position","velocity","acceleration"])
plt.show()
Ejemplo n.º 15
0
Archivo: core.py Proyecto: biyifang/NAS
x_test = x_test.astype('float32') / 255.
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)

dataset = [x_train, y_train, x_test, y_test]
'''

previous_acc = 0.0
total_reward = 0.0

with policy_sess.as_default():
    # create the Controller and build the internal policy network
    controller = Controller(policy_sess,
                            NUM_LAYERS,
                            state_space,
                            reg_param=REGULARIZATION,
                            exploration=EXPLORATION,
                            controller_cells=CONTROLLER_CELLS,
                            embedding_dim=EMBEDDING_DIM,
                            restore_controller=RESTORE_CONTROLLER)

# create the Network Manager
manager = CNNEnv(args,
                 epochs=MAX_EPOCHS,
                 child_batchsize=CHILD_BATCHSIZE,
                 clip_rewards=CLIP_REWARDS,
                 acc_beta=ACCURACY_BETA)

# get an initial random state space if controller needs to predict an
# action from the initial state
state = state_space.get_random_state_space(NUM_LAYERS)
print("Initial Random State : ", state_space.parse_state_space_list(state))
Ejemplo n.º 16
0
from control import Controller

main = Controller()
main.inicio()



Ejemplo n.º 17
0
def turn_on_spot(v, angle, motor, g=None, c=None):
    """
    Turn the robot or servo motor on the spot by the angle.
    :param v - the duty_cycle_sp at which the motor should travel at
    :param motor - either 'SERVO' or 'MOTOR'
    :param angle - If the angle is negative, it will turn CCW else CW.
    It sets the goal state of the robot or servo as the sum
    of its current heading (gyro.value()) and the angle.
    """

    L = io.motA
    R = io.motB
    servo = io.servo
    gyro = io.gyro
    col = io.col

    if angle > 0:
        direction = 1  # set the polairty switch for the wheels
    elif angle < 0:
        direction = -1
    else:  # 0 degrees = no work to be done
        return
    print(direction)

    # -------------- ROBOT ---------------------
    if motor == 'ROBOT':
        desired_angle = gyro.value() + angle
        logging.info(
            'Turning the robot to desired {} degrees'.format(desired_angle))
        turn_control = Controller(.01, 0, 0, desired_angle, history=10)

        while True:

            signal, err = turn_control.control_signal(gyro.value())

            signal, err = turn_control.control_signal(gyro.value())

            if abs(err) <= 5 or io.btn.backspace:  # tolerance
                L.stop()
                R.stop()
                L.duty_cycle_sp = v
                R.duty_cycle_sp = v
                return

            else:
                # if too small or too large, just use the default v
                if abs(v + signal) >= 100 or abs(v + signal) <= 20: signal = 0
                L.run_direct(duty_cycle_sp=direction * abs(v + signal))
                R.run_direct(duty_cycle_sp=-1 * direction * abs(v + signal))

            logging.info(
                'GYRO = {},\tcontrol = {},\t err={}, \tL = {}, \tR = {}'.
                format(gyro.value(), signal, err, L.duty_cycle_sp,
                       R.duty_cycle_sp))
            try:
                g.set_val(gyro.value())
                c.set_val(col.value())
            except AttributeError:
                pass

    # -------------- SERVO ---------------------
    elif motor == 'SERVO':
        turn_control = Controller(.001,
                                  0,
                                  .5,
                                  servo.position + angle,
                                  history=10)
        # servo.duty_cycle_sp = servo.duty_cycle_sp * direction
        ev3.Sound.speak('Turning servo {} degrees'.format(angle)).wait()
        logging.info('Turning servo {} degrees'.format(angle))

        while True:

            signal, err = turn_control.control_signal(servo.position)
            if abs(err) <= 4 or io.btn.backspace:  # tolerance
                servo.stop()
                servo.speed_sp = v
                servo.duty_cycle_sp = servo.duty_cycle_sp * \
                    direction  # return to the original number
                return

            if (v + abs(signal) >= 100): signal = 0
            signal = (direction) * (v + abs(signal))
            servo.run_direct(duty_cycle_sp=signal)
            logging.info(
                'POS = {},\tcontrol = {},\t err={}, \tspd = {}'.format(
                    servo.position, signal, err, servo.speed_sp))
            try:
                g.set_val(gyro.value())
            except AttributeError:
                pass
    else:
        raise NameError('motor should be "ROBOT" or "SERVO"')
Ejemplo n.º 18
0
def main():
    con = Controller("sample.cfg", "True")
    con.run()
Ejemplo n.º 19
0
                                                      gold.get_difficulties()]),
                    times=first_array_or_true([time_in, gold.get_times()]),
                    skills=first_array_or_true([skill_in, gold.get_skills()]),
                    thetas=gt_thetas)


        # run
        for p in policies:
            if run_once and p['type'] in ['greedy','greedy_reverse','accgain','accgain_reverse'] and p['name'] in policies_run:
                continue

            np.random.seed(rint)
            platform.reset()
            controller = Controller(policy=p,
                                    platform=platform,
                                    num_workers=platform.num_workers,
                                    num_questions=platform.num_questions,
                                    max_rounds=max_rounds_in)

                                    
            if 'offline' in p:
                r = controller.run_offline()
            else:
                r = controller.run()

            policies_run.add(p['name'])
            
        

            
            # save platform settings (don't have to do this every run, but we do)
Ejemplo n.º 20
0
import warnings
warnings.simplefilter('ignore')

import strategy
from control import Controller

agent = strategy.EdgeDetectionAgent(10)
# agent = strategy.SiameseNetAgent(10)
controller = Controller(agent, data_dir=None)
controller.run()
Ejemplo n.º 21
0

class SelectSoundScreen(Screen):
    def __init__(self, sensor_controller, **kwargs):
        super().__init__(**kwargs)
        self.controller = sensor_controller


class ThereminGUI(App):
    def __init__(self, controller, **kwargs):
        super().__init__(**kwargs)
        self.sensor_controller = controller

    def build(self):
        sm = ScreenManager()
        sm.add_widget(MenuScreen(self.sensor_controller, name='menu'))
        sm.add_widget(TuneScreen(self.sensor_controller, name='tune'))
        sm.add_widget(LoopScreen(self.sensor_controller, name='loop'))
        sm.add_widget(SelectSoundScreen(self.sensor_controller, name='select_sound'))
        sm.add_widget(OptionsScreen(self.sensor_controller, name='options'))
        return sm


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Usage: python3 gui.py host')
    host = sys.argv[1]
    controller = Controller(host=host)
    thread = controller.main()
    ThereminGUI(controller).run()
Ejemplo n.º 22
0
def train(dataset1, dataset2, initial_state, if_restore):
    total_reward = 0.0
    with policy_sess.as_default():
        # create the Controller and build the internal policy network
        controller = Controller(policy_sess,
                                NUM_LAYERS,
                                state_space,
                                reg_param=REGULARIZATION,
                                exploration=EXPLORATION,
                                controller_cells=CONTROLLER_CELLS,
                                embedding_dim=EMBEDDING_DIM,
                                restore_controller=if_restore)
    # clear the previous files
    controller.remove_files()
    # create the Network Manager
    manager1 = NetworkManager(dataset1,
                              epochs=MAX_EPOCHS,
                              child_batchsize=CHILD_BATCHSIZE,
                              clip_rewards=CLIP_REWARDS,
                              acc_beta=ACCURACY_BETA)
    manager2 = NetworkManager(dataset2,
                              epochs=MAX_EPOCHS,
                              child_batchsize=CHILD_BATCHSIZE,
                              clip_rewards=CLIP_REWARDS,
                              acc_beta=ACCURACY_BETA)

    result_reward = []
    result_total_reward = []
    result_acc = []
    result_moving_acc = []
    result_explore_acc = []
    result_exploit_acc = []

    flag = None
    manager = None
    for trial in range(MAX_TRIALS):
        print("\nTrial %d:" % (trial + 1))
        if 2 * trial < MAX_TRIALS:
            manager = manager1
            if trial % 2 == 0:
                actions = state_space.get_local_state_space_add(
                    int(trial / 2), initial_state)
            else:
                actions = state_space.get_local_state_space(
                    int(trial / 2), initial_state)
        else:
            manager = manager2
            with policy_sess.as_default():
                K.set_session(policy_sess)
                flag, actions = controller.get_action(
                    state)  # get an action for the previous state

        # print the action probabilities
        # state_space.print_actions(actions)
        print("Actions : ", state_space.parse_state_space_list(actions))
        # build a model, train and get reward and accuracy from the network manager
        reward, previous_acc, moving_acc = manager.get_rewards(
            state_space.parse_state_space_list(actions))
        print("Rewards : ", reward)
        print("Accuracy : ", previous_acc)
        print("Movingacc :", moving_acc)

        with policy_sess.as_default():
            K.set_session(policy_sess)

            total_reward += reward
            print("Total reward : ", total_reward)

            # actions and states are equivalent, save the state and reward
            state = actions
            controller.store_rollout(state, reward)

            # train the controller on the saved state and the discounted rewards
            loss = controller.train_step()
            print("Controller loss : %0.6f" % (loss))

            # write the results of this trial into a file
            with open('train_history.csv', mode='a+') as f:
                data = [previous_acc, reward]
                data.extend(state_space.parse_state_space_list(state))
                writer = csv.writer(f)
                writer.writerow(data)
        print()
        result_reward.append(reward)
        result_total_reward.append(total_reward)
        result_acc.append(previous_acc)
        result_moving_acc.append(moving_acc)
        if 2 * trial >= MAX_TRIALS:
            if not flag:
                result_explore_acc.append(previous_acc)
            else:
                result_exploit_acc.append(previous_acc)

    print("Rewards : ", result_reward)
    print("Total Rewards :", result_total_reward)
    print("Accuracy : ", result_acc)
    print("Moving acc : ", result_moving_acc)
    print("Explore acc :", result_explore_acc)
    print("Exploit acc : ", result_exploit_acc)
Ejemplo n.º 23
0
    'depth': bod_depth,
    'height': bod_height,
    'cm': body_cm
}
wheel_params = {
    'mass': wheel_mass,
    'radius': wheel_rad,
    'height': wheel_height,
    'cm': wheel_cms,
    'axis': wheel_axes
}

earth_rad = 6371  #km
sat_alt = earth_rad + 300

vol_pos = (-6, 0)
sat_pos0 = (6, 0)
#number of iterations that the controller's cpu can run
att_update = 0.01
time_sf = 10
w0 = [0, 0, 0]
q0 = [1, 0, 0, 0]
rate = 18  #frames/calculations per second
controller = Controller(rate, body_params, q0=[1, 0, 0, 0], w0=[0, 0, 0])
anim_obj = Animate(controller, time_sf, real=False)
#plt.waitforbuttonpress()
#anim_obj.cid = anim_obj.orbit_fig.canvas.mpl_connect('button_press_event', anim_obj.onclick)
#anim_obj.get_point()
my_anim = anim_obj.make_animation()
plt.show()
Ejemplo n.º 24
0
import tkinter as tk
import gui.FirstInteface as FI
import control.Controller as Con

if __name__ == '__main__':
    root = tk.Tk()
    root.title("الحسابات")
    FI.MainInterface(root, Con.Controller())
    root.mainloop()
Ejemplo n.º 25
0
import RPi.GPIO as GPIO
import sensor
import time, qwiic_vl53l1x
from control import Controller

c = Controller()

sensor.get_sensors()

pitch = sensor.get_pitch(c)
volume = sensor.get_volume(c)


while True:
    print(sensor.get_pitch(c))
    print(sensor.get_volume(c))
    time.sleep(2)
Ejemplo n.º 26
0
import logging
from db import SQLQuery
from control import Controller
from telegram_bot import TelegramBot

from config import TelegramConfig, DBConfig

logging.basicConfig(filename='log',
                    format='%(asctime)s - %(message)s',
                    level=logging.INFO)

if __name__ == '__main__':
    db = SQLQuery(DBConfig)
    controller = Controller(db)
    bot = TelegramBot(TelegramConfig, controller)
    bot.main()
Ejemplo n.º 27
0
 def __init__(self):
     self.input = Controller()
     self.world = World(debug=True)
Ejemplo n.º 28
0
args = parser.parse_args()

logger.critical("hoge")

camera = PiCamera()  # PiCamera object
camera.resolution = (640, 480)
camera.framerate = 30
window_size = 600
buffer = PiRGBArray(camera)  # PiRGBArray object
num_green = 5
time.sleep(0.1)  # 100ms

running = True
con = serial.Serial("/dev/ttyACM0", 9600)
con.write(b"I")
controller = Controller(num_green, window_size)
while running:
    for stream in camera.capture_continuous(buffer,
                                            format="bgr",
                                            use_video_port=True):

        frame = stream.array
        frame = imutils.resize(frame, width=window_size)
        blurred = cv2.GaussianBlur(frame, (11, 11), 0)
        hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
        hsv = hsv[:-100, :, :]
        if (controller.key == "green"):
            centre_info = find_green(hsv)
        else:
            centre_info = find_red(hsv)
        controller.control(con, centre_info)
Ejemplo n.º 29
0
import sys
from control import Controller
from PyQt5.QtWidgets import QApplication

if __name__ == "__main__":
    app = QApplication(sys.argv)
    control = Controller()
    app.exec_()