Ejemplo n.º 1
0
    def __init__(self, engine):
        """Constructor"""
        System.__init__(self, engine)
        ogre.FrameListener.__init__(self)
        ogre.WindowEventListener.__init__(self)
        OIS.KeyListener.__init__(self)
        OIS.MouseListener.__init__(self)
        OIS.JoyStickListener.__init__(self)

        self.handlers = [dict() for x in range(InputEvent.NUM)]
        self.mouse_handlers = [dict() for x in range(MouseEvent.NUM)]
        self.joy_handlers = [dict() for x in range(JoyEvent.NUM)]
        self.key_states = {}
        self.keys_down = list()
        self.mouse_buttons_down = {}
        self.mouse_down_pos = {}
        self.mouse_down_over = {}
        self.mouse_down_modifiers = {}
        self.input_locks = {}
        for mb in MouseButton.LIST:
            self.mouse_buttons_down[mb] = False
            self.mouse_down_pos[mb] = None
            self.mouse_down_over[mb] = None
            self.mouse_down_modifiers[mb] = [False for x in range(Modifier.NUM)]
            self.input_locks[mb] = InputLock()
        self.mouse_state = None

        #box selection
        #self.selection_dd_context = self.engine.debugDrawSystem.getContext()
        #self.boxSelection = None
        #self.maintainDDContext = self.engine.debugDrawSystem.getContext()
        self.translation_to_apply = vector3(0,0,0)

        self.translation_to_apply_time_left = 0
Ejemplo n.º 2
0
def menu(arguments):
    if arguments['list']:
        if arguments['--YAML'] or arguments['--JSON']:
            where = dict(name=arguments['<name>']) if arguments['<name>'] else dict()
            systems = System.list(**where)
            common.dump(systems, toyaml=arguments['--YAML'], tojson=arguments['--JSON'], entry=lambda item: item.__dict__)

        else:
            _system_list_table(arguments)

    elif system_execute(arguments):
        pass

    else:
        try:
            if arguments['create']:
                System.create(**_system_create_kwargs(arguments))

            elif arguments['read']:
                system_read(arguments)

            elif arguments['set']:
                system_set(arguments)

            elif arguments['delete']:
                System(arguments['<name>']).delete()

            elif arguments['reset']:
                system_reset(arguments)

        except NameError as exc:
            print(PACKAGE_NAME, 'Error!', exc)
            sys.exit(1)
Ejemplo n.º 3
0
    def __init__(self):
        global _requests

        self.camip = "sonycam.msgroup.ucla.edu"
        self.ourip = socket.gethostbyaddr(socket.gethostname())[-1][0]
        self.port = 9218
        self.camtool = "./camctrl"
        self.pan=0
        self.tilt=0
        self.zoom=0
        self.setCam()
        
        print "Start parsing xml file"
        espmlFile = 'sonyCamSystem.xml'
        espmlDocObject = espml.parse(espmlFile)
        systemElement = espmlDocObject.getSystem()
        systemElement.setId('http://'+str(self.ourip)+':'+self.port)
        espmlDocObject.export(file(espmlFile, 'w'), 0)
        
        System.__init__(self, self.port, "http://128.97.93.5:1718/", "sonyCamSystem.xml")
        print "Registered system"
        

        #the next call is blocking!
        print "starting..."
        self.start()
        
        raw_input("Press a key when done")
Ejemplo n.º 4
0
def main():
    # Solar system data comes from
    #   http://hyperphysics.phy-astr.gsu.edu/hbase/solar/soldata2.html
    sun = Body(1.98892e30, 0, 0, 0, 0, 15, 1, 1, 0)
    mercury = Body(.06 * EM, -.3871 * AU, 0, 0, 47890, 3, 1, .4, 0)
    venus = Body(.82 * EM, -.7233 * AU, 0, 0, 35040, 6, 0, .6, .2)
    earth = Body(1.0 * EM, -1.0 * AU, 0, 0, 29790, 7, 0, .4, 1)
    mars = Body(.11 * EM, -1.524 * AU, 0, 0, 24140, 4, .8, .2, 0)
    
    solar_system = System([sun, mercury, venus, earth, mars])

    set_clear_color(0, 0, 0)    # black background
    enable_smoothing()
    
    while not window_closed():
        clear()

        # Draw the system in its current state.   
        solar_system.draw(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, PIXELS_PER_METER)

        # Update the system for its next state.
        solar_system.update(TIMESTEP * TIME_SCALE)

        # Draw the frame and take a brief nap.
        request_redraw()
        sleep(TIMESTEP)
Ejemplo n.º 5
0
class BRTest(unittest.TestCase):
    def showMsg(self, msg):
        print "[%s/%s/%s] %s" % (self.testname, self.testinstance,
                                 datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                 msg)
    def setUp(self):
        if os.getenv("REUSE_BUILD"):
            self.builddir = os.getenv("REUSE_BUILD").rstrip("/")
            skip_build = True
        else:
            skip_build = False
            b = subprocess.check_output(["mktemp", "-d", "buildroot.XXXXX"],
                                        cwd=configtest.builddir)
            b = b.strip()
            self.builddir = os.path.join(configtest.builddir, b)
        self.testname = self.__class__.__name__
        self.testinstance = os.path.basename(self.builddir)
        self.buildlog = self.builddir + "-build.log"
        self.runlog = self.builddir + "-run.log"
        self.s = None
        self.showMsg("Starting")
        self.b = Builder(self.__class__.config, self.builddir, self.buildlog)
        if not skip_build:
            self.showMsg("Building")
            self.b.build()
            self.showMsg("Building done")
        self.s = System(self.runlog)

    def tearDown(self):
        self.showMsg("Cleaning up")
        if self.s:
            self.s.stop()
        if self.b and os.getenv("KEEP_BUILD"):
            self.b.delete()
