예제 #1
0
 def finish_plot(args,params_chipt,params_plot,result,ax,leg1,leg2):
     epi = result['xdict']['epi_plot']
     a = result['xdict']['a']
     if type(epi) != np.ndarray and type(a) == np.ndarray:
         ax.set_xlabel(r'$(a/w_0)^2$',fontsize=params_plot['fs'])
         ax.axis([args.asq_x[0],args.asq_x[1],args.asq_y[0],args.asq_y[1]])
         x0 = 0
     elif type(a) != np.ndarray and type(epi) == np.ndarray: 
         ax.set_xlabel(r'$\epsilon_\pi = m_\pi /(4\pi F_\pi)$',fontsize=params_plot['fs'])
         ax.vlines(params_chipt['epi_phys'],0.5,1.6,linestyle='--',color='k')
         ax.axis([args.epi_x[0],args.epi_x[1],args.epi_y[0],args.epi_y[1]])
         x0 = params_chipt['epi_phys']
     ax.set_ylabel(r'$g_A$',fontsize=params_plot['fs'])
     leg = ax.errorbar(x0,params_chipt['ga_phys'],\
         yerr=params_chipt['dga_phys'],\
         marker='o',markersize=10,mec='k',mfc='None',color='k',alpha=1,linestyle='None',\
         label=r'$g_A^{PDG}=%.4f(%s)$' \
             %(params_chipt['ga_phys'],str(params_chipt['dga_phys']).split('0')[-1]))
     leg2.append(leg)
     d_leg = ax.legend(handles=leg1,loc=4,numpoints=1,ncol=2,shadow=False,fancybox=True)
     plt.gca().add_artist(d_leg)
     ax.legend(handles=leg2,loc=1,numpoints=1,ncol=1,shadow=False,fancybox=True)
     ax.tick_params(axis='both', which='major', labelsize=16)
     ax.set_title(plt.get_figlabels()[-1].split(' ')[-1],fontdict={'fontsize':20,'verticalalignment':'top','horizontalalignment':'left'},x=0.05,y=0.9)
     plt.savefig('%s.pdf' %(plt.get_figlabels()[-1].replace(' ','_').replace('(','').replace(')','').replace('$','').replace('\\','').replace('.','').replace('^','').replace('/','')), transparent=True)
     return 0
예제 #2
0
 def plot_results(self, x, y, label, name_x, name_y, figure_number, marker):
     plt.figure(figure_number)
     plt.plot(x, y, label=label, marker=marker)
     plt.xlabel = name_x
     plt.ylabel = name_y
     plt.legend()
     plt.get_figlabels()
예제 #3
0
 def fv_plot(args,params_chipt,params_plot,result,data,ax,select):
     e0 = result['xdict']['epi0']
     x = result['xdict']['xplot']
     # data for plots
     i_fv = [params_chipt['ens_idx']['a12m220S'],params_chipt['ens_idx']['a12m220'],\
         params_chipt['ens_idx']['a12m220L']]
     mL = [params_chipt['mpiL']['a12m220S'],params_chipt['mpiL']['a12m220'],\
         params_chipt['mpiL']['a12m220L']]
     epiL = [data['epi_b0'][params_chipt['ens_idx']['a12m220S']],\
         data['epi_b0'][params_chipt['ens_idx']['a12m220']],\
         data['epi_b0'][params_chipt['ens_idx']['a12m220L']]]
     xL = np.exp(-np.array(mL)) / np.sqrt(np.array(mL))
     epi = np.mean(epiL)
     epifv = epi
     if 'esq' in select:
         epi = epi**2
     a = params_chipt['aw0']['a12m220']
     # reconstructed fit
     mLplot = result['xdict']['mL']
     xplot = np.exp(-mLplot) / np.sqrt(mLplot)
     #print ga_L
     ga_L = np.zeros_like(mLplot)
     dga_L = np.zeros_like(mLplot)
     cov = np.array(result['ga_min'].matrix(correlation=False,skip_fixed=True))
     fv_class = gafit.FV_function(epifv,mLplot)
     if 'g0fv' in result['ga_min'].values:
         ga_L  = fv_class.dgaFV(result['ga_min'].values['g0fv'])
         ga_L += gafit.ga_epi(epi0=e0,epi=epi,a=a,**result['ga_min'].values)
     else:
         ga_L  = fv_class.dgaFV(result['ga_min'].values['g0'])        
         ga_L += gafit.ga_su2(epi=epi,a=a,**result['ga_min'].values)
     dga_L = np.zeros_like(ga_L)
     for i,mLi in enumerate(mLplot):
         if select in ['t_esq1_a2','t_esq0_a2','t_esq1_a2_ea2','t_esq1_a0']:
             dga_L[i] = gafit.dga_epi_fv(e0,epi,epifv,a,mLi,cov,**result['ga_min'].values)
         elif select in ['x_lo_a2','x_lo_aSa2','x_nlo_a0','x_nlo_a2','x_nlo_a2','x_nlo_aSa2','x_nlo_a2_ea2']:
             dga_L[i] = gafit.dfv_su2_nlo(epi,mLi,a,lam_cov=cov,**result['ga_min'].values)
     gn = params_plot['e_clr']['a12m220']
     mkr = params_plot['e_mrkr']['a12m220']
     ax.fill_between(xplot,ga_L-dga_L, ga_L+dga_L,color=gn,alpha=0.2)
     ax.plot(xplot,ga_L,color='k',linestyle='--',label=r'NLO $\chi$PT prediction')
     for ii,i in enumerate(i_fv):
         gi = data['ga_b0'][i]
         dgi = data['ga_bs'][:,i].std()
         ax.errorbar(xL[ii],gi,yerr=dgi,color=gn,mec=gn,mfc=gn,marker=mkr)
     ax.set_ylabel(r'$g_A$',fontsize=params_plot['fs'])
     ax.set_xlabel(r'$e^{-m_\pi L} / (m_\pi L)^{1/2}$',fontsize=params_plot['fs'])
     ax.axis([0.,0.024,1.2025,1.3125])
     ax.legend(loc=3,shadow=False,fancybox=True,fontsize=params_plot['fs'])
     ax.tick_params(axis='both', which='major', labelsize=16)
     ax.set_title(plt.get_figlabels()[-1].split(' ')[-1],fontdict={'fontsize':20,'verticalalignment':'top','horizontalalignment':'left'},x=0.05,y=0.9)
     plt.savefig('%s.pdf' %(plt.get_figlabels()[-1].replace(' ','_').replace('(','').replace(')','').replace('$','').replace('\\','').replace('.','').replace('^','').replace('/','')), transparent=True)
