コード例 #1
0
        self.stiffness.set_ydata(self.Y[1, :i])

        return self.pendulum, self.spring1, self.spring2, self.inputIndicator1, self.inputIndicator1Arrow, self.inputIndicator2, self.inputIndicator2Arrow, self.input1, self.input2, self.angle, self.stiffness, self.timeStamp,

    def start(self, interval):
        self.anim = animation.FuncAnimation(self.fig,
                                            self.animate,
                                            frames=len(self.Time),
                                            interval=interval,
                                            blit=False)


if __name__ == '__main__':
    Time, X, U, Y, plant1, plant2 = test_plant()
    if len(sys.argv) - 1 != 0:
        if '--savefigs' in sys.argv:
            save_figures("visualizations/",
                         "v0",
                         params,
                         ReturnPath=False,
                         SaveAsPDF=True)
        if '--animate' in sys.argv:
            downsamplingFactor = 300
            ani = animate_pendulum(
                Time[::downsamplingFactor], X[:, ::downsamplingFactor],
                U[:, ::downsamplingFactor], Y[:, ::downsamplingFactor],
                plant2.desiredOutput[:, ::downsamplingFactor], **params)
            ani.start(downsamplingFactor)
            # ani.anim.save('test.mp4', writer='ffmpeg', fps=1000/downsamplingFactor)
    plt.show()
コード例 #2
0
    def run_babbling_trial(self,
                           x1o,
                           plot=False,
                           saveFigures=False,
                           saveAsPDF=False,
                           returnData=False,
                           saveData=False,
                           saveParams=False):

        is_number(x1o,
                  "Initial Joint Angle",
                  notes="Should be between 0 and 2 pi.")

        if saveFigures == True:
            assert plot == True, "No figures will be generated. Please select plot=True."

        poorBabbling = True
        count = 0
        while poorBabbling:

            ## Generate babbling input
            if self.babblingType == 'continuous':
                self.generate_continuous_babbling_input()
            else:  #self.babblingType=='step'
                self.generate_step_babbling_input()

            ## running the babbling data through the plant
            X_o = self.plant.return_X_o(x1o, self.babblingSignals[0, :])

            X, U, _ = self.plant.forward_simulation(
                X_o, U=self.babblingSignals.T, addTitle="Motor Babbling"
            )  # need the transpose for the shapes to align (DAH)

            tendonDeformation1 = np.array(
                [-self.plant.rj, 0, self.plant.rm, 0, 0, 0]) @ X
            tendonDeformation2 = np.array(
                [self.plant.rj, 0, 0, 0, self.plant.rm, 0]) @ X
            minDeformation = np.array([tendonDeformation1,
                                       tendonDeformation2]).min()
            if minDeformation < -0.02:
                print(
                    "Poor Babbling! Large Negative Tendon Deformations. Try Again"
                )
                count += 1
                assert count < 100, "count exceeded (negative tendon deformation)."
            elif (abs(X[0, :].min() - self.plant.jointAngleBounds['LB']) <= 5 *
                  (np.pi / 180) and
                  abs(X[0, :].max() - self.plant.jointAngleBounds['UB']) <= 5 *
                  (np.pi / 180)):
                poorBabbling = False
            else:
                print("Poor Babbling! Trying again...")
        ## plot (and save) figures
        output = {}
        if plot == True:
            # self.plant.plot_states(X,Return=True)
            self.plant.plot_states_and_inputs(X, U, returnFig=True)

            self.plant.plot_output_power_spectrum_and_distribution(
                X, returnFigs=True)

            self.plant.plot_tendon_tension_deformation_curves(X)

            self.plot_signals_power_spectrum_and_amplitude_distribution()

            if saveFigures == True:
                trialPath = save_figures("babbling_trials/",
                                         babblingParams["Babbling Type"],
                                         self.totalParams,
                                         returnPath=True,
                                         saveAsPDF=saveAsPDF,
                                         saveAsMD=True)

                if saveParams == True:
                    save_params_as_MAT(self.totalParams, path=trialPath)

                if saveData == True:
                    self.save_data(X, filePath=trialPath)

                if returnData == True:
                    output["time"] = self.plant.time
                    output["X"] = X
                    output["U"] = U
                    output["path"] = trialPath
                    return (output)
                else:
                    output["path"] = trialPath
                    return (output)
            else:
                if saveParams == True:
                    save_params_as_MAT(self.totalParams)

                if saveData == True:
                    self.save_data(X)

                if returnData == True:
                    output["time"] = self.plant.time
                    output["X"] = X
                    output["U"] = U
                    return (output)
        else:
            if saveParams == True:
                save_params_as_MAT(self.totalParams)

            if saveData == True:
                babblingTrial.save_data(X)

            if returnData == True:
                output["time"] = self.plant.time
                output["X"] = X
                output["U"] = U
                return (output)