Ejemplo n.º 6
0
class BaseTest(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(BaseTest, self).__init__(*args, **kwargs)
        self.auto_power_on = True

    def setUp(self):
        obc_com = config['OBC_COM']
        sys_bus_com = config['SYS_BUS_COM']
        payload_bus_com = config['PAYLOAD_BUS_COM']
        use_single_bus = config['SINGLE_BUS']
        gpio_com = config['GPIO_COM']

        self.gpio = Pins(gpio_com)

        extensions.set_up(test_id=self.id())

        self.system = System(obc_com, sys_bus_com, payload_bus_com, use_single_bus, self.gpio, self.auto_power_on)

    def tearDown(self):
        self.system.close()
        self.gpio.close()
        extensions.tear_down(test_id=self.id())

    def power_on_obc(self):
        self.system.obc.power_on()

    def power_on_and_wait(self):
        self.power_on_obc()
        self.system.obc.wait_to_start()
Ejemplo n.º 7
0
    def __init__(self):
        global _requests

        System.__init__(self, 8081, "http://128.97.93.154:8080/", "sos_system.xml")
        # start the SOAP server
        
        self.sossrvClient = sossrv_tools.SossrvClient()

        _requests = {'field_getCurrent': {},
                     'field_average': {},
                     'sensor_getCurrentValue': {},
                     'sensor_getAverageValue': {}
                     }

        self.sensorModule = SensorModule()
        self.sossrvClient.register_module(self.sensorModule)
        # connect to the sossrv application
        self.sossrvClient.connect()

        SocketServer.TCPServer.__init__(self, ('128.97.93.154', 8082) , ESPRequestHandler)
        esphttpserver = thread.start_new_thread(self.serve_forever, ())

        #the next call is blocking!
        print "starting..."
        self.start()
        
        raw_input("Press a key when done")
Ejemplo n.º 8
0
 def set_screen(target, on=True):
     log = logging.getLogger('Screen')
     if not on:
         log.info('Setting screen OFF')
         System.sleep(target)
         return
     log.info('Setting screen ON')
     System.wakeup(target)
Ejemplo n.º 9
0
	def startup(self, verbosity):
		'''Initialisation for the objects that have variable startup behaviour'''
		self.myInfoDisplay = infodisplay.InfoDisplay()
#		self.myKey = keyboardpoller.KeyboardPoller()
#		self.myKey.start()
		try:
			if keys.board == 'emulator':
				import gpio_emulator
				import mpc_emulator
				self.myGpio = gpio_emulator.Gpio()
				self.myMpc = mpc_emulator.Mpc()
				host = 'dummy host'
				self.programmename = 'dummy prog\nTest\nSecond row'
			if keys.board == 'lcd':
				host = 'rotary host'
				import rotary
				self.myGpio = rotary.Rotary()
				self.myVol = rotary.Rotary(1)
				self.myMpc = mpc2.Mpc()
				print 'mpc has been setup'
#				count = self.myMpc.podcounter()
				self.mySystem = System()
				host = self.mySystem.return_hostname()
				print 'Hostname:', host
				self.programmename = self.myMpc.progname()
				print 'Prog:', self.programmename
#				remaining = self.myMpc.check_time_left()
			else:
				from mpc2 import Mpc
				import gpio
				self.myGpio = gpio.Gpio()
				self.myMpc = Mpc(False, True)		# Test mode, podmode
				count = self.myMpc.podcounter()
				self.mySystem = System()
				host = self.mySystem.return_hostname()
				self.programmename = self.myMpc.progname()
				remaining = self.myMpc.check_time_left()
		except:
			self.cleanup('Failed to start gpio')
#		self.myInfoDisplay.writerow(0,host)
#		self.myInfoDisplay.update_display()
		self.myInfoDisplay.prog = self.programmename
		self.myInfoDisplay.start()
		time.sleep(2)
		self.myInfoDisplay.prog = self.myMpc.progname()
		self.ending = False
		self.t = threading.Timer(AUDIOTIMEOUT, self.audiofunc)
		self.t.start()
		self.t.name = 'audiot'
		print threading.enumerate()		# helps debug
		print 'Thread count: ', threading.active_count()
#		self.check_threads()
		if False:								# set to true for testing
			self.cleanup('Forced cleanup')
		self.dt = threading.Timer(DEBUGTIMEOUT, self.debugfunc)
#		self.dt.start()
		self.dt.name = 'debugt'
Ejemplo n.º 10
0
    def __init__(self):
        global _requests

        System.__init__(self, 7082, "128.97.93.5:1817", "sensorbase_system.xml")

        #the next call is blocking!
        print "starting..."
        self.start()
        
        raw_input("Press a key when done")
Ejemplo n.º 11
0
    def __init__(self):
        global _requests

        System.__init__(self, 7081, "http://128.97.93.154:8080/", "soundscape_system.xml")

        #the next call is blocking!
        print "starting..."
        self.start()
        
        raw_input("Press a key when done")
Ejemplo n.º 12
0
def qa_linker():
    import time
    from gnuradio import window
    from system import System
    from signal_psk31 import PSK31Signal

    def mag(c):
        """Magnitude of complex number."""
        return (c*c.conjugate()).real

    src = gr.wavfile_source("../example.WAV", False)
    samp_rate = 44100
    tb = gr.top_block()
    system = System(tb, src, samp_rate, throttle=False, src_is_float=True,
                    center_freq=0)
    linker = Linker(1000, 80, samp_rate)
    snk = gr.null_sink(gr.sizeof_gr_complex)
    system.connect(system.out, linker, snk)
    system.refresh()
    system.start()
    time.sleep(5)
    system.stop()
    data = linker.probe.level()
    print(data[:10])
    print(linker.samp_rate)
    plot_fft([mag(x) for x in data], linker.samp_rate)
Ejemplo n.º 13
0
class Alive(object):

    def __init__(self):

        self.system = System()
        logging.info('Alive Initialization Succeeded!')

    def data(self):

        cpu = self.system.cpu()
        memory = self.system.memory()
        message = "Cpu %s / Memory %s" % (cpu, memory)
        logging.info(message)
Ejemplo n.º 14
0
    def __init__(self):
        global _requests

        print "Start parsing xml file"
        System.__init__(self, 8081, "http://127.0.0.1:8080/", "iTunesSystem.xml")
        print "Registered system"
        

        #the next call is blocking!
        print "starting..."
        self.start()
        
        raw_input("Press a key when done")
Ejemplo n.º 15
0
    def __init__(self):
        global _requests

        print "Start parsing xml file"
        System.__init__(self, 9181, "http://128.97.93.154:8080/", "beachCamSystem.xml")
        print "Registered system"
        

        #the next call is blocking!
        print "starting..."
        self.start()
        
        raw_input("Press a key when done")
Ejemplo n.º 16
0
 def test_next(self):
     rules = [
         Rule("A", 0, 1, True, "B"),
         Rule("B", 0, 1, False, "A"),
         Rule("C", 0, 1, False, "B"),
         Rule("A", 1, 1, False, "C"),
         Rule("B", 1, 1, True, "B"),
         Rule("C", 1, 1, True, "HALT"),
     ]
     m = Machine(rules)
     t = Tape()
     s = System(m, t)
     s.next()
     self.assertEqual(s.steps, 1)
Ejemplo n.º 17
0
 def test_iterate_until_halt_max(self):
     rules = [
         Rule("A", 0, 1, True, "B"),
         Rule("B", 0, 1, False, "A"),
         Rule("C", 0, 1, False, "B"),
         Rule("A", 1, 1, False, "C"),
         Rule("B", 1, 1, True, "B"),
         Rule("C", 1, 1, True, "HALT"),
     ]
     m = Machine(rules)
     t = Tape()
     s = System(m, t)
     with self.assertRaises(DidNotHalt):
         s.iterate_until_halt(max_steps=10)
     self.assertNotEqual(s.machine.state, "HALT")
Ejemplo n.º 18
0
def main():

    # load in the images for all the planets
    # like hitting ctrl+r and loading your blitz
    suni = load_image("sun.png")
    merci = load_image("mercury.gif")
    venusi = load_image("venus.gif")
    earthi = load_image("earth.png")
    marsi = load_image("mars.png")

    # initialize all the planets as an object
    # hope that the values are all correct
    sun = Body(1.98892e30, 0, 0, 0, 0, 12, 1, 1, 0,suni,17,17,0,17,17)
    mercury = Body(.06*EM,0,.3871*AU,47890,0,3,1,0,0,merci,8,8,.2,16,16)
    venus = Body(.82*EM,0,-.7233*AU,-35040,0,8,0,1,0,venusi,10,9,.3,20,18)
    earth = Body(EM,AU,0,0,-29790,6,0,0,1,earthi,13,13,.4,26,26)
    mars = Body(.11*EM,-1.524*AU,0,0,24140,4,0,1,1,marsi,10,10,.3,20,20)

    listp = [sun,mercury,venus,earth,mars]

    # put em in a list, for safekeeping
    # as of now, the planets are still sleeping
    solar = System(listp)

    # kill the backlights, set up the stage,
    # draw things inside the page
    set_clear_color(0, 0, 0)
    enable_smoothing()
    player = Spaceship(3*WINDOW_HEIGHT/4,3*WINDOW_HEIGHT/4)


    while not window_closed():

        # draw the spaceship yo
        clear()
        player.spaceshipupdate()
        player.draw()


        # Draw the system in its current state.
        solar.draw(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, PIXELS_PER_METER)

        # Update the system for its next state.
        solar.update(SEC_PER_FRAME)

        # Draw the frame and take a brief nap.
        request_redraw()
        sleep(TIMESTEP)
Ejemplo n.º 19
0
    def __init__(self):
        global _requests

        print "Start parsing xml file"
        System.__init__(self, 9081, "http://128.97.93.154:8080/", "weatherSystem.xml")
        print "Registered system"
        
        # start the SOAP server
        
        SocketServer.TCPServer.__init__(self, ('128.97.93.154', 9082) , ESPRequestHandler)
        esphttpserver = thread.start_new_thread(self.serve_forever, ())

        #the next call is blocking!
        print "starting..."
        self.start()
        
        raw_input("Press a key when done")
Ejemplo n.º 20
0
 def test_get_state_tape_contents_and_index(self):
     rules = [
         Rule("A", 0, 1, True, "B"),
         Rule("B", 0, 1, False, "A"),
         Rule("C", 0, 1, False, "B"),
         Rule("A", 1, 1, False, "C"),
         Rule("B", 1, 1, True, "B"),
         Rule("C", 1, 1, True, "HALT"),
     ]
     m = Machine(rules)
     t = Tape()
     s = System(m, t)
     s.next()
     state, contents, index = s.get_state_tape_contents_and_head_index()
     self.assertEqual(state, "B")
     self.assertEqual(contents, [1, 0])
     self.assertEqual(index, 1)
Ejemplo n.º 21
0
 def test_iterate_until_halt(self):
     rules = [
         Rule("A", 0, 1, True, "B"),
         Rule("B", 0, 1, False, "A"),
         Rule("C", 0, 1, False, "B"),
         Rule("A", 1, 1, False, "C"),
         Rule("B", 1, 1, True, "B"),
         Rule("C", 1, 1, True, "HALT"),
     ]
     m = Machine(rules)
     t = Tape()
     s = System(m, t)
     steps = s.iterate_until_halt()
     self.assertEqual(steps, 14)
     state, contents, index = s.get_state_tape_contents_and_head_index()
     self.assertEqual(state, "HALT")
     self.assertEqual(contents, 6 * [1])
     self.assertEqual(index, 4)
Ejemplo n.º 22
0
def main():
    earth = Body(5.9736e24, 0, 0, 0, 0, 24, 0, 0, 1)            # blue earth
    moon = Body(7.3477e22, 3.84403e8, 0, 0, 1022, 4, 1, 1, 1)   # white moon
    earth_moon = System([earth, moon])
    
    set_clear_color(0, 0, 0)    # black background
    enable_smoothing()

    while not window_closed(): 
        clear()
        
        # Draw the system in its current state.
        earth_moon.draw(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, PIXELS_PER_METER)
    
        # Update the system for its next state.
        earth_moon.update(TIMESTEP * TIME_SCALE)
    
        # Draw the frame and take a brief nap.
        request_redraw()
        sleep(TIMESTEP)
Ejemplo n.º 23
0
    def setUp(self):
        obc_com = config['OBC_COM']
        sys_bus_com = config['SYS_BUS_COM']
        payload_bus_com = config['PAYLOAD_BUS_COM']
        use_single_bus = config['SINGLE_BUS']
        gpio_com = config['GPIO_COM']

        self.gpio = Pins(gpio_com)

        extensions.set_up(test_id=self.id())

        self.system = System(obc_com, sys_bus_com, payload_bus_com, use_single_bus, self.gpio, self.auto_power_on)
Ejemplo n.º 24
0
def main():
    # initialize system
    system = System.getInstance()
    
    # parse commandline
    options = parseCommandLine()
    if options is None:
        sys.exit(1)
    
    # initialize and run PyNode
    node = PyNode(options)
    node.run()
class Signal():
	def __init__(self,fc_p,fc_v,fc_a,dt=1/30.0):
		s = control.tf([1.0,0.0],[1.0])
		self.pos = System( 1 ,dt=dt)
		self.vel = System( s/(1+s/(fc_v*2.0*math.pi)) ,dt=dt)
		self.acc = System( (s/(1+s/(fc_a*2.0*math.pi)) )**2 ,dt=dt)

	def append(self,s,t):
		self.p = self.pos.output(s,t)
		self.v = self.vel.output(s,t)
		self.a = self.acc.output(s,t)

		self.pos.next_state()
		self.vel.next_state()
		self.acc.next_state()

	def get(self):
		return [self.p, self.v, self.a]
Ejemplo n.º 26
0
	def runTest( self ):
		context = Context( 'root' )
		context.start()

		listener = TestListener()
		listener.context = context

		node = System( 'system', listener )
		node.addListener( listener )

		context.queue( Event( System.EVENT_START ), node )

#		from message import *
		s = 'INVITE sip:[email protected] SIP/2.0\r\n' \
'Call-ID: abcde\r\nContent-Length: 136\r\nContent-Type: application/simple-message-summary\r\n\r\nMessages-Waiting: yes\r\nMessage-Account: sip:[email protected]\r\nvoice-message: 1/5(2/4)\r\nfax-message: 0/1\r\ntext-message: 3/7\r\n' \
'\r\n'
		message = Request( s )
		e = MessageEvent( MessageEvent.EVENT_RX, message )
		context.queue( e, node )

		#context.queue( Event( System.EVENT_STOP ), node )
		context.stop()
Ejemplo n.º 27
0
    def prepare(self):
        """
            prepare new root system suitable to create an initrd from it
        """
        self.__load_boot_xml_description()
        boot_image_name = self.boot_xml_state.xml_data.get_name()

        self.__import_system_description_elements()

        log.info('Preparing boot image')
        system = System(
            xml_state=self.boot_xml_state,
            root_dir=self.boot_root_directory,
            allow_existing=True
        )
        manager = system.setup_repositories()
        system.install_bootstrap(
            manager
        )
        system.install_system(
            manager
        )

        profile = Profile(self.boot_xml_state)
        profile.add('kiwi_initrdname', boot_image_name)

        defaults = Defaults()
        defaults.to_profile(profile)

        setup = SystemSetup(
            self.boot_xml_state,
            self.__boot_description_directory(),
            self.boot_root_directory
        )
        setup.import_shell_environment(profile)
        setup.import_description()
        setup.import_overlay_files(
            follow_links=True
        )
        setup.call_config_script()

        system.pinch_system(
            manager=manager, force=True
        )

        setup.call_image_script()
        setup.create_init_link_from_linuxrc()
Ejemplo n.º 28
0
def run_simulation(repo_path, gen_max):
    logger.info("Running simulation with: REPO_PATH={}, GENERATION_MAX={}"
                .format(repo_path, gen_max))
    
    # Init base system
    sys=System(repo_path=repo_path)
    sys.setLowestVersions()
    sys.dump()
    
    # Init goal (latest version)
    goal=System.latestVersion(sys)
    goal.dump()
    
    # Init population
    pop=Population(DEFAULT_POP_SIZE, sys, goal)
    
    # Init dataframe for storing results
    ## TODO

    logger.info("Starting simulation...")
    
    for i in range(gen_max):
        '''
        For each generation we need to go through all the genomes
        and evolve them (mutate/crossover/rebel) and test. The more
        successful a genome is (more programs installed/tests), the
        more likely it is to create offspring for the next generation
        '''
        
        logger.info("Generation #{}".format(i))
        
        for genome in pop.getGenomes():
            # TODO some evaluation, score, record
            logger.info("\t{}".format(genome))
        
        #Check if objective has been met yet
        if pop.isGoalMet():
            # TODO
            logger.info("Goal configuration has been found!")
            break
        
        pop=pop.nextGeneration()
        
        logger.debug("System state at end of this generation")
        pop.sys.dump()
    
    #TODO do some final reporting
    logger.info("Final configuration after {} generations looks like:".format(i))
    pop.sys.dump()
Ejemplo n.º 29
0
 def reset(self):
     self.system = System.getInstance()
     self.config = AttributeDict()
     
     self.resources = [ ]
     self.delayedActions = set()
     
     now = datetime.now()
     self.updateConfig({
         'date': now, 
         'pynode.version': version(),
         'pynode.longVersion': longVersion(),
         'pynode.backup.path': '/tmp/pynode/backup',
         'pynode.backup.prefix': now.strftime("%Y%m%d%H%M%S"),
     })
Ejemplo n.º 30
0
class SystemUpdateTask(CliTask):
    """
        Implements update and maintenance of root systems
    """
    def process(self):
        self.manual = Help()
        if self.__help():
            return

        Privileges.check_for_root_permissions()

        self.load_xml_description(
            self.command_args['--root']
        )

        package_requests = False
        if self.command_args['--add-package']:
            package_requests = True
        if self.command_args['--delete-package']:
            package_requests = True

        log.info('Updating system')
        self.system = System(
            self.xml_state,
            self.command_args['--root'],
            allow_existing=True
        )
        manager = self.system.setup_repositories()

        if not package_requests:
            self.system.update_system(manager)
        else:
            if self.command_args['--add-package']:
                self.system.install_packages(
                    manager, self.command_args['--add-package']
                )
            if self.command_args['--delete-package']:
                self.system.delete_packages(
                    manager, self.command_args['--delete-package']
                )

    def __help(self):
        if self.command_args['help']:
            self.manual.show('kiwi::system::update')
        else:
            return False
        return self.manual
Ejemplo n.º 31
0
 def __init__(self,markers,ship,name):
     self.ship = ship
     # The markers tracked by the system can change over time, so save the original
     self.markers = list(markers)
     self.system = System(markers,ship.player,name)
Ejemplo n.º 32
0
def exercise2():
    """ Main function to run for Exercise 2.

    Parameters
    ----------
        None

    Returns
    -------
        None
    """

    # Define and Setup your pendulum model here
    # Check PendulumSystem.py for more details on Pendulum class
    pendulum_params = PendulumParameters()  # Instantiate pendulum parameters
    pendulum_params.L = 0.5  # To change the default length of the pendulum
    pendulum_params.m = 1.  # To change the default mass of the pendulum
    pendulum = PendulumSystem(pendulum_params)  # Instantiate Pendulum object

    #### CHECK OUT PendulumSystem.py to ADD PERTURBATIONS TO THE MODEL #####

    pylog.info('Pendulum model initialized \n {}'.format(
        pendulum.parameters.showParameters()))

    # Define and Setup your pendulum model here
    # Check MuscleSytem.py for more details on MuscleSytem class
    M1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    M1_param.f_max = 1500  # To change Muscle 1 max force
    M2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    M2_param.f_max = 1500  # To change Muscle 2 max force
    M1 = Muscle(M1_param)  # Instantiate Muscle 1 object
    M2 = Muscle(M2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    muscles = MuscleSytem(M1, M2)  # Instantiate Muscle System with two muscles
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(), M2.parameters.showParameters()))

    # Define Muscle Attachment points
    m1_origin = np.array([-0.17, 0.0])  # Origin of Muscle 1
    m1_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 1

    m2_origin = np.array([0.17, 0.0])  # Origin of Muscle 2
    m2_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 2

    # Attach the muscles
    muscles.attach(np.array([m1_origin, m1_insertion]),
                   np.array([m2_origin, m2_insertion]))

    # Create a system with Pendulum and Muscles using the System Class
    # Check System.py for more details on System class
    sys = System()  # Instantiate a new system
    sys.add_pendulum_system(pendulum)  # Add the pendulum model to the system
    sys.add_muscle_system(muscles)  # Add the muscle model to the system

    ##### Time #####
    t_max = 3  # Maximum simulation time
    time = np.arange(0., t_max, 0.004)  # Time vector

    ##### Model Initial Conditions #####
    x0_P = np.array([0., 0.])  # Pendulum initial condition

    # Muscle Model initial condition
    x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

    x0 = np.concatenate((x0_P, x0_M))  # System initial conditions

    ##### System Simulation #####
    # For more details on System Simulation check SystemSimulation.py
    # SystemSimulation is used to initialize the system and integrate
    # over time

    sim = SystemSimulation(sys)  # Instantiate Simulation object

    # Add muscle activations to the simulation
    # Here you can define your muscle activation vectors
    # that are time dependent
    '''
    #act1 = np.ones((len(time), 1)) * 1.
    #act2 = np.ones((len(time), 1)) * 0.05
    act1 = (np.sin((time/t_max)*10*np.pi)+1)/2
    act2 = (np.sin((time/t_max)*10*np.pi + np.pi)+1)/2
    
    act1 = np.reshape(act1, (len(time),1)) 
    act2 = np.reshape(act2, (len(time),1)) 

    activations = np.hstack((act1, act2))

    # Plotting the results
    plt.figure('Activations')
    plt.title('Muscle activations')
    plt.plot(time, act1, label = 'Activation muscle 1')
    plt.plot(time, act2, label = 'Activation muscle 2')
    plt.xlabel('Time [s]')
    plt.ylabel('Activation')
    plt.legend()
    plt.grid()
    # Method to add the muscle activations to the simulation

    sim.add_muscle_activations(activations)
    '''
    max_amplitude = np.zeros([10, 10])
    i = 0
    j = 0
    # Simulate the system for given time
    for activation_max in np.arange(0, 1, 0.9):
        i = 0
        for frequency in np.arange(1, 10, 4):
            act1 = ((np.sin(
                (time / t_max) * frequency * np.pi) + 1) / 2) * activation_max
            act2 = ((np.sin((time / t_max) * frequency * np.pi + 1) + 1) /
                    2) * activation_max

            act1 = np.reshape(act1, (len(time), 1))
            act2 = np.reshape(act2, (len(time), 1))

            activations = np.hstack((act1, act2))
            sim.add_muscle_activations(activations)

            sim.initalize_system(x0, time)  # Initialize the system state

            #: If you would like to perturb the pedulum model then you could do
            # so by
            sim.sys.pendulum_sys.parameters.PERTURBATION = False
            # The above line sets the state of the pendulum model to zeros between
            # time interval 1.2 < t < 1.25. You can change this and the type of
            # perturbation in
            # pendulum_system.py::pendulum_system function

            # Integrate the system for the above initialized state and time
            sim.simulate()

            # Obtain the states of the system after integration
            # res is np.array [time, states]
            # states vector is in the same order as x0
            res = sim.results()
            # In order to obtain internal states of the muscle
            # you can access the results attribute in the muscle class
            muscle1_results = sim.sys.muscle_sys.Muscle1.results
            muscle2_results = sim.sys.muscle_sys.Muscle2.results

            max_amplitude[i, j] = np.max(np.abs(res[:, 1]))
            i += 1

            # Plotting the results
            plt.figure('Pendulum')
            plt.title('Pendulum Phase')
            plt.plot(res[:, 1],
                     res[:, 2],
                     label='activation %.2f - frequency %f' %
                     (activation_max, frequency))
            plt.xlabel('Position [rad]')
            plt.ylabel('Velocity [rad.s]')
            plt.grid()
        j += 1

    plt.figure('Amplitude')
    fig, ax1 = plt.subplots(1, 1)
    ax1.set_xticklabels(np.array([0, 0, 0.2, 0.4, 0.8, 1]))
    ax1.set_yticklabels(np.array([0, 1, 3, 5, 7, 9]))
    plt.title('Ampliudes')
    plt.imshow(max_amplitude, aspect='equal', origin='lower')

    plt.xlabel('Activation')
    plt.ylabel('Frequncy')
    # To animate the model, use the SystemAnimation class
    # Pass the res(states) and systems you wish to animate
    simulation = SystemAnimation(res, pendulum, muscles)
    # To start the animation
    if DEFAULT["save_figures"] is False:
        simulation.animate()

    if not DEFAULT["save_figures"]:
        plt.show()
    else:
        figures = plt.get_figlabels()
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
            plt.close(fig)