예제 #4
0
파일: exercise3.py 프로젝트: Gabmrtt/CMC
def exercise3():
    """ Main function to run for Exercise 3.

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

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

    # Create system
    sim = system_init()

    # Add external inputs to neural network
    sim.add_external_inputs_to_network(0.1 * np.ones((len(sim.time), 4)))

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

    # Obtain the states of the system after integration
    # res is np.asarray [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.asarray [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
    muscle_1_results = sim.sys.muscle_sys.muscle_1.results
    muscle_2_results = sim.sys.muscle_sys.muscle_2.results

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

    # 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)

    if DEFAULT["save_figures"] is False:
        # To start the animation
        simulation.animate()
        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)
예제 #5
0
 def list_open_figs(cls) -> Sequence[Tuple[str, Figure]]:
     """
     Returns all currently open figures and their labels via ``Figure.label``.
     Note that ``Figure.label`` is often empty in practice.
     """
     warnings.warn("open_fig_map will be removed; use list_open_figs instead")
     return [(label, plt.figure(label=label)) for label in plt.get_figlabels()]
예제 #6
0
def exercise1():

    if DEFAULT["1a"] is True:
        exercise1a()
    elif DEFAULT["1b"] is True:
        exercise1b()
    elif DEFAULT["1c"] is True:
        exercise1c()
    elif DEFAULT["1d"] is True:
        exercise1d()
    elif DEFAULT["1f"] is True:
        exercise1f()
    else:
        exercise1a()
        exercise1b()
        exercise1c()
        exercise1d()
        exercise1f()

    if DEFAULT["save_figures"] is False:
        plt.show()
    else:
        figures = plt.get_figlabels()
        print(figures)
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
            plt.close(fig)
예제 #7
0
def get_current_figure_size():
    
    if not plt.get_figlabels(): return
    
    fig = plt.gcf()
    
    return fig.get_size_inches()
예제 #8
0
	def shift_contour(self,distance):
		#Find numbers for current figures
		openfiglabels=plt.get_figlabels()
		openfignums=plt.get_fignums()
		#for each one, show the image again but shift in the AP direction and replot between the original image and the lines
		for i in range(len(openfiglabels)):
			plt.figure(openfignums[i])
			plt.imshow(self.images[:,:,openfiglabels[int(i)]],extent=[self.sortedIPP[i][0],self.sortedIPP[i][0]+self.cols*self.PS[0],self.sortedIPP[i][1]+self.rows*self.PS[0]+distance,self.sortedIPP[i][1]+distance],interpolation='nearest',cmap='gray',zorder=2)			
예제 #9
0
def test_figure_label():
    # pyplot figure creation, selection and closing with figure label and number
    plt.close('all')
    plt.figure('today')
    plt.figure(3)
    plt.figure('tomorow')
    plt.figure()
    plt.figure(0)
    plt.figure(1)
    plt.figure(3)
    assert_equal(plt.get_fignums(), [0, 1, 3, 4, 5])
    assert_equal(plt.get_figlabels(), ['', 'today', '', 'tomorow', ''])
    plt.close(10)
    plt.close()
    plt.close(5)
    plt.close('tomorow')
    assert_equal(plt.get_fignums(), [0, 1])
    assert_equal(plt.get_figlabels(), ['', 'today'])
예제 #10
0
 def open_fig_map(cls) -> Mapping[str, Figure]:
     """
     Returns all currently open figures as a dict mapping their labels ``Figure.label`` to their instances.
     Note that ``Figure.label`` is often empty in practice.
     """
     warnings.warn(
         "open_fig_map will be removed; use list_open_figs instead", DeprecationWarning
     )
     return {label: plt.figure(label=label) for label in plt.get_figlabels()}
예제 #11
0
def test_figure_label():
    # pyplot figure creation, selection and closing with figure label and number
    plt.close('all')
    plt.figure('today')
    plt.figure(3)
    plt.figure('tomorrow')
    plt.figure()
    plt.figure(0)
    plt.figure(1)
    plt.figure(3)
    assert_equal(plt.get_fignums(), [0, 1, 3, 4, 5])
    assert_equal(plt.get_figlabels(), ['', 'today', '', 'tomorrow', ''])
    plt.close(10)
    plt.close()
    plt.close(5)
    plt.close('tomorrow')
    assert_equal(plt.get_fignums(), [0, 1])
    assert_equal(plt.get_figlabels(), ['', 'today'])
예제 #12
0
def test_figure_label():
    # pyplot figure creation, selection and closing with figure label and number
    plt.close("all")
    plt.figure("today")
    plt.figure(3)
    plt.figure("tomorrow")
    plt.figure()
    plt.figure(0)
    plt.figure(1)
    plt.figure(3)
    assert_equal(plt.get_fignums(), [0, 1, 3, 4, 5])
    assert_equal(plt.get_figlabels(), ["", "today", "", "tomorrow", ""])
    plt.close(10)
    plt.close()
    plt.close(5)
    plt.close("tomorrow")
    assert_equal(plt.get_fignums(), [0, 1])
    assert_equal(plt.get_figlabels(), ["", "today"])
예제 #13
0
def redraw(event):
    """Redraw the plot on a resize event"""
    if  np.size(plt.get_figlabels()):
        #Need to check if figure is closed or not and only then do the following
        #operations. Else, the following operations will create a new figure
        ax.clear()
        drawRectangle(ax)
        fig.canvas.draw()
    else:
        pass
예제 #14
0
 def set_output_window_names(self):
     import matplotlib.pyplot as plt  # unfortunately need to import again
     """
     Change the output name if more than one plot of the same workspace
     """
     window_title = self.canvas.get_window_title()
     workspace_name = window_title.rsplit('-', 1)[0]
     for open_figures in plt.get_figlabels():
         if open_figures != window_title and open_figures.rsplit('-', 1)[0] == workspace_name:
             self.setOutputName(window_title)
     return None
예제 #15
0
def test_figure_label():
    # pyplot figure creation, selection, and closing with label/number/instance
    plt.close('all')
    fig_today = plt.figure('today')
    plt.figure(3)
    plt.figure('tomorrow')
    plt.figure()
    plt.figure(0)
    plt.figure(1)
    plt.figure(3)
    assert plt.get_fignums() == [0, 1, 3, 4, 5]
    assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', '']
    plt.close(10)
    plt.close()
    plt.close(5)
    plt.close('tomorrow')
    assert plt.get_fignums() == [0, 1]
    assert plt.get_figlabels() == ['', 'today']
    plt.figure(fig_today)
    assert plt.gcf() == fig_today
    with pytest.raises(ValueError):
        plt.figure(Figure())
예제 #16
0
def exercise3():

    time_param = TimeParameters(time_start=0, time_stop=10., time_step=0.001)
    exercise3a(time_param)
    exercise3b(time_param)

    if DEFAULT["save_figures"]:
        figures = plt.get_figlabels()
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
    plt.show()
예제 #17
0
def exercise1():
    #exercise1a()
    exercise1d()

    if DEFAULT["save_figures"] is False:
        plt.show()
    else:
        figures = plt.get_figlabels()
        print(figures)
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
            plt.close(fig)
예제 #18
0
def save_open_images(outputpath,loopcounter=''):
    ''' Saves all open images in files named after the image titles,
    and the loop counter.

    _Parameters_:

    outputpath:     path to folder where file is saved

    loopcounter:    integer, counter of robot steps (used for naming the images

    _Returns_: Nothing
    '''
    for i in plt.get_figlabels():
        plt.figure(i)
        plt.savefig(outputpath+str(loopcounter)+"_"+str(i)+'.png')
예제 #19
0
def exercise2():
    """ Main function to run for Exercise 2.

    """
    exercise2b()

    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)
예제 #20
0
def save_open_images(outputpath,loopcounter=''):
    ''' Saves all open images in files named after the image titles,
    and the loop counter.

    _Parameters_:

    outputpath:     path to folder where file is saved

    loopcounter:    integer, counter of robot steps (used for naming the images

    _Returns_: Nothing
    '''
    for i in plt.get_figlabels():
        plt.figure(i)
        plt.savefig(outputpath+str(loopcounter)+"_"+str(i)+'.png')
예제 #21
0
파일: plotter.py 프로젝트: yawudede/volkscv
    def plot(self, func=None, figsize=(15, 15), dpi=150, **kwargs):
        exist_figlabels = plt.get_figlabels()
        if self.text in exist_figlabels:
            self.text = self.text + '_copy'
        self.figure(self.text, figsize=figsize, dpi=dpi)
        plt.clf()
        self.title(self.text)
        for idx, p in enumerate(self.processor):
            ax = plt.subplot(self.row, self.col, idx + 1)
            ax.set_title(str(self.category[idx]))
            if func is None:
                p.plot()
            else:
                p.plot(func, **kwargs)

        get_fig()
예제 #22
0
    def show(self):
        import matplotlib.pyplot as plt
        """
        Override the base class method. Initialise the peak editing tool.
        """
        allowed_spectra = self._get_allowed_spectra()
        table = self._get_table_workspace()

        if allowed_spectra:
            self._add_spectra(allowed_spectra)
        elif table:
            self.addAllowedTableWorkspace(table)
        else:
            self.toolbar_manager.toggle_fit_button_checked()
            logger.warning(
                "Cannot open fitting tool: No valid workspaces to fit to.")
            return

        super(FitPropertyBrowser, self).show()
        self.tool = FitInteractiveTool(
            self.canvas,
            self.toolbar_manager,
            current_peak_type=self.defaultPeakType(),
            default_background=self.defaultBackgroundType())
        self.tool.fit_range_changed.connect(self.set_fit_range)
        self.tool.peak_added.connect(self.peak_added_slot)
        self.tool.peak_moved.connect(self.peak_moved_slot)
        self.tool.peak_fwhm_changed.connect(self.peak_fwhm_changed_slot)
        self.tool.peak_type_changed.connect(self.setDefaultPeakType)
        self.tool.add_background_requested.connect(self.add_function_slot)
        self.tool.add_other_requested.connect(self.add_function_slot)

        self.set_fit_bounds(self.get_fit_bounds())
        self.set_fit_range(self.tool.fit_range.get_range())

        self.setPeakToolOn(True)
        self.canvas.draw()

        # change the output name if more than one plot of the same workspace
        window_title = self.canvas.get_window_title()
        workspace_name = window_title.rsplit('-', 1)[0]
        for open_figures in plt.get_figlabels():
            if open_figures != window_title and open_figures.rsplit(
                    '-', 1)[0] == workspace_name:
                self.setOutputName(window_title)
예제 #23
0
def get_fig():
    """ get the current plt.figure and saved to obj (Collect)

    Examples:
        >>> import random
        >>> def show():
        >>>     plt.figure('example')
        >>>     plt.hist([random.randint(0,100) for _ in range(100)])
        >>>     get_fig()
        >>> show()
        >>> cc = get_collect()
        >>> cc._infos.get('example')
    """

    collect = get_collect()
    name = plt.get_figlabels()[-1]
    ff = plt.gcf()
    collect.update_info(name, ff)
예제 #24
0
    def __clear_plots(self):
        """
        Close all existing plots
        """
        #import pdb; pdb.set_trace()

        allLabels = plt.get_figlabels()
        for i in range(len(allLabels)):
            try:
                # Because of the NBagg backend we need to try to close
                # each one, it'll fail but then we can close all
                plt.close()
            except ValueError:
                pass

        try:
            plt.close('all')
        except ValueError:
            pass
예제 #25
0
def save_results():
    image_path = Path(__file__).parent.joinpath("images/")
    #print(image_path)
    #print(image_path.joinpath("hi/"))
    i = 1
    while image_path.joinpath(f"{i}").exists():
        i = i + 1

    print(i)
    image_path = image_path.joinpath(f"{i}")
    print(f"will save at {image_path}.")
    image_path.mkdir()
    figs = [plt.figure(n) for n in plt.get_fignums()]
    labels = [n for n in plt.get_figlabels()]

    for i, fig in enumerate(figs):
        fig.savefig(image_path.joinpath(f"{labels[i]}.pdf"), format='pdf')

    config_str = ""
    config_str += "===" * 30 + "\n"
    config_str += "Data Config options:\n\n"
    for v in dir(c):
        if v[0] == '_': continue
        s = eval('c.%s' % (v))
        config_str += "  {:25}\t{}\n".format(v, s)

    config_str += "\n"
    config_str += "===" * 30 + "\n"
    config_str += "Config options:\n\n"

    for v in dir(c):
        if v[0] == '_': continue
        s = eval('c.%s' % (v))
        config_str += "  {:25}\t{}\n".format(v, s)

    config_str += "===" * 30 + "\n"

    with image_path.joinpath(
            f"settings{c.configuration}_{c.run_name}.txt").open(
                "w", encoding="utf-8") as f:
        f.write(config_str)
예제 #26
0
def exercise1():
    plt.close("all")
    pylog.info("Start exercise 1")
    time_param = TimeParameters(time_start=0.0,
                                time_stop=0.2,
                                time_step=0.001,
                                time_stabilize=0.2)

    exercise1a(time_param)
    exercise1b(time_param)
    exercise1c(time_param)
    time_param.t_stop = 0.3  # change time parameters for the second part
    exercise1d(time_param)
    exercise1e(time_param)

    if DEFAULT["save_figures"]:
        figures = plt.get_figlabels()
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
    plt.show()
예제 #27
0
def exercise3():
    """ 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

    # 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.5  # 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)))
    # sim.add_external_inputs_to_network(ext_in)

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

    # 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
    plt.figure('Pendulum')
    plt.title('Pendulum Phase')
    plt.plot(res[:, 0], res[:, :2])
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad.s]')
    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()