コード例 #3
0
    def run_babbling_trial(self,
                           x1o,
                           plot=False,
                           saveFigures=False,
                           saveAsPDF=False,
                           returnData=False,
                           saveData=False,
                           saveParams=False):

        is_number(x1o,
                  "Initial Joint Angle",
                  notes="Should be between 0 and 2 pi.")

        if saveFigures == True:
            assert plot == True, "No figures will be generated. Please select plot=True."

        ## Generate babbling input
        if self.babblingType == 'continuous':
            self.generate_continuous_babbling_input()
        else:  #self.babblingType=='step'
            self.generate_step_babbling_input()

        ## running the babbling data through the plant
        X_o = self.plant.return_X_o(x1o, self.babblingSignals[0, :])

        X, U, _ = self.plant.forward_simulation(
            X_o, U=self.babblingSignals.T, addTitle="Motor Babbling"
        )  # need the transpose for the shapes to align (DAH)

        ## plot (and save) figures
        output = {}
        if plot == True:
            self.plant.plot_states(X)

            self.plant.plot_joint_angle_power_spectrum_and_distribution(X)

            self.plant.plot_tendon_tension_deformation_curves(X)

            self.plot_signals_power_spectrum_and_amplitude_distribution()

            if saveFigures == True:
                trialPath = save_figures("babbling_trials/",
                                         "propAmp",
                                         self.totalParams,
                                         returnPath=True,
                                         saveAsPDF=saveAsPDF)

                if saveParams == True:
                    save_params_as_MAT(self.totalParams, path=trialPath)

                if saveData == True:
                    self.save_data(X, path=trialPath)

                if returnData == True:
                    output["time"] = self.plant.time
                    output["X"] = X
                    output["U"] = U
                    output["path"] = trialPath
                    return (output)
                else:
                    output["path"] = trialPath
                    return (output)
            else:
                if saveParams == True:
                    save_params_as_MAT(self.totalParams)

                if saveData == True:
                    self.save_data(X)

                if returnData == True:
                    output["time"] = self.plant.time
                    output["X"] = X
                    output["U"] = U
                    return (output)
        else:
            if saveParams == True:
                save_params_as_MAT(self.totalParams)

            if saveData == True:
                self.save_data(X)

            if returnData == True:
                output["time"] = self.plant.time
                output["X"] = X
                output["U"] = U
                return (output)
        for el in np.linspace(0,
                              np.round(delta_lT_max / 0.01) * 0.01,
                              int(np.round(delta_lT_max / 0.01)) + 1)
    ])
    cax2.set_yticklabels([
        '{:0.2f}'.format(el)
        for el in np.linspace(0,
                              np.round(delta_lT_max / 0.01) * 0.01,
                              int(np.round(delta_lT_max / 0.01)) + 1)
    ])

    if i == 0:
        Path = save_figures("./Figures/Iso_Error/",
                            "Iso_" + str(100 * fT_array[i]) + "_MVC", {
                                "Initial Force": initial_force,
                                "Slack to Optimal Ratio": l_Ts_over_l_To
                            },
                            figs=[fig2],
                            SaveAsPDF=True,
                            ReturnPath=True)
    else:
        save_figures("./Figures/Iso_Error/",
                     "Iso_" + str(int(100 * fT_array[i])) + "_MVC", {},
                     SubFolder=Path[-18:],
                     figs=[fig2],
                     SaveAsPDF=True)
    plt.close(fig2)
    statusbar.update(i)