Ejemplo n.º 33
0
def zero_test():
    System.register_power_hardware("HDD", 200, 200)
    System.register_power_hardware("HDD", 200, 200)
    System.register_heavy_hardware("SSD", 400, 400)
    print(System.analyze())
    System.register_light_software("HDD", "Test", 0, 10)
    print(System.register_express_software("HDD", "Test2", 100, 100))
    System.register_express_software("HDD", "Test3", 50, 100)
    System.register_light_software("SSD", "Windows", 20, 50)
    System.register_express_software("SSD", "Linux", 50, 100)
    System.register_light_software("SSD", "Unix", 20, 50)
    print(System.analyze())
    System.release_software_component("SSD", "Linux")
    print(System.system_split())
from flask import Flask, render_template, request, redirect, url_for, flash
from system import System

app = Flask(__name__)
app.secret_key = 'what is the secret key used for?'
system_instance = System()


@app.route('/')
@app.route('/home')
def home():
    return render_template('home.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user = system_instance.client_login_details(
            Email_inp=request.form['Email'],
            Password_inp=request.form['Password'])
        if 'message' in user:
            flash("Invalid Credentials !")
            return render_template('login.html')
        flash('Login Successful !!')
        return render_template('my_details.html',
                               FirstName=user['FirstName'],
                               LastName=user['LastName'],
                               Email=user['Email'],
                               DateOfBirth=user['DateOfBirth'],
                               Mobile=user['Mobile'],
                               Address=user['Address'])