예제 #28
0
 def check_open_fig(self):
     # checks if other bd plots are open and closes them
     labels = plt.get_figlabels()
     if self._seq not in labels: plt.close()
예제 #29
0
       def descriptor(self, doc):
           
        self._descriptors[doc['uid']] = doc
        stream_name = doc.get('name', 'primary')  # fall back for old docs

        if stream_name not in self._stream_names_seen:
            self._stream_names_seen.add(stream_name)
            if self._table_enabled:
                print("New stream: {!r}".format(stream_name))

        columns = hinted_fields(doc)

        # ## This deals with old documents. ## #

        if stream_name == 'primary' and self._cleanup_motor_heuristic:
            # We stashed object names in self.dim_fields, which we now need to
            # look up the actual fields for.
            self._cleanup_motor_heuristic = False
            fixed_dim_fields = []
            for obj_name in self.dim_fields:
                # Special case: 'time' can be a dim_field, but it's not an
                # object name. Just add it directly to the list of fields.
                if obj_name == 'time':
                    fixed_dim_fields.append('time')
                    continue
                try:
                    fields = doc.get('hints', {}).get(obj_name, {})['fields']
                except KeyError:
                    fields = doc['object_keys'][obj_name]
                fixed_dim_fields.extend(fields)
            self.dim_fields = fixed_dim_fields

        # ## TABLE ## #

        if stream_name == self.dim_stream:
            # Ensure that no independent variables ('dimensions') are
            # duplicated here.
            columns = [c for c in columns if c not in self.all_dim_fields]

            if self._table_enabled:
                # plot everything, independent or dependent variables
                self._table = LiveTable(list(self.all_dim_fields) + columns)
                self._table('start', self._start_doc)
                self._table('descriptor', doc)

        # ## DECIDE WHICH KIND OF PLOT CAN BE USED ## #

        if not self._plots_enabled:
            return
        if stream_name in self.noplot_streams:
            return
        if not columns:
            return
        if ((self._start_doc.get('num_points') == 1) and
                (stream_name == self.dim_stream) and
                self.omit_single_point_plot):
            return

        # This is a heuristic approach until we think of how to hint this in a
        # generalizable way.
        if stream_name == self.dim_stream:
            dim_fields = self.dim_fields
        else:
            dim_fields = ['time']  # 'time' once LivePlot can do that

        # Create a figure or reuse an existing one.

        fig_name = '{} vs {}'.format(' '.join(sorted(columns)),
                                     ' '.join(sorted(dim_fields)))
        if self.overplot and len(dim_fields) == 1:
            # If any open figure matches 'figname {number}', use it. If there
            # are multiple, the most recently touched one will be used.
            pat1 = re.compile('^' + fig_name + '$')
            pat2 = re.compile('^' + fig_name + r' \d+$')
            for label in plt.get_figlabels():
                if pat1.match(label) or pat2.match(label):
                    fig_name = label
                    break
        else:
            if plt.fignum_exists(fig_name):
                # Generate a unique name by appending a number.
                for number in itertools.count(2):
                    new_name = '{} {}'.format(fig_name, number)
                    if not plt.fignum_exists(new_name):
                        fig_name = new_name
                        break
        ndims = len(dim_fields)
        if not 0 < ndims < 3:
            # we need 1 or 2 dims to do anything, do not make empty figures
            return

        if self._fig_factory:
            fig = self._fig_factory(fig_name)
        else:
            fig = plt.figure(fig_name)
        if not fig.axes:
            # This is apparently a fresh figure. Make axes.
            # The complexity here is due to making a shared x axis. This can be
            # simplified when Figure supports the `subplots` method in a future
            # release of matplotlib.
            fig.set_size_inches(6.4, min(950, len(columns) * 400) / fig.dpi)
            for i in range(len(columns)):
                if i == 0:
                    ax = fig.add_subplot(len(columns), 1, 1 + i)
                    if ndims == 1:
                        share_kwargs = {'sharex': ax}
                    elif ndims == 2:
                        share_kwargs = {'sharex': ax, 'sharey': ax}
                    else:
                        raise NotImplementedError("we now support 3D?!")
                else:
                    ax = fig.add_subplot(len(columns), 1, 1 + i,
                                         **share_kwargs)
        axes = fig.axes

        # ## LIVE PLOT AND PEAK ANALYSIS ## #

        if ndims == 1:
            self._live_plots[doc['uid']] = {}
            self._peak_stats[doc['uid']] = {}
            x_key, = dim_fields
            for y_key, ax in zip(columns, axes):
                dtype = doc['data_keys'][y_key]['dtype']
                if dtype not in ('number', 'integer'):
                    warn("Omitting {} from plot because dtype is {}"
                         "".format(y_key, dtype))
                    continue
                # Create an instance of LivePlot and an instance of PeakStats.
                live_plot = LivePlotPlusPeaks(y=y_key, x=x_key, ax=ax,
                                              peak_results=self.peaks)
                live_plot('start', self._start_doc)
                live_plot('descriptor', doc)
                peak_stats = PeakStats(x=x_key, y=y_key)
                peak_stats('start', self._start_doc)
                peak_stats('descriptor', doc)

                # Stash them in state.
                self._live_plots[doc['uid']][y_key] = live_plot
                self._peak_stats[doc['uid']][y_key] = peak_stats

            for ax in axes[:-1]:
                ax.set_xlabel('')
        elif ndims == 2:
            # Decide whether to use LiveGrid or LiveScatter. LiveScatter is the
            # safer one to use, so it is the fallback..
            gridding = self._start_doc.get('hints', {}).get('gridding')
            if gridding == 'rectilinear':
                self._live_grids[doc['uid']] = {}
                slow, fast = dim_fields
                try:
                    extents = self._start_doc['extents']
                    shape = self._start_doc['shape']
                except KeyError:
                    warn("Need both 'shape' and 'extents' in plan metadata to "
                         "create LiveGrid.")
                else:
                    data_range = np.array([float(np.diff(e)) for e in extents])
                    y_step, x_step = data_range / [max(1, s - 1) for s in shape]
                    adjusted_extent = [extents[1][0] - x_step / 2,
                                       extents[1][1] + x_step / 2,
                                       extents[0][0] - y_step / 2,
                                       extents[0][1] + y_step / 2]
                    for I_key, ax in zip(columns, axes):
                        # MAGIC NUMBERS based on what tacaswell thinks looks OK
                        data_aspect_ratio = np.abs(data_range[1]/data_range[0])
                        MAR = 2
                        if (1/MAR < data_aspect_ratio < MAR):
                            aspect = 'equal'
                            ax.set_aspect(aspect, adjustable='box-forced')
                        else:
                            aspect = 'auto'
                            ax.set_aspect(aspect, adjustable='datalim')

                        live_grid = LiveGrid(shape, I_key,
                                             xlabel=fast, ylabel=slow,
                                             extent=adjusted_extent,
                                             aspect=aspect,
                                             ax=ax)

                        live_grid('start', self._start_doc)
                        live_grid('descriptor', doc)
                        self._live_grids[doc['uid']][I_key] = live_grid
            else:
                self._live_scatters[doc['uid']] = {}
                x_key, y_key = dim_fields
                for I_key, ax in zip(columns, axes):
                    try:
                        extents = self._start_doc['extents']
                    except KeyError:
                        xlim = ylim = None
                    else:
                        xlim, ylim = extents
                    live_scatter = LiveScatterHxn(x_key, y_key, I_key,
                                               xlim=xlim, ylim=ylim,
                                               # Let clim autoscale.
                                               ax=ax)
                     
                    live_scatter('start', self._start_doc)
                    live_scatter('descriptor', doc)
                    self._live_scatters[doc['uid']][I_key] = live_scatter
        else:
            raise NotImplementedError("we do not support 3D+ in BEC yet "
                                      "(and it should have bailed above)")
        try:
            fig.tight_layout()
        except ValueError:
            pass