save_figures("./Figures/Iso_Error/",
             "Iso_MVC_all_levels", {},
             SubFolder=Path[-18:],
             f"PCC = {pearsonr(lm2o,MAE2)[0]:0.3f}",
             transform=ax2.transAxes,
             horizontalalignment='center',
             verticalalignment='center',
             color="k",
             fontsize=14,
             bbox=dict(boxstyle='round,pad=0.5', edgecolor='k', facecolor='w'))
    ax1.set_ylim([0, 2])
    ax2.set_ylim([0, 2])
    # plt.show()

    folderPath = save_figures(
        "output_figures/integrator_backstepping_sinusoidal_activations_fixed_tensions/",
        "1DOF_2DOA", {
            "Initial Muscle Lengths": InitialMuscleLengths,
            "Initial Tendon Tensions": InitialTensions
        },
        returnPath=True,
        saveAsPDF=True,
        saveAsMD=True)
    # save_figures("output_figures/integrator_backstepping_sinusoidal_activations_fixed_muscle_lengths/","1DOF_2DOA_v1.0",SaveAsPDF=True)
    plt.close('all')
    FormatedSaveData = {
        "States": TotalX,
        "Input": TotalU,
        "Error": Error,
        "Initial Tensions": InitialTensionsFromSuccessfulTrials
    }
    pickle.dump(FormatedSaveData, open(folderPath / "output.pkl", "wb"))
else:
    print("All Trials Unsuccessful...")
コード例 #6
0
    0, 1 / min(stuff['Slack_Opt_Tendon_Ratio']),
    1 / min(stuff['Slack_Opt_Tendon_Ratio'])
], [1, 1, 0], 'k--')
ax.set_xlabel(r"$\hat{l}^T$", fontsize=14)
ax.set_ylabel(r"$\hat{f}^T$", fontsize=14)
cax, _ = matplotlib.colorbar.make_axes(ax)
cbar = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap)
cax.set_ylabel(r"$\dfrac{l_{T,o}}{l_{T,s}}$", fontsize=14)
cbar.set_ticks([(
    int(100 *
        (el - np.floor(1 /
                       (max(stuff['Slack_Opt_Tendon_Ratio'])) / 0.01) * 0.01) /
        (np.ceil(1 / (min(stuff['Slack_Opt_Tendon_Ratio'])) / 0.01) * 0.01 -
         np.floor(1 / (max(stuff['Slack_Opt_Tendon_Ratio'])) / 0.01) * 0.01)) /
    100) for el in np.arange(
        np.floor(1 / (max(stuff['Slack_Opt_Tendon_Ratio'])) / 0.01) * 0.01,
        np.ceil(1 / (min(stuff['Slack_Opt_Tendon_Ratio'])) / 0.01) * 0.01 +
        1e-4, 0.01)])
cax.set_yticklabels([
    '{:0.2f}'.format(el) for el in np.arange(
        np.floor(1 / (max(stuff['Slack_Opt_Tendon_Ratio'])) / 0.01) * 0.01,
        np.ceil(1 / (min(stuff['Slack_Opt_Tendon_Ratio'])) / 0.01) * 0.01 +
        1e-4, 0.01)
])

save_figures("./Figures/feasible_cTkT/",
             "fT_lT_plot_from_cT_kT_range", {},
             figs=[fig2],
             SaveAsPDF=True)
plt.close(fig2)