Python:Ordinary Differential Equations/Templates

From PrattWiki
Revision as of 19:05, 26 November 2018 by DukeEgr93 (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

The codes below present templates for creating the function file responsible for computing values of the first derivatives of all the variables and the script whose job is to solve a system of initial value problems based on ordinary differential equations. This program calls the StatePlotter program, available at the bottom.

Code

#%% Imports
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp

#%% Define independent function and derivative function
def x(t):
    return # Independent function here

def f(t, y, c):
'''
Template for calculating first derivatives of state variables
t is time
y is the state vector
c contains any required constants
dydt must be a list or an array
'''
    dydt = # list or array of first derivatives here
    return dydt
    
#%% Define time spans, initial value, and extra constants
tspan = 
yinit = #must be a list or an array
c = 

#%% Solve differential equation
sol = solve_ivp(f, [tspan[0], tspan[-1]], yinit, t_eval=tspan)

#%% Determine if states should be plotted
plot_states = True;

#%% Plot independent and dependent variable


State Plotter

The StatePlotter.m code will accept a vector of times and a matrix of states (which should have each state in a column). It will determine how many states there are based on the number of columns, break the figure window up into the appropriate number of subplots, and graph each state.

function StatePlotter(Time, States)

StateCount = size(States, 2);

NumCols = ceil(sqrt(StateCount));
NumRows = ceil(StateCount / NumCols);
clf;
for PlotNumber = 1:StateCount
        subplot(NumRows, NumCols, PlotNumber);
        plot(Time, States(:,PlotNumber), 'ko:');
        xlabel('Time');
        ylabel(sprintf('y_{%0.0f}(t)', PlotNumber))
        title(sprintf('y_{%0.0f}(t) vs. Time', PlotNumber));
end

Questions

Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.

External Links

References