Ejemplo n.º 35
0
import pygame
from pygame.locals import *
import sys
from missile import Missile
from player import Player
from enemy import Enemy
from projectile import Projectile
from system import System
import random


TIMER_SPAWN_ENEMY = 3000
X_MARGIN_ENEMY_SPAWN = 50

# OBJECTS INITIALIZATION
game_system = System('Shoot them all!', (600, 1000))
player = Player(game_system.window_center)
objects = {}
objects["player"] = player
objects["missiles"] = []
objects["enemies"] = []
objects["projectiles"] = []
objects["effects"] = []
enemy = Enemy((random.randint(0+X_MARGIN_ENEMY_SPAWN,
                              game_system.width-X_MARGIN_ENEMY_SPAWN), 0))
objects["enemies"].append(enemy)
projectile = Projectile(game_system.window, enemy.rect.center,game_system.aim_projectile_vector(enemy,player))


# MAIN LOOP
background_iter = 0 
Ejemplo n.º 36
0
class Termud(object):
    def __init__(self):
        self.log = open("log", 'w', 0)
        self.boot()
        self.bootWorld()
        self.loop()

    def boot(self):
        try:
            self.interface = Interface()
            self.system = System()
            self.manager = Manager(self.system, self.interface)
        except:
            self.stop('Failed to boot Termud:\n\n' + traceback.format_exc())

    def bootWorld(self):
        try:
            self.world = World()
            self.manager.setWorld(self.world)
            self.world.registerWindows(self.manager)
            self.interface.setLayoutSize(self.world.sidebarWidth,
                                         self.world.topbarHeight)
            self.interface.build()
            self.system.connect(self.world.host, self.world.port)
        except:
            self.stop('Failed to boot World:\n\n' + traceback.format_exc())

    def loop(self):
        try:
            while True:
                sleep(1.0 / 30.0)
                self.step()
        except KeyboardInterrupt as e:
            self.stop("Gud bye!")
        except Exception as e:
            self.stop('Runtime error:\n\n' + traceback.format_exc())

    def step(self):
        while True:
            key = self.interface.getch()
            if not key:
                break
            self.system.input(key)
            self.world.input(key, self.manager)
            self.interface.setInput(self.system.getInput())
        actions = self.system.step()
        self.interface.checkResize()
        for action in actions:
            self.log.write(str(action) + "\n")
            if action[0] == "connected":
                self.world.onConnect(self.manager)
            if action[0] == "gmcp":
                self.world.handleGMCP(action[1], action[2], self.manager)
            else:
                self.interface.step(action)
        self.interface.refresh()

    def stop(self, reason=False):
        try:
            self.interface.stop()
        except:
            try:
                import curses
                curses.endwin()
            except:
                pass
        if reason:
            print reason
        exit()