예제 #30
0
def exercise3():
    """ 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 = .5  # To change the default length of the pendulum
    P_params.mass = 5.  # To change the default mass of the pendulum
    pendulum = Pendulum(P_params)  # Instantiate Pendulum object

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

    biolog.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
    biolog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(), M2.parameters.showParameters()))
    ###
    ########################################## 3a ########################################
    #
    #    # Define a huge mass, such that the pendulum goes up to pi/2 and up t -pi/2
    #    P_params.mass = 15000.
    #    # Defines 3 different origins and 3 different insertions for each muscle
    #    origins1 = [-0.01, -0.05, -0.10, -0.15, -0.2]
    #    origins2 = map(lambda x: -(x), origins1)
    #    insertions1 = [-0.15, -0.20, -0.25, -0.30]
    #    insertions2 = insertions1[:] # Just for visibility
    #    legendsertion =np.array(['Insertion at -15 cm', 'Insertion at -20 cm', 'Insertion at -25 cm', 'Insertion at -30 cm'])
    #    legleg = np.array(['Insertion at -15 cm', 'Insertion at -15 cm', 'Insertion at -20 cm', 'Insertion at -20 cm', 'Insertion at -25 cm', 'Insertion at -25 cm', 'Insertion at -30 cm', 'Insertion at -30 cm'])
    #    cols = ('blue', 'red', 'olive', 'purple')
    ##    length1 = np.array()
    #
    #    for o1,o2 in zip(origins1, origins2):
    #        fig, (ax1, ax2) = plt.subplots(1,2, sharex = True)
    #        fig.suptitle('Origin of muscles: o1 = {}, o2 = {}'.format(o1,o2), fontsize='26')
    #        for i,j in enumerate(insertions1):
    #            # Define Muscle Attachment points
    #            m1_origin = np.array([o1, 0.0])  # Origin of Muscle 1
    #            m1_insertion = np.array([0.0, j])  # Insertion of Muscle 1
    #
    #            m2_origin = np.array([o2, 0.0])  # Origin of Muscle 2
    #            m2_insertion = np.array([0.0, j])  # 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 #####
    #
    #            dt=0.01
    #            t_max = 1.  # Maximum simulation time
    #            time = np.arange(0., t_max, dt)  # Time vector
    #
    #
    #
    #            ##### Model Initial Conditions #####
    #            x0_P = np.array([np.pi/2. - 0.00001,0.])  # Pendulum initial condition
    #
    #            # Muscle Model initial condition
    #            x0_M = np.array([0., M1.l_CE, 0., M2.l_CE])
    #
    #            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))*0.05
    #            act2=np.ones((len(time),1))*0.05
    #
    #            activations = np.hstack((act1, act2))
    #
    #            # 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
    #
    #            # 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 paramters of the muscle
    #            # Check SystemSimulation.py results_muscles() method for more information
    #            res_muscles = sim.results_muscles()
    #            length1 = np.array(map(lambda x: np.sqrt(o1**2. + j**2. + 2.*o1*j*np.sin(x)), res[:,1])) # muscle 1 length
    #            length2 = np.array(map(lambda x: np.sqrt(o2**2. + j**2. + 2.*o2*j*np.sin(x)), res[:,1])) # muscle 2 length
    #            # moment arm of muscles calculation
    #            h1lambda = np.array(map(lambda x: np.abs(o1)*np.abs(j)*np.cos(x), res[:,1]))
    #            h2lambda = np.array(map(lambda x: np.abs(o2)*np.abs(j)*np.cos(x), res[:,1]))
    #            h1 = h1lambda/length1
    #            h2 = h2lambda/length2
    #            # Plotting the result for the current origins
    #            ax1.plot(res[:, 1], length1)
    #            ax2.plot(res[:, 1], h1)
    #            if o1 == -0.1:
    #                plt.figure('Muscles\' moment arm for insertions at {} and {}'.format(o1, o2))
    #                if j == -0.15:
    #                    temp = 0.0
    #                    plt.plot(res[:, 1], h1, color=(1.0, temp, 0.0), linestyle = ':')
    #                    plt.plot(res[:, 1], h2, color=(temp, .5, 1.), linestyle = ':')
    #                elif j == -0.2:
    #                    temp = 0.3
    #                    plt.plot(res[:, 1], h1, color=(1.0, temp, 0.0), linestyle = '--')
    #                    plt.plot(res[:, 1], h2, color=(temp, .5, 1.), linestyle = '--')
    #                elif j == -0.25:
    #                    temp = 0.7
    #                    plt.plot(res[:, 1], h1, color=(1.0, temp, 0.0), linestyle = '-.')
    #                    plt.plot(res[:, 1], h2, color=(temp, .5, 1.), linestyle = '-.')
    #                else:
    #                    temp = 1.0
    #                    plt.plot(res[:, 1], h1, color=(1.0, temp, 0.0))
    #                    plt.plot(res[:, 1], h2, color=(temp, .5, 1.))
    #                plt.legend(legleg)
    #                plt.xlabel('Pendulum position [rad]', fontsize = '18')
    #                plt.ylabel('Muscle moment arm [m]', fontsize = '18')
    #                plt.title('Muscles\' moment arm for insertions at {} and {}.\nRedish = muscle 1 (left), Blueish = muscle 2 (right)'.format(o1, o2), fontsize='26')
    #                plt.grid('ON')
    #
    #        ax1.legend(legendsertion)
    #        ax2.legend(legendsertion)
    #        ax1.set_xlabel('Position [rad]', fontsize='18')
    #        ax2.set_xlabel('Position [rad]', fontsize='18')
    #        ax1.set_ylabel('Muscle length [m]', fontsize='18') # Here we computed length 1 but muscle 2 has the same behaviour for identical params
    #        ax2.set_ylabel('Muscle moment arm [m]', fontsize='18')
    #        ax1.set_title('Muscle-tendon unit length in terms of pendulum position', fontsize='20')
    #        ax2.set_title('Muscle\'s moment arm', fontsize='20')
    #        ax1.grid()
    #        ax2.grid()
    #
    ######################################## End OF 3a ########################################
    ##
    ########################################## 3b ########################################
    #
    #    # Define a huge mass, such that the pendulum goes up to pi/2 and up t -pi/2
    #    P_params.mass = 1500.
    #    # Defines 3 different origins and 3 different insertions for each muscle
    #    origins1 = [-0.01, -0.05, -0.10, -0.15, -0.2]
    #    origins2 = map(lambda x: -(x), origins1)
    #    insertions1 = [-0.15, -0.20, -0.25, -0.30]
    #    insertions2 = insertions1[:] # Just for visibility
    #    legendsertion =np.array(['Insertion at -15 cm', 'Insertion at -20 cm', 'Insertion at -25 cm', 'Insertion at -30 cm'])
    #    legleg = np.array(['Insertion at -15 cm', 'Insertion at -15 cm', 'Insertion at -20 cm', 'Insertion at -20 cm', 'Insertion at -25 cm', 'Insertion at -25 cm', 'Insertion at -30 cm', 'Insertion at -30 cm'])
    #    cols = ('blue', 'red', 'olive', 'purple')
    ##    length1 = np.array()
    #
    #    for o1,o2 in zip(origins1, origins2):
    #        fig, (ax1, ax2) = plt.subplots(1,2, sharex = True)
    #        fig.suptitle('Origin of muscles - passive: o1 = {}, o2 = {}'.format(o1,o2), fontsize='26')
    #        for i,j in enumerate(insertions1):
    #            # Define Muscle Attachment points
    #            m1_origin = np.array([o1, 0.0])  # Origin of Muscle 1
    #            m1_insertion = np.array([0.0, j])  # Insertion of Muscle 1
    #
    #            m2_origin = np.array([o2, 0.0])  # Origin of Muscle 2
    #            m2_insertion = np.array([0.0, j])  # 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 #####
    #
    #            dt=0.01
    #            t_max = 1.  # Maximum simulation time
    #            time = np.arange(0., t_max, dt)  # Time vector
    #
    #
    #
    #            ##### Model Initial Conditions #####
    #            x0_P = np.array([np.pi/2. - 0.00001,0.])  # Pendulum initial condition
    #
    #            # Muscle Model initial condition
    #            x0_M = np.array([0., M1.l_CE, 0., M2.l_CE])
    #
    #            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))*0.00 # Passive muscles, unactivated.
    #            act2=np.ones((len(time),1))*0.00
    #
    #            activations = np.hstack((act1, act2))
    #
    #            # 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
    #
    #            # 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 paramters of the muscle
    #            # Check SystemSimulation.py results_muscles() method for more information
    #            res_muscles = sim.results_muscles()
    #            length1 = np.array(map(lambda x: np.sqrt(o1**2. + j**2. + 2.*o1*j*np.sin(x)), res[:,1])) # muscle 1 length
    #            length2 = np.array(map(lambda x: np.sqrt(o2**2. + j**2. + 2.*o2*j*np.sin(x)), res[:,1])) # muscle 2 length
    #            # moment arm of muscles calculation
    #            h1lambda = np.array(map(lambda x: np.abs(o1)*np.abs(j)*np.cos(x), res[:,1]))
    #            h2lambda = np.array(map(lambda x: np.abs(o2)*np.abs(j)*np.cos(x), res[:,1]))
    #            h1 = h1lambda/length1
    #            h2 = h2lambda/length2
    #            # Plotting the result for the current origins
    #            ax1.plot(res[:, 1], length1)
    #            ax2.plot(res[:, 1], h1)
    #            if o1 == -0.1:
    #                plt.figure('Muscles\' moment arm for insertions at {} and {} - passive'.format(o1, o2))
    #                if j == -0.15:
    #                    temp = 0.0
    #                    plt.plot(res[:, 1], h1, color=(1.0, temp, 0.0), linestyle = ':')
    #                    plt.plot(res[:, 1], h2, color=(temp, .5, 1.), linestyle = ':')
    #                elif j == -0.2:
    #                    temp = 0.3
    #                    plt.plot(res[:, 1], h1, color=(1.0, temp, 0.0), linestyle = '--')
    #                    plt.plot(res[:, 1], h2, color=(temp, .5, 1.), linestyle = '--')
    #                elif j == -0.25:
    #                    temp = 0.7
    #                    plt.plot(res[:, 1], h1, color=(1.0, temp, 0.0), linestyle = '-.')
    #                    plt.plot(res[:, 1], h2, color=(temp, .5, 1.), linestyle = '-.')
    #                else:
    #                    temp = 1.0
    #                    plt.plot(res[:, 1], h1, color=(1.0, temp, 0.0))
    #                    plt.plot(res[:, 1], h2, color=(temp, .5, 1.))
    #                plt.legend(legleg)
    #                plt.xlabel('Pendulum position [rad]', fontsize = '18')
    #                plt.ylabel('Muscle moment arm [m]', fontsize = '18')
    #                plt.title('Muscles\' moment arm for insertions at {} and {} - passive.\nRedish = muscle 1 (left), Blueish = muscle 2 (right)'.format(o1, o2), fontsize='26')
    #                plt.grid('ON')
    #
    #        ax1.legend(legendsertion)
    #        ax2.legend(legendsertion)
    #        ax1.set_xlabel('Position [rad]', fontsize='18')
    #        ax2.set_xlabel('Position [rad]', fontsize='18')
    #        ax1.set_ylabel('Muscle length [m]', fontsize='18') # Here we computed length 1 but muscle 2 has the same behaviour for identical params
    #        ax2.set_ylabel('Muscle moment arm [m]', fontsize='18')
    #        ax1.set_title('Muscle-tendon unit length in terms of pendulum position', fontsize='20')
    #        ax2.set_title('Muscle\'s moment arm', fontsize='20')
    #        ax1.grid()
    #        ax2.grid()
    #
    ######################################## End OF 3b ########################################
    ######################################## Part 3c,d,e,f ##########################################

    LC = True  # Limit Cycle ON => LC True, Limit Cyle OFF => LC False

    if LC == True:
        P_params.mass = 10.
    else:
        P_params.mass = 100.

    # For point 3f, we changed max forces up here (line 55 and 57)

    # 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 #####

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

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

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

    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.arange(0., t_max, dt)
    act2 = np.arange(0., t_max, dt)

    if LC == True:
        act1 = (np.sin(2. * np.pi / t_max * 5. * act1) +
                1.) * .5  # acts = time
        act2 = (
            -np.sin(2. * np.pi / t_max * 5. * act2) + 1.
        ) * .5  # by increasing frequency, we don't let the time to gravity to make its office and contribute to the system's equilibrium, so the amplitude of the pendulum diminues.
        act1 = act1.reshape(len(act1), 1)
        act2 = act2.reshape(len(act2), 1)
    else:
        act1 = np.ones((len(time), 1)) * 0.25
        act2 = np.ones((len(time), 1)) * 0.25

    activations = np.hstack((act1, act2))
    # 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

    # 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 paramters of the muscle
    # Check SystemSimulation.py results_muscles() method for more information
    res_muscles = sim.results_muscles()

    # Plotting the results
    plt.figure('Pendulum')
    #    plt.title('Pendulum Phase')
    plt.title('Limit cycle behaviour for a max force of {} N'.format(M1.F_max),
              fontsize='22')
    #    plt.plot(res[:, 1], res[:, 2])
    plt.plot(time, res[:, 1])
    #    plt.xlabel('Position [rad]')
    #    plt.ylabel('Velocity [rad.s]')
    plt.xlabel('Time [s]')
    plt.ylabel('Pendulum position [rad]')
    plt.grid()

    # Plotting activation
    legact = ("Muscle 1 - left", "Muscle 2 - right")
    plt.figure('Activations')
    #    plt.title('Pendulum Phase')
    plt.title('Muscle activation patterns', fontsize='22')
    #    plt.plot(res[:, 1], res[:, 2])
    plt.plot(time, act1, color='red')
    plt.plot(time, act2, color='green')
    #    plt.xlabel('Position [rad]')
    #    plt.ylabel('Velocity [rad.s]')
    plt.xlabel('Time [s]')
    plt.ylabel('Activation [-]')
    plt.legend(legact)
    plt.grid()

    if DEFAULT["save_figures"] is False:
        plt.show()
    else:
        figures = plt.get_figlabels()
        biolog.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, pendulum, muscles)
    # To start the animation
    simulation.animate()
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
    P_params.PERTURBATION = True
    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.tau = [0.02, 0.02, 0.1, 0.1]
    N_params.b = [3.0, 3.0, -3.0, -3.0]
    N_params.D = 1.0  # To change a network parameter
    N_params.w = np.asarray([[0.0, -5.0, -5.0, 0.0], [-5.0, 0.0, 0.0, -5.0],
                             [5.0, -5.0, 0.0, 0.0], [-5.0, 5.0, 0.0, 0.0]])
    # 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
    sys.add_neural_system(
        neural_network)  # Add the neural network to the system

    ##### 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.5, 0], [-0.25, -0.25], [0., 0.],
                     [0.5, 0]])  # Pendulum initial condition

    for i in x0_P:
        # Muscle Model initial condition
        x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

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

        x0 = np.concatenate((i, 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

        #    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()

        # 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()
예제 #32
0
def exercise2():
    """ Main function to run for Exercise 2.
    """

    # 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()))

    # 2a : set of muscle 1 attachment points
    
    m1_origin = np.array([[-0.17, 0.0]])  # Origin of Muscle 1
    m1_insertion = np.array([[0.0, -0.17], [0.0, -0.3], [0.0, -0.4], [0.0, -0.5]])  # Insertion of Muscle 1
    
    theta = np.linspace(-np.pi/2,np.pi/2)
        
    m_lengths = np.zeros((len(m1_insertion),len(theta)))
    m_moment_arms = np.zeros((len(m1_insertion),len(theta)))
    leg=[]
    for i in range(0,len(m1_insertion)):
        m_lengths[i,:]=np.sqrt(m1_origin[0,0]**2 + m1_insertion[i,1]**2 +
                         2 * np.abs(m1_origin[0,0]) * np.abs(m1_insertion[i,1]) * np.sin(theta))
        m_moment_arms[i,:]= m1_origin[0,0] * m1_insertion[i,1] * np.cos(theta) / m_lengths[i,:]
        leg.append('Origin: {}m, Insertion: {}m'.format(m1_origin[0,0],m1_insertion[i,1]))
        
    # Plotting
    plt.figure('2a length')
    plt.title('Length of M1 with respect to the position of the limb') 
    for i in range(0,len(m_lengths)):
        plt.plot(theta*180/np.pi, m_lengths[i,:])
    plt.plot((theta[0]*180/np.pi,theta[len(theta)-1]*180/np.pi),(0.11,0.11), ls='dashed')
    leg.append('l_opt')
    plt.plot((theta[0]*180/np.pi,theta[len(theta)-1]*180/np.pi),(0.13,0.13), ls='dashed')
    leg.append('l_slack') 
    plt.xlabel('Position [deg]')
    plt.ylabel('Muscle length [m]')
    plt.legend(leg)
    plt.grid()
    plt.savefig('2_a_length.png')
    
    plt.figure('2a moment')
    plt.title('Moment arm over M1 with respect to the position of the limb')
    for i in range(0,len(m_moment_arms)):
        plt.plot(theta*180/np.pi, m_moment_arms[i,:])
    plt.xlabel('Position [deg]')
    plt.ylabel('Moment arm [m]')
    plt.legend(leg)
    plt.grid()
    plt.savefig('2_a_moment.png')
    
    
    # 2b : simple activation wave forms
        
    # Muscle 2 attachement point
    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[0,:], m1_insertion[0,:]]),
                   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 = 2.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

    sin_frequency = 2 #Hz
    amp_stim = 1
    phase_shift = np.pi
    act1 = np.zeros((len(time),1))
    act2 = np.zeros((len(time),1))
    for i in range(0,len(time)):
        act1[i,0] = amp_stim*(1+np.sin(2*np.pi*sin_frequency*time[i]))/2
        act2[i,0] = amp_stim*(1+ np.sin(2*np.pi*sin_frequency*time[i] + phase_shift))/2
    
    plt.figure('2b activation')
    plt.plot(time,act1)
    plt.plot(time,act2)
    plt.legend(["Activation for muscle 1", "Activation for muscle 2"])
    plt.title('Activation for muscle 1 and 2 with simple activation wave forms')
    plt.xlabel("Time [s]")
    plt.ylabel("Activation")
    plt.savefig('2_b_activation.png')
    plt.show()

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

    # 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()
    
    # Plotting the results
    plt.figure('2b phase')
    plt.title('Pendulum Phase')
    plt.plot(res[:, 1], res[:, 2])
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad/s]')
    plt.grid()
    plt.savefig('2_b_phase.png')
    plt.show()
    
    plt.figure('2b oscillations')
    plt.title('Pendulum Oscillations')
    plt.plot(time,res[:, 1])
    plt.xlabel('Time [s]')
    plt.ylabel('Position [rad]')
    plt.grid()
    plt.savefig('2_b_oscillations.png')
    plt.show()
    
    # 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)
    
 # 2c : relationship between stimulation frequency and amplitude
    
    # Effect of frequency
    stim_frequency_range = np.array([0.05,0.1,0.5,1,5,10,50,100,500]) #Hz
    stim_amp = 1
    phase_shift = np.pi
    frequency_pend=np.zeros(len(stim_frequency_range))
    amplitude_pend=np.zeros(len(stim_frequency_range))
    
    for j,stim_frequency in enumerate(stim_frequency_range):
        period = 1/stim_frequency
        t_max = 10*period  # Maximum simulation time
        time = np.arange(0., t_max, 0.001*period)  # Time vector

        act1 = np.zeros((len(time),1))
        act2 = np.zeros((len(time),1))
        act1[:,0] = stim_amp*(1 + np.sin(2*np.pi*stim_frequency*time))/2
        act2[:,0] = stim_amp*(1+ np.sin(2*np.pi*stim_frequency*time + phase_shift))/2
        activations = np.hstack((act1, act2))
        sim.add_muscle_activations(activations)
        sim.initalize_system(x0, time)  # Initialize the system state
        sim.simulate()
        res = sim.results()  
        # computing the frequency and amplitude
        angular_position = res[:,1]
        signal_stat = angular_position[int(len(angular_position)/2):len(angular_position)]
        index_zeros = np.where(np.diff(np.sign(signal_stat)))[0]
        deltas = np.diff(index_zeros)
        delta = np.mean(deltas)
        period = 2*delta*0.001*period
        frequency_pend[j] = 1/period
        amplitude_pend[j] = (np.max(signal_stat)-np.min(signal_stat))/2

    # Plotting
    plt.figure('2c : effect of frequency')
    plt.subplot(121)
    plt.loglog(stim_frequency_range,frequency_pend)
    plt.grid()
    plt.xlabel('Stimulation Frequency in Hz')
    plt.ylabel('Pendulum Oscillation Frequency [Hz]')
    plt.subplot(122)
    plt.loglog(stim_frequency_range,amplitude_pend)
    plt.grid()
    plt.xlabel('Stimulation Frequency in Hz')
    plt.ylabel('Pendulum Oscillation Amplitude [rad]')
    plt.savefig('2c_frequency.png')
    plt.show()

    # Effect of amplitude
    stim_frequency = 10 #Hz
    stim_amp_range = np.arange(0,1.1,0.1)
    phase_shift = np.pi
    frequency_pend=np.zeros(len(stim_amp_range))
    amplitude_pend=np.zeros(len(stim_amp_range))
    
    for j,stim_amp in enumerate(stim_amp_range):
        period = 1/stim_frequency
        t_max = 5*period  # Maximum simulation time
        time = np.arange(0., t_max, 0.001*period)  # Time vector

        act1 = np.zeros((len(time),1))
        act2 = np.zeros((len(time),1))
        act1[:,0] = stim_amp*(1 + np.sin(2*np.pi*stim_frequency*time))/2
        act2[:,0] = stim_amp*(1+ np.sin(2*np.pi*stim_frequency*time + phase_shift))/2
        activations = np.hstack((act1, act2))
        sim.add_muscle_activations(activations)
        sim.initalize_system(x0, time)  # Initialize the system state
        sim.simulate()
        res = sim.results()  
        # computing the frequency and amplitude
        angular_position = res[:,1]
        signal_stat = angular_position[int(len(angular_position)/2):len(angular_position)]
        index_zeros = np.where(np.diff(np.sign(signal_stat)))[0]
        deltas = np.diff(index_zeros)
        delta = np.mean(deltas)
        period = 2*delta*0.001*period
        frequency_pend[j] = 1/period
        amplitude_pend[j] = (np.max(signal_stat)-np.min(signal_stat))/2
        
    frequency_pend[0] = 0.0;
    
    # Plotting
    plt.figure('2c : effect of amplitude')
    plt.subplot(121)
    plt.plot(stim_amp_range,frequency_pend)
    plt.grid()
    plt.xlabel('Stimulation Amplitude')
    plt.ylabel('Pendulum Oscillation Frequency [Hz]')
    plt.subplot(122)
    plt.plot(stim_amp_range,amplitude_pend)
    plt.grid()
    plt.xlabel('Stimulation Amplitude')
    plt.ylabel('Pendulum Oscillation Amplitude [rad]')
    plt.savefig('2c_amplitude.png')
    plt.show()
예제 #33
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 = 2.5  # Maximum simulation time
    time = np.arange(0., t_max, 0.001)  # Time vector

    ##### Model Initial Conditions #####
    x0_P = np.array([np.pi / 6, 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
    sin_freq = 1  #hz
    ampl_sin = 1
    phase_difference_1_2 = np.pi
    act1 = np.ones((len(time), 1))
    act2 = np.ones((len(time), 1))
    for i in range(len(time)):
        act1[i, 0] = ampl_sin * (1 + np.sin(2 * np.pi * sin_freq * time[i]))
        act2[i, 0] = ampl_sin * (
            1 + np.sin(2 * np.pi * sin_freq * time[i] + phase_difference_1_2))
    activations = np.hstack((act1, act2))

    # 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('Pendulum')
    plt.title('Pendulum Phase')
    plt.plot(res[:, 1], res[:, 2])
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad.s]')
    plt.grid()
    plt.figure('Activations')
    plt.title('Sine wave activations for both muscles')
    plt.plot(time, act1)
    plt.plot(time, act2)
    plt.legend(("activation muscle1", "activation muscle2"))
    # 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)
예제 #34
0
    def update(self, key, E, P):
        """Update liveplots"""
        # Check if there are still open figures
        if self.any_figs:
            open_figns = plt.get_figlabels()
            live_figns = set(self.figures.keys())
            self.any_figs = bool(live_figns.intersection(open_figns))
        else:
            return

        # Playback control
        SPACE = b' '
        CHAR_I = b'i'
        ENTERs = [b'\n', b'\r']  # Linux + Windows

        def pause():
            """Loop until user decision is made."""
            ch = read1()
            while True:
                # Set state (pause, skipping, ipdb)
                if ch in ENTERs:
                    self.paused = False
                elif ch == CHAR_I:
                    self.run_ipdb = True
                # If keypress valid, resume execution
                if ch in ENTERs + [SPACE, CHAR_I]:
                    break
                ch = read1()
                # Pause to enable zoom, pan, etc. of mpl GUI
                plot_pause(0.01)  # Don't use time.sleep()!

        # Enter pause loop
        if self.paused:
            pause()

        else:
            if key == (0, None, 'u'):
                # Skip read1 for key0 (coz it blocks)
                pass
            else:
                ch = read1()
                if ch == SPACE:
                    # Pause
                    self.paused = True
                    self.skipping = False
                    pause()
                elif ch in ENTERs:
                    # Toggle skipping
                    self.skipping = not self.skipping
                elif ch == CHAR_I:
                    # Schedule debug
                    # Note: The reason we dont set_trace(frame) right here is:
                    # - I could not find the right frame, even doing
                    #   >   frame = inspect.stack()[0]
                    #   >   while frame.f_code.co_name != "assimilate":
                    #   >       frame = frame.f_back
                    # - It just restarts the plot.
                    self.run_ipdb = True

        # Update figures
        if not self.skipping:
            faus = key[-1]
            if faus != 'u' or self.plot_u:
                for name, (updater) in self.figures.items():
                    if plt.fignum_exists(name) and \
                            getattr(updater, 'is_active', 1):
                        _ = plt.figure(name)
                        updater(key, E, P)
                        plot_pause(self.params['pause_' + faus])

        if self.run_ipdb:
            self.run_ipdb = False
            import inspect

            import ipdb
            print("Entering debug mode (ipdb).")
            print("Type '?' (and Enter) for usage help.")
            print("Type 'c' to continue the assimilation.")
            ipdb.set_trace(inspect.stack()[2].frame)
예제 #35
0
    charparams = (40, 20, .02)
    i_probe = LPchar(v, *charparams)
    i_probe += noise[0] * 2 * (np.random.random(len(t)) - 0.5)
    i_probe += (i_probe -
                max(i_probe)) * noise[1] * 2 * (np.random.random(len(t)) - 0.5)
    label = str('test - {cp}'.format(cp=charparams))
    if np.max(np.abs(lfnoise)) > 0:
        N = len(i_probe)
        i_probe += np.sum([
            lfnoise[i] * np.sin(2 * np.pi * i * np.arange(N) / float(N))
            for i in range(len(lfnoise))
        ],
                          axis=0)

else:
    (labs_nums) = zip(plt.get_figlabels(), plt.get_fignums())
    for lab in labs_nums:
        label, num = lab
        if '[' in label:
            fig = plt.figure(label)
            mgr = plt.get_current_fig_manager()
            mgr.window.tkraise()
            break

    print('found "' + label + '"', end='')
    if label.startswith('['):
        print()
    else:
        ans = input(' which is not the expected figure label: continue?')
        if ans.lower() != 'y':
            sys.exit(1)
예제 #36
0
파일: best_effort.py 프로젝트: xpdAcq/xpdAn
    def descriptor(self, doc):
        self._descriptors[doc["uid"]] = doc
        stream_name = doc.get("name", "primary")  # fall back for old docs

        if stream_name not in self._stream_names_seen:
            self._stream_names_seen.add(stream_name)
            if self._table_enabled:
                print("New stream: {!r}".format(stream_name))

        columns = hinted_fields(doc)
        # don't build plots for things which can't be handled
        columns = list(
            filter(lambda x: len(doc["data_keys"][x]["shape"]) == 0, columns)
        )

        # ## This deals with old documents. ## #

        if stream_name == "primary" and self._cleanup_motor_heuristic:
            # We stashed object names in self.dim_fields, which we now need to
            # look up the actual fields for.
            self._cleanup_motor_heuristic = False
            fixed_dim_fields = []
            for obj_name in self.dim_fields:
                # Special case: 'time' can be a dim_field, but it's not an
                # object name. Just add it directly to the list of fields.
                if obj_name == "time":
                    fixed_dim_fields.append("time")
                    continue
                try:
                    fields = doc.get("hints", {}).get(obj_name, {})["fields"]
                except KeyError:
                    fields = doc["object_keys"][obj_name]
                fixed_dim_fields.extend(fields)
            self.dim_fields = fixed_dim_fields

        # ## TABLE ## #

        if stream_name == self.dim_stream:
            # Ensure that no independent variables ('dimensions') are
            # duplicated here.
            columns = [c for c in columns if c not in self.all_dim_fields]

            if self._table_enabled:
                # plot everything, independent or dependent variables
                self._table = LiveTable(list(self.all_dim_fields) + columns)
                self._table("start", self._start_doc)
                self._table("descriptor", doc)

        # ## DECIDE WHICH KIND OF PLOT CAN BE USED ## #
        # only use columns we can plot!
        columns = [
            c
            for c in columns
            if doc["data_keys"][c]["dtype"]
            in ("number", "integer", "float64", "float32")
        ]
        if not self._plots_enabled:
            return
        if stream_name in self.noplot_streams:
            return
        if not columns:
            return
        if (
            (self._start_doc.get("num_points", "") == 1)
            and (stream_name == self.dim_stream)
            and self.omit_single_point_plot
        ):
            return

        # This is a heuristic approach until we think of how to hint this in a
        # generalizable way.
        if stream_name == self.dim_stream:
            dim_fields = self.dim_fields
        else:
            dim_fields = ["time"]  # 'time' once LivePlot can do that

        # Create a figure or reuse an existing one.

        fig_name = "{} vs {}".format(
            " ".join(sorted(columns)), " ".join(sorted(dim_fields))
        )
        if self.overplot and len(dim_fields) == 1:
            # If any open figure matches 'figname {number}', use it. If there
            # are multiple, the most recently touched one will be used.
            pat1 = re.compile("^" + fig_name + "$")
            pat2 = re.compile("^" + fig_name + r" \d+$")
            for label in plt.get_figlabels():
                if pat1.match(label) or pat2.match(label):
                    fig_name = label
                    break
        elif self.overplot:
            if plt.fignum_exists(fig_name):
                # Generate a unique name by appending a number.
                for number in itertools.count(2):
                    new_name = "{} {}".format(fig_name, number)
                    if not plt.fignum_exists(new_name):
                        fig_name = new_name
                        break
        ndims = len(dim_fields)
        if not 0 < ndims < 3:
            # we need 1 or 2 dims to do anything, do not make empty figures
            return

        if self._fig_factory:
            fig = self._fig_factory(fig_name)
        else:
            fig = plt.figure(fig_name)

        self.fig = fig

        if not fig.axes:
            # This is apparently a fresh figure. Make axes.
            # The complexity here is due to making a shared x axis. This can be
            # simplified when Figure supports the `subplots` method in a future
            # release of matplotlib.
            fig.set_size_inches(6.4, min(950, len(columns) * 400) / fig.dpi)
            for i in range(len(columns)):
                if i == 0:
                    ax = fig.add_subplot(len(columns), 1, 1 + i)
                    if ndims == 1:
                        share_kwargs = {"sharex": ax}
                    elif ndims == 2:
                        share_kwargs = {"sharex": ax, "sharey": ax}
                    else:
                        raise NotImplementedError("we now support 3D?!")
                else:
                    ax = fig.add_subplot(
                        len(columns), 1, 1 + i, **share_kwargs
                    )
        axes = fig.axes

        # ## LIVE PLOT AND PEAK ANALYSIS ## #

        if ndims == 1:
            self._live_plots[doc["uid"]] = {}
            self._peak_stats[doc["uid"]] = {}
            x_key, = dim_fields
            for y_key, ax in zip(columns, axes):
                dtype = doc["data_keys"][y_key]["dtype"]
                if dtype not in ("number", "integer", "float64", "float32"):
                    warn(
                        "Omitting {} from plot because dtype is {}"
                        "".format(y_key, dtype)
                    )
                    continue
                # Create an instance of LivePlot and an instance of PeakStats.
                live_plot = LivePlotPlusPeaks(
                    y=y_key, x=x_key, ax=ax, peak_results=self.peaks
                )
                live_plot("start", self._start_doc)
                live_plot("descriptor", doc)
                peak_stats = PeakStats(x=x_key, y=y_key)
                peak_stats("start", self._start_doc)
                peak_stats("descriptor", doc)

                # Stash them in state.
                self._live_plots[doc["uid"]][y_key] = live_plot
                self._peak_stats[doc["uid"]][y_key] = peak_stats

            for ax in axes[:-1]:
                ax.set_xlabel("")
        elif ndims == 2:
            # Decide whether to use LiveGrid or LiveScatter. LiveScatter is the
            # safer one to use, so it is the fallback..
            gridding = self._start_doc.get("hints", {}).get("gridding")
            if gridding == "rectilinear":
                self._live_grids[doc["uid"]] = {}
                slow, fast = dim_fields
                try:
                    extents = self._start_doc["extents"]
                    shape = self._start_doc["shape"]
                except KeyError:
                    warn(
                        "Need both 'shape' and 'extents' in plan metadata to "
                        "create LiveGrid."
                    )
                else:
                    data_range = np.array([float(np.diff(e)) for e in extents])
                    y_step, x_step = data_range / [
                        max(1, s - 1) for s in shape
                    ]
                    adjusted_extent = [
                        extents[1][0] - x_step / 2,
                        extents[1][1] + x_step / 2,
                        extents[0][0] - y_step / 2,
                        extents[0][1] + y_step / 2,
                    ]
                    for I_key, ax in zip(columns, axes):
                        if len(doc["data_keys"][I_key]["shape"]) > 0:
                            continue
                        # MAGIC NUMBERS based on what tacaswell thinks looks OK
                        data_aspect_ratio = np.abs(
                            data_range[1] / data_range[0]
                        )
                        MAR = 2
                        if 1 / MAR < data_aspect_ratio < MAR:
                            aspect = "equal"
                            ax.set_aspect(aspect, adjustable="box-forced")
                        else:
                            aspect = "auto"
                            ax.set_aspect(aspect, adjustable="datalim")

                        live_grid = LiveGrid(
                            shape,
                            I_key,
                            xlabel=fast,
                            ylabel=slow,
                            extent=adjusted_extent,
                            aspect=aspect,
                            ax=ax,
                        )

                        live_grid("start", self._start_doc)
                        live_grid("descriptor", doc)
                        self._live_grids[doc["uid"]][I_key] = live_grid
            else:
                self._live_scatters[doc["uid"]] = {}
                x_key, y_key = dim_fields
                for I_key, ax in zip(columns, axes):
                    if len(doc["data_keys"][I_key]["shape"]) > 0:
                        continue
                    try:
                        extents = self._start_doc["extents"]
                    except KeyError:
                        xlim = ylim = None
                    else:
                        xlim, ylim = extents
                    live_scatter = LiveScatter(
                        x_key,
                        y_key,
                        I_key,
                        xlim=xlim,
                        ylim=ylim,
                        # Let clim autoscale.
                        ax=ax,
                    )
                    live_scatter("start", self._start_doc)
                    live_scatter("descriptor", doc)
                    self._live_scatters[doc["uid"]][I_key] = live_scatter
        else:
            raise NotImplementedError(
                "we do not support 3D+ in BEC yet "
                "(and it should have bailed above)"
            )
        try:
            fig.tight_layout()
        except ValueError:
            pass