Ejemplo n.º 37
0
def case():
    """
    In this example, one cantilever beam is bent towards another.
    Contact, static analysis.
    """

    mat = {
        'area': 7.85398e-5,
        'elastic_modulus': 1.0e9,
        'shear_modulus': 1.0e9,
        'inertia_primary': 4.90874e-10,
        'inertia_secondary': 4.90874e-10,
        'inertia_torsion': 9.81748e-10,
        'density': 8.0e-7,
        'contact_radius': 0.005
    }

    (coordinates1, elements1) = mesh.line_mesh(A=(0, 0, 0),
                                               B=(2.0, 0, 0),
                                               n_elements=3,
                                               order=1,
                                               material=mat,
                                               reference_vector=(0, 0, 1))
    (coordinates2,
     elements2) = mesh.line_mesh(A=(0.05, 0, 0.015),
                                 B=(0.85, 0, 0.015),
                                 n_elements=2,
                                 order=1,
                                 material=mat,
                                 reference_vector=(0, 0, 1),
                                 starting_node_index=coordinates1.shape[1],
                                 possible_contact_partners=elements1,
                                 dual_basis_functions=False,
                                 n_contact_integration_points=None)

    coordinates1[0, 1] = 0.9
    coordinates1[0, 2] = 1.2

    coordinates = np.hstack((coordinates1, coordinates2))
    elements = elements1 + elements2

    system = System(coordinates, elements)
    system.time_step = 1.0
    system.final_time = 101.0
    system.solver_type = 'static'
    system.convergence_test_type = 'RES'
    system.contact_detection = True
    system.print_residual = True
    system.max_number_of_newton_iterations = 10

    def user_distributed_force_load(self):
        q = []
        for ele in self.elements:
            qe = np.zeros((6, ele.int_pts[1].n_pts))
            p = 1.0
            qe[2] = -p
            q.append(qe)
        return q

    def user_displacement_load(self):
        n_nodes = self.get_number_of_nodes()
        U = np.zeros((6, n_nodes))
        if self.current_time > 1:
            U[0, coordinates1.shape[1]] = 1.001 / 100
        return U

    system.degrees_of_freedom[-1][0, coordinates1.shape[
        1]] = False  # [current time, dof 0 through 5, first node of the top beam]
    system.degrees_of_freedom[-1][
        6, coordinates1.
        shape[1]:] = True  # [current time, dof 6, all nodes of the top beam]
    system.degrees_of_freedom[-1][:6, :coordinates1.shape[
        1]] = False  # [current time, dof 0 through 5, all nodes of the bottom beam]
    system.distributed_force_load = functools.partial(
        user_distributed_force_load, system)
    system.displacement_load = functools.partial(user_displacement_load,
                                                 system)

    return system
Ejemplo n.º 38
0
Archivo: main.py Proyecto: kpj/OsciPy
def main(inp):
    """
    Main interface
    """
    if inp is None:
        # generate basis of system
        graph = nx.gnp_random_graph(10, 0.6)
        dim = len(graph.nodes())
        assert nx.is_connected(graph), 'Graph not connected'

        orig_A = nx.to_numpy_matrix(graph)
        orig_B = np.random.uniform(10, 20, size=dim)

        nz = np.nonzero(orig_A)
        orig_A[nz] = np.random.uniform(2, 5, size=len(nz[0]))

        print('Original A:\n', orig_A)
        print('Original B:', orig_B)

        omega = 3
        OMEGA_list = [2.9, 3.05, 3.1, 3.2]  #np.arange(3.7, 4.3, 0.05)

        # generate solutions
        data = []
        for OMEGA in tqdm(OMEGA_list):
            runs = []
            for i in trange(dim):
                mask = np.ones(dim, dtype=bool)
                mask[i] = 0
                Bvec = orig_B.copy()
                Bvec[mask] = 0

                syst = System(orig_A, Bvec, omega, OMEGA)
                sols, ts = syst.solve(0.01, 100)

                pdiffs = Reconstructor.extract_phase_differences(
                    sols, ts, syst.Phi)
                #print(pdiffs)
                #System.plot_solution(syst.Phi(ts), sols, ts)

                if pdiffs is not None:
                    runs.append(pdiffs)

            if len(runs) > 0:
                data.append(((OMEGA, omega), runs))

        # cache results
        fname = '{}_{}'.format(datetime.now().strftime('%Y%m%d%H%M%S'), dim)
        np.save('cache/{}'.format(fname), {
            'data': data,
            'ts': ts,
            'orig_A': orig_A,
            'orig_B': orig_B
        })
    else:
        data, ts = inp.item()['data'], inp.item()['ts']
        orig_A, orig_B = inp.item()['orig_A'], inp.item()['orig_B']
        dim = orig_A.shape[0]

        print('Original A:\n', orig_A)
        print('Original B:', orig_B)

    # reconstruct parameters
    recon = Reconstructor(ts, data, dim)
    rec_A, rec_B = recon.reconstruct()

    print('Reconstructed A:\n', rec_A)
    print('Reconstructed B:', rec_B)

    # plot result
    bundle = DictWrapper({
        'orig_A': orig_A,
        'orig_B': orig_B,
        'rec_A': rec_A,
        'rec_B': rec_B
    })
    show_reconstruction_overview(bundle, verbose=dim < 20)
Ejemplo n.º 39
0
def exercise3a():
    """ Main function to run for Exercise 3.

    Parameters
    ----------
        None

    Returns
    -------
        None
    """
    # Define and Setup your pendulum model here
    # Check Pendulum.py for more details on Pendulum class
    P_params = PendulumParameters()  # Instantiate pendulum parameters
    P_params.L = 0.5  # To change the default length of the pendulum
    P_params.m = 1.  # To change the default mass of the pendulum
    pendulum = PendulumSystem(P_params)  # Instantiate Pendulum object

    #### CHECK OUT Pendulum.py to ADD PERTURBATIONS TO THE MODEL #####

    pylog.info('Pendulum model initialized \n {}'.format(
        pendulum.parameters.showParameters()))

    # Define and Setup your pendulum model here
    # Check MuscleSytem.py for more details on MuscleSytem class
    M1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    M1_param.f_max = 1500  # To change Muscle 1 max force
    M2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    M2_param.f_max = 1500  # To change Muscle 2 max force
    M1 = Muscle(M1_param)  # Instantiate Muscle 1 object
    M2 = Muscle(M2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    muscles = MuscleSytem(M1, M2)  # Instantiate Muscle System with two muscles
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(), M2.parameters.showParameters()))

    # Define Muscle Attachment points
    m1_origin = np.array([-0.17, 0.0])  # Origin of Muscle 1
    m1_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 1

    m2_origin = np.array([0.17, 0.0])  # Origin of Muscle 2
    m2_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 2

    # Attach the muscles
    muscles.attach(np.array([m1_origin, m1_insertion]),
                   np.array([m2_origin, m2_insertion]))

    ##### Neural Network #####
    # The network consists of four neurons
    N_params = NetworkParameters()  # Instantiate default network parameters
    N_params.D = 2.  # To change a network parameter
    # Similarly to change w -> N_params.w = (4x4) array
    print(N_params.w)
    ############################# Exercise 3A  ######################
    N_params.w = np.transpose(
        np.asarray([[0, -1, 1, -1], [-1, 0, -1, 1], [-1, 0, 0, 0],
                    [0, -1, 0, 0]])) * 5
    print(N_params.w, N_params.D, N_params.tau, N_params.b, N_params.exp)

    # Create a new neural network with above parameters
    neural_network = NeuralSystem(N_params)
    pylog.info('Neural system initialized \n {}'.format(
        N_params.showParameters()))

    # Create system of Pendulum, Muscles and neural network using SystemClass
    # Check System.py for more details on System class
    sys = System()  # Instantiate a new system
    sys.add_pendulum_system(pendulum)  # Add the pendulum model to the system
    sys.add_muscle_system(muscles)  # Add the muscle model to the system
    # Add the neural network to the system
    sys.add_neural_system(neural_network)

    ##### Time #####
    t_max = 2.  # Maximum simulation time
    time = np.arange(0., t_max, 0.001)  # Time vector

    ##### Model Initial Conditions #####
    x0_P = np.array([0., 0.])  # Pendulum initial condition

    # Muscle Model initial condition
    x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

    x0_N = np.array([-0.5, 1, 0.5, 1])  # Neural Network Initial Conditions

    x0 = np.concatenate((x0_P, x0_M, x0_N))  # System initial conditions

    ##### System Simulation #####
    # For more details on System Simulation check SystemSimulation.py
    # SystemSimulation is used to initialize the system and integrate
    # over time

    sim = SystemSimulation(sys)  # Instantiate Simulation object

    # Add external inputs to neural network

    #    sim.add_external_inputs_to_network(np.ones((len(time), 4)))

    #    wave_h1 = np.sin(time*3)*2               #makes a sinusoidal wave from 'time'
    #    wave_h2 = np.sin(time*3 + np.pi)*1       #makes a sinusoidal wave from 'time'
    #
    #    wave_h1[wave_h1<0] = 0      #formality of passing negative values to zero
    #    wave_h2[wave_h2<0] = 0      #formality of passing negative values to zero
    #
    #    act1 = wave_h1.reshape(len(time), 1) #makes a vertical array like act1
    #    act2 = wave_h2.reshape(len(time), 1) #makes a vertical array like act1
    #    column = np.ones((len(time), 1))

    #    ext_in = np.hstack((act1, column, act2, column))

    #    sim.add_external_inputs_to_network(ext_in)
    sim.initalize_system(x0, time)  # Initialize the system state

    sim.sys.pendulum_sys.parameters.PERTURBATION = False

    # Integrate the system for the above initialized state and time
    sim.simulate()

    # Obtain the states of the system after integration
    # res is np.array [time, states]
    # states vector is in the same order as x0
    res = sim.results()

    # Obtain the states of the system after integration
    # res is np.array [time, states]
    # states vector is in the same order as x0
    res = sim.results()

    # In order to obtain internal states of the muscle
    # you can access the results attribute in the muscle class
    muscle1_results = sim.sys.muscle_sys.Muscle1.results
    muscle2_results = sim.sys.muscle_sys.Muscle2.results

    # Plotting the results: Position(phase) vs time
    plt.figure('Pendulum Phase')
    plt.title('Pendulum Phase')
    plt.plot(res[:, 0], res[:, 1])  #to plot pendulum Position (phase)
    #    plt.plot(res[:, 0], time)   #to plot position
    #    plt.plot(res[:, 0], res[:, -5:-1])  # to Plot neurons' states
    plt.xlabel('time [s]')
    plt.ylabel('Position [rad]')
    plt.grid()

    # Plotting the results: Velocity vs Position (phase)
    plt.figure('Pendulum Vel v.s. Phase')
    plt.title('Pendulum Vel v.s. Phase')
    plt.plot(res[:, 1], res[:, 2])  #to plot Velocity vs Position (phase)
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad.s]')
    plt.grid()

    # Plotting the results: Velocity vs time
    plt.figure('Pendulum Velocity')
    plt.title('Pendulum Velocity')
    plt.plot(res[:, 0], res[:, 2])  #to plot Velocity vs Position
    plt.xlabel('time [s]')
    plt.ylabel('Velocity [rad.s]')
    plt.grid()

    # Plotting the results: Output of the network
    plt.figure('Network output')
    plt.title('Network output')
    plt.plot(res[:, 0], res[:, -1],
             label='neuron1')  #to plot Velocity vs Position
    plt.plot(res[:, 0], res[:, -2], label='neuron2')
    plt.plot(res[:, 0], res[:, -3], label='neuron3')
    plt.plot(res[:, 0], res[:, -4], label='neuron4')
    plt.xlabel('time [s]')
    plt.ylabel('Stimulation ')
    plt.legend(loc='upper right')
    plt.grid()

    if DEFAULT["save_figures"] is False:
        plt.show()
    else:
        figures = plt.get_figlabels()
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
            plt.close(fig)

    # To animate the model, use the SystemAnimation class
    # Pass the res(states) and systems you wish to animate
    simulation = SystemAnimation(res, sim.sys.pendulum_sys, sim.sys.muscle_sys,
                                 sim.sys.neural_sys)
    # To start the animation
    simulation.animate()
Ejemplo n.º 40
0
class PasswordManager:
    def __init__(self, id_user: int = 0):
        """
		Init method.
		"""
        self.database = Database()
        self.system = System()
        self.id_user = id_user
        self.alert = ""

    def menu(self):
        """
		This method print a menu and checks the data entered by the user.
		"""
        self.system.clear_terminal()
        if self.alert != "":
            print(f"{self.alert}\n")
        print(("-" * 19) + " Menu " + ("-" * 19))
        print("1. Create a new password")
        print("2. Search for all sites you have registered")
        print("3. Find a password for a site or application")
        print("Q. Quit")
        print("-" * 44)
        self.choice = input(": ").lower()
        while self.choice != "q" and self.choice != "1" and self.choice != "2" and self.choice != "3":
            print("Sorry, I don't understand !")
            self.choice = input(": ").lower()
        if self.choice == "1":
            self.create_new_password()
        elif self.choice == "2":
            self.search_all_sites_registered()
        elif self.choice == "3":
            self.find_password()
        else:
            self.system.exit_program("You leave the program.")

    def create_new_password(self):
        """
		This method is a form to create a new password for an application or site.
		"""
        app_name = input("Please enter the application name : ").capitalize()
        identifier = input("Please enter the identifier : ")
        password = input("Please enter the password : "******"Please enter the url : ").lower()
        while app_name == "" or identifier == "" or password == "" or url == "":
            print("\nPlease complete all fields !")
            app_name = input(
                "Please enter the application name : ").capitalize()
            identifier = input("Please enter the identifier : ")
            password = input("Please enter the password : "******"Please enter the url : ").lower()
        verify_app_name = self.database.research_app_name(
            self.id_user, app_name)
        if verify_app_name != []:
            self.alert = f"{app_name} is already registered !"
            self.menu()
        password_hashed = self.hash(password)
        pyperclip.copy(password_hashed)
        pyperclip.paste()
        self.database.insert_new_password(self.id_user, app_name, identifier,
                                          password_hashed, url)
        self.alert = f"The password for the site or the application {app_name} has been saved !"
        self.menu()

    def search_all_sites_registered(self):
        """
		This method displays all accounts of the logged in user.
		"""
        data = ("App Name: ", "Identifier: ", "Password: "******"Url: ")
        result = self.database.search_all_sites(self.id_user)
        if result == []:
            self.alert = "You have not registered an account !"
            self.menu()
        print("\nResult:\n")
        for row in result:
            [print(str(data[i]) + str(row[i])) for i in range(len(row))]
            print("")
        print("-" * 30)

    def find_password(self):
        """
		This method saves the password of the application that the user to request.
		"""
        app_name = input(
            "Please enter the name of application/site : ").capitalize()
        result = self.database.find_password_to_application(
            self.id_user, app_name)
        if result == []:
            self.alert = f"{app_name} has not been registered !"
            self.menu()
        pyperclip.copy(result[0][0])
        pyperclip.paste()
        self.alert = f"The password for {app_name} has been copied to the clipboard !"
        self.menu()

    def hash(self, password: str):
        """
		This method encrypts the password passed as a parameter.
		"""
        return sha256((password + KEY + password).encode("utf-8")).hexdigest()
Ejemplo n.º 41
0
from system import System
x = System()

print('Rock, Paper, Scissors'+'             '+'Author: Mahtab')

computer_point = 0
user_point = 0
opt = True
willplay = True
name = None

while willplay:
    if opt:
        print("Enter 'r' for rock, 'p' for paper, 's' for scissors\nRock Wins With Scissors\nPaper Wins With Rock\nScissors Wins With Paper")
        print()

    if not name:
        name = input('Enter Your Name Here: ')

    p = 'a'

    while p.isalpha():
        p = input('Enter The Winning Point Here: ')

    print('Match Has Started..')
    print()

    user = '******'
    p = int(p)
    computer_point = 0
    user_point = 0
Ejemplo n.º 42
0
import threading
from system import System
from random import randint

process1 = threading.Thread(target=System(randint(5101, 5200), 1, 'ceico',
                                          5000).main,
                            args=())
process2 = threading.Thread(target=System(randint(5201, 5300), 2, 'ceico',
                                          5000).main,
                            args=())
process3 = threading.Thread(target=System(randint(5301, 5400), 3, 'ceico',
                                          5000).main,
                            args=())

process1.start()
process2.start()
process3.start()

process1.join()
process2.join()
process3.join()
Ejemplo n.º 43
0
import main
from system import System

DISPLAY = False

SYSTEM = System(DISPLAY)

for i in range(2):
    main.run_simulation(SYSTEM=SYSTEM, DISPLAY=DISPLAY)
    set_clear_color(0, 0, 0)  # black background

    clear()

    # Draw the system in its current state.
    solar.draw(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, PIXELS_PER_METER)

    # Update the system for its next state.
    solar.update(TIMESTEP * TIME_SCALE)

    if pressed:
        planet_preview()


sun = Body(1.98892e30, 0, 0, 0, 0, 30, 1, 1, 0)
mercury = Body(3.30e23, 5.79e10, 0, 0, -47400, 3, 1, 0.5, 0)
venus = Body(4.87e24, 1.082e11, 0, 0, -35000, 8, 0, 1, 0)
earth = Body(5.9736e24, 1.496e11, 0, 0, -29800, 8, 0, 0, 1)
mars = Body(6.42e23, 2.279e11, 0, 0, -24100, 4, 1, 0, 0)

solar = System([sun, mercury, venus, earth, mars])

# added these variables for interactive planet creating functionality
press_time = None
press_coords = []
pressed = False
new_planet_size = 1

start_graphics(main, 2400, framerate=FRAMERATE, height=WINDOW_HEIGHT, width=WINDOW_WIDTH, mouse_press=press,
               mouse_release=release)
test = Grid(*build_from_segments(((1,Ns),)))
test.rectangle(1,(0.5,0.5),0.4,0.7)
test.rectangle(1,(0.2,0.4),0.02,0.02)

#test.show(color=(0,0,0,0.1))

amr_system = AMR_system(test)
amr_system.SOR(w=w,max_iter=10000,max_time=150,tol=1e-10,verbose=False)

print('amr time:',clock()-start)
#amr_system.show()

start = clock()

system = System(Ns+1)

system.add(Shape(Ns+1,1,(0.5,0.5),0.4,0.7,shape='rectangle'))
system.add(Shape(Ns+1,1,(0.2,0.4),0.02,0.02,shape='rectangle'))

#system.show_setup()

system.SOR_single(w=w,max_iter=10000,max_time=150,tol=1e-10,verbose=False)

print('normal time:',clock()-start)
#system.show()

source_diff = system.source_potentials - amr_system.grid.source_potentials
plt.figure()
plt.title('source diffs')
plt.imshow(source_diff.T,origin='lower',interpolation='none')
Ejemplo n.º 46
0
def main():
    system = System()
    while True:
        system.menu()
        oper = input('请输入您的操作:')
        if oper == '1':
            system.addphone()
        elif oper == '2':
            system.search_phone()
        elif oper == '3':
            system.display_all_phones()
        elif oper == '4':
            system.update_price()
        elif oper == '5':
            system.del_phone()
        elif oper == '6':
            exit()
        time.sleep(2)
Ejemplo n.º 47
0
from body import Body

WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400

TIME_SCALE = 100000  # real seconds per simulation second
PIXELS_PER_METER = 3 / 1e7  # distance scale for the simulation

FRAMERATE = 30  # frames per second
TIMESTEP = 1.0 / FRAMERATE  # time between drawing each frame


def main():

    set_clear_color(0, 0, 0)  # black background

    clear()

    # Draw the system in its current state.
    earth_moon.draw(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2, PIXELS_PER_METER)

    # Update the system for its next state.
    earth_moon.update(TIMESTEP * TIME_SCALE)


earth = Body(5.9736e24, 0, 0, 0, 0, 24, 0, 0, 1)  # blue earth
moon = Body(7.3477e22, 3.84403e8, 0, 0, 1022, 4, 1, 1, 1)  # white moon
earth_moon = System(
    [earth, moon])  # list of bodies that are an object of the System class

start_graphics(main, 2400, framerate=FRAMERATE)
Ejemplo n.º 48
0
 def test_set_val_const(self):
     system = System()
     cpu = C8cpu()
     opcode = 0x6277
     cpu.set_val_const(opcode, system)
     self.assertEqual(system.registers[2], 0x77)
Ejemplo n.º 49
0
from system import System


if __name__ == '__main__':
    s = System.System()
    s.initialize()
    s.core()
Ejemplo n.º 50
0
from drawer import Drawer
from system import System

rules = {'X': 'F[-X][X]F[-X]+FX', 'F': 'pFF'}

s = System('X', rules)
d = Drawer(draw_speed=0,
           init_angle=0,
           init_size=7,
           fwd_amt=5,
           turn_amt=30,
           inc_amt=0.1)

d.draw(s.get_str(6))

try:
    input('any key to exit')
except:
    pass
Ejemplo n.º 51
0
        loop = new_event_loop()
        set_event_loop(loop)
        loop.create_task(
            start_unix_server(self._read_commands_from_socket,
                              "/home/austin/uds_socket"))
        loop.run_forever()

    async def _read_commands_from_socket(self, reader, writer):
        request = (await reader.read(256))
        cmd = Command.Parse(request)
        response = cmd.exec(system=system)
        payload = json.dumps(response.value).encode()
        writer.write(cmd.command_id.encode().ljust(8, b"\0") +
                     str(len(payload)).encode().ljust(8, b"\0") + payload)
        await writer.drain()
        writer.close()


system = System(ships=[_create_test_ship()], inert_bodies=_create_asteroids())
system.clock = GameClock
if __name__ == "__main__":
    GameClock()
    thread = CommandServer()
    thread.start()
    while True:
        print("=================== Loop {} ===================".format(
            system.clock.time()))
        responses = system.perform_tick()
        system.clock.next()
        sleep(0.05)
Ejemplo n.º 52
0
 def __init__(self):
     self.manager = System()
Ejemplo n.º 53
0
 def test_call(self):
     system = System()
     cpu = C8cpu()
     opcode = 0x0ABD
     cpu.call(opcode, system)
     self.assertEqual(system.pc, 0xABD)
Ejemplo n.º 54
0
 def test_flow_goto(self):
     system = System()
     cpu = C8cpu()
     opcode = 0x1123
     cpu.flow_goto(opcode, system)
     self.assertEqual(system.pc, 0x123)
Ejemplo n.º 55
0
from Apps.sleepSecurity import SleepSecurity

from environment import Environment

from system import System


def update():
    env.update()
    sys_.process()

    sys_.show_current_state()


env = Environment()
sys_ = System(env)

# # # # # SENSORS # # # # #
outdoor_motion_detector = MotionSensor(env)
sys_.register_sensor(outdoor_motion_detector)

power_meter = PowerMeter(env)
sys_.register_sensor(power_meter)

power_rate = PowerRate(env)
sys_.register_sensor(power_rate)

user_locator = UserLocator(env)
sys_.register_sensor(user_locator)

outdoor_brightness = OutdoorBrightnessSensor(env)
Ejemplo n.º 56
0
 def test_call_subrutine(self):
     system = System()
     cpu = C8cpu()
     opcode = 0x2ABD
     cpu.call_subrutine(opcode, system)
     self.assertEqual(system.pc, 0xABD)
Ejemplo n.º 57
0
 def test_mem_set(self):
     system = System()
     cpu = C8cpu()
     opcode = 0xA123
     cpu.mem_set(opcode, system)
     self.assertEqual(system.index, 0x123)
Ejemplo n.º 58
0
 def __init__(self,ship,system,markers,name):
     self.markers = list(markers)
     newsystem = System(markers,None,name)
     YellowAction.__init__(self,ship,system,newsystem)
Ejemplo n.º 59
0
    def test_execute(self):
        cpu = C8cpu(testing=True)
        system = System()

        # Call
        instruction = 0x0123
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # display_clear
        instruction = 0x00E0
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # flow_return
        instruction = 0x00EE
        system.stack.append(0x999)
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # flow_goto
        instruction = 0x1123
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # call subrutine
        instruction = 0x2123
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # skip if eqv
        instruction = 0x3123
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # skip if neqv
        instruction = 0x4123
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # skip if eq
        instruction = 0x5120
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # set val const
        instruction = 0x6120
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # add val const
        instruction = 0x7120
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # addign reg
        instruction = 0x8120
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # bit op or
        instruction = 0x8121
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # bit op and
        instruction = 0x8122
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # bit op xor
        instruction = 0x8123
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # math add
        instruction = 0x8124
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # math sub
        instruction = 0x8125
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # bit op right shift
        instruction = 0x8126
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # math sub regs
        instruction = 0x8127
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # bit op left shift
        instruction = 0x812E
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # skip if neqr
        instruction = 0x9120
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # mem set
        instruction = 0xA12E
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # flow jmp
        instruction = 0xB12E
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # flow random_valr
        instruction = 0xC12E
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # display
        instruction = 0xD12E
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # key op skip eq
        instruction = 0xE19E
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # key op skip neq
        instruction = 0xE1A1
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # timer get delay
        instruction = 0xF107
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # key op get key
        instruction = 0xF10A
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # set delay timer
        instruction = 0xF115
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # set sound timer
        instruction = 0xF118
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # mem add
        instruction = 0xF11E
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # mem set spritaddr
        instruction = 0xF129
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # binary coded decimal store
        instruction = 0xF133
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # mem reg dump
        instruction = 0xF155
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)

        # mem reg load
        instruction = 0xF165
        opcode = cpu.decode(instruction)
        cpu.execute(instruction, opcode, system)
Ejemplo n.º 60
0
def exercise2():
    """ Main function to run for Exercise 2.

    Parameters
    ----------
        None

    Returns
    -------
        None
    """
    
    #----------------# Exercise 2a #----------------#

    theta = np.linspace(-np.pi/4, np.pi/4,num=50)
    h1=[]
    a1= 1
    a2a1=np.linspace(0.5,2,num=4)

    plt.figure('2a_Muscle_Length_vs_Theta')    
    plt.title('Muscle Length vs Theta')
    plt.xlabel('Position [rad]')
    plt.ylabel('Muscle length [m]')
    plt.grid()
    plt.figure('2a_Moment_arm_vs_Theta')    
    plt.title('Moment arm vs Theta')
    plt.xlabel('Position [rad]')
    plt.ylabel('Moment arm [m]')
    plt.grid()

    for i in range(0,len(a2a1)):
        a2=a2a1[i]*a1
        L1=(np.sqrt(a1**2+a2**2+2*a1*a2*np.sin(theta)))
        h1=((a1*a2*np.cos(theta))/L1)

        plt.figure('2a_Muscle_Length_vs_Theta')
        plt.plot(theta,L1,label=('a2/a1 = %.1f' %(a2a1[i])))

        plt.figure('2a_Moment_arm_vs_Theta')
        plt.plot(theta,h1,label=('a2/a1= %.1f' %(a2a1[i])))
        
    plt.figure('2a_Muscle_Length_vs_Theta')
    plt.legend()
    plt.figure('2a_Moment_arm_vs_Theta')
    plt.legend()

    #----------------# Exercise 2a finished #----------------#
    
    
    # Define and Setup your pendulum model here
    # Check PendulumSystem.py for more details on Pendulum class
    pendulum_params = PendulumParameters()  # Instantiate pendulum parameters
    pendulum_params.L = 0.5  # To change the default length of the pendulum
    pendulum_params.m = 1.  # To change the default mass of the pendulum
    pendulum = PendulumSystem(pendulum_params)  # Instantiate Pendulum object

    #### CHECK OUT PendulumSystem.py to ADD PERTURBATIONS TO THE MODEL #####

    pylog.info('Pendulum model initialized \n {}'.format(
        pendulum.parameters.showParameters()))

    # Define and Setup your pendulum model here
    # Check MuscleSytem.py for more details on MuscleSytem class
    M1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    M1_param.f_max = 1500  # To change Muscle 1 max force
    M2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    M2_param.f_max = 1500  # To change Muscle 2 max force
    M1 = Muscle(M1_param)  # Instantiate Muscle 1 object
    M2 = Muscle(M2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    muscles = MuscleSytem(M1, M2)  # Instantiate Muscle System with two muscles
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(),
        M2.parameters.showParameters()))

    # Define Muscle Attachment points
    m1_origin = np.array([-0.17, 0.0])  # Origin of Muscle 1
    m1_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 1

    m2_origin = np.array([0.17, 0.0])  # Origin of Muscle 2
    m2_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 2

    # Attach the muscles
    muscles.attach(np.array([m1_origin, m1_insertion]),
                   np.array([m2_origin, m2_insertion]))

    # Create a system with Pendulum and Muscles using the System Class
    # Check System.py for more details on System class
    sys = System()  # Instantiate a new system
    sys.add_pendulum_system(pendulum)  # Add the pendulum model to the system
    sys.add_muscle_system(muscles)  # Add the muscle model to the system

    ##### Time #####
    t_max = 5  # Maximum simulation time
    time = np.arange(0., t_max, 0.001)  # Time vector

    ##### Model Initial Conditions #####
    x0_P = np.array([np.pi/4, 0.])  # Pendulum initial condition

    # Muscle Model initial condition
    x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

    x0 = np.concatenate((x0_P, x0_M))  # System initial conditions

    ##### System Simulation #####
    # For more details on System Simulation check SystemSimulation.py
    # SystemSimulation is used to initialize the system and integrate
    # over time

    sim = SystemSimulation(sys)  # Instantiate Simulation object

    # Add muscle activations to the simulation
    # Here you can define your muscle activation vectors
    # that are time dependent

    activationFunction = ['sin','square']
    for idx, act in enumerate(activationFunction):
        #----------------# Exercise 2c #----------------#
        
        w = np.linspace(0.2,4,4)
#        w = 0.5
#        a = np.linspace(0.1,1,4)
        plt.figure('2c_LimitCycle_'+str(act))
#        plt.figure('2c_LimitCycle_Amplitude_'+str(act))
        plt.title('Pendulum Phase')
        
        plt.figure('2c_Amplitude_'+str(act))
#        plt.figure('2c_Amplitude_Amplitude_'+str(act))
        plt.title('Amplitude vs. Frequency')
#        plt.title('Amplitude vs. Stimulation Amplitude')
        
        for i in range(0,len(w)):
#        for i in range(0,len(a)):
#            plt.figure('2c_LimitCycle_Amplitude_'+str(act))
            plt.figure('2c_LimitCycle_'+str(act))
            print('Running simulation %d out of %d'%(i+1,len(w)))
#            print('Running simulation %d out of %d'%(i+1,len(a)))
            
            if act == 'sin':
                sinAct = np.sin(2*np.pi*w[i]*time).reshape(len(time),1)
#                sinAct = a[i]*np.sin(2*np.pi*w*time).reshape(len(time),1)
            else:
                sinAct = signal.square(2*np.pi*w[i]*time).reshape(len(time),1)
#                sinAct = a[i]*signal.square(2*np.pi*w*time).reshape(len(time),1)
                
            sinFlex = sinAct.copy()
            sinFlex[sinAct<0] = 0 
            sinExt = sinAct.copy()
            sinExt[sinAct>0] = 0
            sinExt = abs(sinExt)
            
            sinAct1 = np.ones((len(time),1))
            sinAct2 = np.ones((len(time),1))
            sinAct1 = sinFlex
            sinAct2 = sinExt
        
            sinActivations = np.hstack((sinAct1,sinAct2))
            # Method to add the muscle activations to the simulation
        
            sim.add_muscle_activations(sinActivations)
        
            # Simulate the system for given time
        
            sim.initalize_system(x0, time)  # Initialize the system state
        
            #: If you would like to perturb the pedulum model then you could do
            # so by
            sim.sys.pendulum_sys.parameters.PERTURBATION = False
            # The above line sets the state of the pendulum model to zeros between
            # time interval 1.2 < t < 1.25. You can change this and the type of
            # perturbation in
            # pendulum_system.py::pendulum_system function
        
            # Integrate the system for the above initialized state and time
            sim.simulate()
        
            # Obtain the states of the system after integration
            # res is np.array [time, states]
            # states vector is in the same order as x0
            res = sim.results()
        
            # In order to obtain internal states of the muscle
            # you can access the results attribute in the muscle class
            muscle1_results = sim.sys.muscle_sys.Muscle1.results
            muscle2_results = sim.sys.muscle_sys.Muscle2.results
        
            # Plotting the results
            
            plt.plot(res[:, 1], res[:, 2], label='Act. $%s(2\cdot{}\\pi\cdot{}%.1f\cdot{}t)$'%(act,w[i]))
#            plt.plot(res[:, 1], res[:, 2], label='Act. $%.1f\cdot{}%s(2\cdot{}\\pi\cdot{}0.5\cdot{}t)$'%(a[i],act))
            plt.figure('2c_Amplitude_'+str(act))
            plt.plot(time,res[:, 1], label='Frequency = %.1f'%(w[i]))
            
#            plt.figure('2c_Amplitude_Amplitude_'+str(act))
#            plt.plot(time,res[:, 1], label='Amplitude = %.1f'%(a[i]))
            
            
        plt.figure('2c_LimitCycle_'+str(act))
#        plt.figure('2c_LimitCycle_Amplitude_'+str(act))
        
        plt.xlabel('Position [rad]')
        plt.ylabel('Velocity [rad/s]')
        plt.grid()
        plt.legend()
        
        plt.figure('2c_Amplitude_'+str(act))
#        plt.figure('2c_Amplitude_Amplitude_'+str(act))
        plt.xlabel('Time [s]')
        plt.ylabel('Amplitude [rad]')
        plt.grid()
        plt.legend()
        
        #----------------# Exercise 2c finished #----------------#
        
        #----------------# Exercise 2b #----------------#

        w = 0.5
        if act == 'sin':
            sinAct = np.sin(2*np.pi*w*time).reshape(len(time),1)
        else:
            sinAct = signal.square(2*np.pi*w*time).reshape(len(time),1)
        sinFlex = sinAct.copy()
        sinFlex[sinAct<0] = 0 
        sinExt = sinAct.copy()
        sinExt[sinAct>0] = 0
        sinExt = abs(sinExt)
        
        sinAct1 = np.ones((len(time),1))
        sinAct2 = np.ones((len(time),1))
        sinAct1 = sinFlex
        sinAct2 = sinExt
        activations = np.hstack((sinAct1,sinAct2))     
            
        # Method to add the muscle activations to the simulation
    
        sim.add_muscle_activations(activations)
    
        # Simulate the system for given time
    
        sim.initalize_system(x0, time)  # Initialize the system state
    
        #: If you would like to perturb the pedulum model then you could do
        # so by
        sim.sys.pendulum_sys.parameters.PERTURBATION = True
        # The above line sets the state of the pendulum model to zeros between
        # time interval 1.2 < t < 1.25. You can change this and the type of
        # perturbation in
        # pendulum_system.py::pendulum_system function
    
        # Integrate the system for the above initialized state and time
        sim.simulate()
    
        # Obtain the states of the system after integration
        # res is np.array [time, states]
        # states vector is in the same order as x0
        res = sim.results()
    
        # In order to obtain internal states of the muscle
        # you can access the results attribute in the muscle class
        muscle1_results = sim.sys.muscle_sys.Muscle1.results
        muscle2_results = sim.sys.muscle_sys.Muscle2.results
    
        # Plotting the results
        plt.figure('2b_LimitCycle_'+str(act))
        plt.title('Pendulum Phase')
        plt.plot(res[:, 1], res[:, 2], label='Act. $%s(2\cdot{}\\pi\cdot{}%.1f\cdot{}t)$, Pert. ($t=3.2,\\theta = 1, \dot{\\theta} = -0.5$)' %(act,w))
        plt.xlabel('Position [rad]')
        plt.ylabel('Velocity [rad/s]')
        plt.grid()
        plt.legend()
        
        plt.figure('2b_ActivationFunction_'+str(act))
        plt.title('Activation Function')
        plt.plot(time, sinAct1, label='Flexor')
        plt.plot(time, sinAct2, label='Extensor')
        plt.xlabel('Time [s]')
        plt.ylabel('Activation')
        plt.grid()
        plt.legend()
  
        #----------------# Exercise 2b finished #----------------#
    
    # To animate the model, use the SystemAnimation class
    # Pass the res(states) and systems you wish to animate
    simulation = SystemAnimation(res, pendulum, muscles)
    # To start the animation
    if DEFAULT["save_figures"] is False:
        simulation.animate()

    if not DEFAULT["save_figures"]:
        plt.show()
    else:
        figures = plt.get_figlabels()
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
            #plt.close(fig)
        plt.show