Difference between revisions of "SymPy/Simultaneous Equations"

From PrattWiki
Jump to navigation Jump to search
(Solving Equations With SymPy)
(Introduction)
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
==Introduction==
 
==Introduction==
This page focuses on using SymPy to find both the symbolic and the numeric solutions to equations obtained from electric circuits.   
+
This page focuses on using SymPy to find both the symbolic and the numeric solutions to equations obtained from electric circuits.  The examples are available via a Google Drive at [https://drive.google.com/drive/folders/10NuAAl4yWpsapZesm2snnWOgMtBb-tP2?usp=sharing Basic Linear Algebra].  If you have the [https://workspace.google.com/marketplace/app/colaboratory/1014160490159 Google Colaboratory app] installed in your browser, you should be able to run the notebooks in your browser.  If not, you can either install it or install a local program that can read notebook files such as Jupyter Notebooks, available with [https://www.anaconda.com/ Anaconda].
  
== Initialization ==
+
== Very Basic Example ==
To use SymPy, you will need to import the moduleThe module comes with the Anaconda distribution of Python, but if you have a different installation, you may need to get the module firstAlso, you will likely want to use the "pretty printing" capabilities of SymPy, which requires initializing printingThese two steps can be done with:
+
The example code below assumes you are either running code in a notebook of some kind or typing it into a consoleThere is a finished example at the end of this section which also includes the commands to display different variables if you are using a script.
 +
Imagine you have the equation $$ax=d$$ and you want to solve for $$x$$You can do this in SymPy as follows:
 +
 
 +
=== Initialization ===
 +
You will need to import <code>sympy</code> to use symbolic calculationsPratt Pundit will generally give that module the nickname <code>sym</code>:
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
 
import sympy as sym
 
import sympy as sym
 
sym.init_printing()
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
== Declaring Symbols ==
+
=== Declare Variables ===
While there are ways to bring in certain "standard" symbols in SymPy, it may be clearest to define them yourself.  You need to declare something as a symbol before using it on the right side of an assignment; as usual, if you create a variable as a combination of symbols, Python will duck type it as a symbol tooThe <code>sym.var()</code> function accepts a space or comma-separated string of variables and will create symbolic entities based on the code in the string. 
+
You will need to let Python know what your variables areThere are several ways to do this; the easiest is to use the <code>sym.var()</code> command with a string containing the variables you want separated by spaces:
For instance:
 
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
sym.var('x, y')
+
sym.var('a x d')
 
</syntaxhighlight>
 
</syntaxhighlight>
will create variables <code>x</code> and <code>y</code>
 
  
== Defining Equations ==
+
=== Define Equations ===
 
When it comes to solving things later, there are two different ways to define an equation:
 
When it comes to solving things later, there are two different ways to define an equation:
* If the equation is equal to zero, you do not explicitly have to include the "=0" part; you can simply define a variable to hold on to the expression.  If $$x+y=0$$ is one of the equations you are looking to solve, you can use:
+
* If you have an expression that evaluates to other than zero, you can use sym.Eq(left, right) for that.  Given that we are trying to solve $$ax=d$$, you can write that in code as:
 +
<syntaxhighlight lang=python>
 +
eqn1 = sym.Eq(a * x, d)
 +
</syntaxhighlight>
 +
* If the equation is equal to zero, you do not explicitly have to include the "=0" part; you can simply define a variable to hold on to the expression.  For instance, in this case, we can re-write the equation we are trying to solve as $$ax-d=0$$ and just define a variable to hold on to the left side:
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
eqn1 = x + y
+
eqn1 = a * x - d
 
</syntaxhighlight>
 
</syntaxhighlight>
  
If you have an expression that evaluates to other than zero, you can use sym.Eq(left, right) for that.  If the other equations for which you are trying to solve is $$x-y=3$$, you can write that in code as:
+
=== Solve Equations ===
 +
There are two fundamentally different ways to solve one equation.  If you give the solver the equation, it will return a list with the solution in it:
 +
<syntaxhighlight lang=python>
 +
soln1 = sym.solve(eqn1, x)
 +
soln1
 +
</syntaxhighlight>
 +
will produce a list that contains $$d/a$$On the other hand, if you give the solver a list with an equation in it, it will return a dictionary with the solution defined in it:
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
eqn2 = sym.Eq(x - y, 3)
+
soln2 = sym.solve([eqn1], x)
 +
soln2
 
</syntaxhighlight>
 
</syntaxhighlight>
Of course, you could also rearrange the expression by moving the right side to the left, in which case:
+
will produce the dictionary $$\left\{x: \frac{d}{a}\right\}$$.  Whenever you have more than one equation, you will need to collect the equations in a list or a tuple and the solver will return a dictionary.  Given that, it is generally a good idea to always give the solver a list for the equations and a list for the unknowns, even if there is only one of each.
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
eqn2 = x - y - 3
+
soln = sym.solve([eqn1], [x])
 +
soln
 
</syntaxhighlight>
 
</syntaxhighlight>
would work!
 
  
 +
=== Make Substitutions ===
 +
Now that you have symbolic answers, you can make numerical substitutions for those symbols using the <code>subs</code> command.  You will need to pull the appropriate definition out of the dictionary and then apply the substitutions to it.  For example, to see what $$x$$ is when $$d$$ is 10, you can write:
  
==Solving Equations With SymPy==
 
To solve a system of linear algebra equations, you can use the <code>sym.solve(eqns, vars)</code> command.  The system of equations should be in a list, set, or tuple as should the list of unknowns.  Note that even if you don't specifically "care" about the value of one or more of the unknowns, you must list them; if you want to solve the two equations above to find x, you still need to explicitly list y as a unknown or else SymPy will assume that it is a symbolic, but known, value, thus constraining the system.  Here is an example solving the two equations above:
 
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
soln = sym.solve((eqn1, eqn2), (x, y))
+
soln[x].subs(d, 10)
 
</syntaxhighlight>
 
</syntaxhighlight>
If you run this in the console, <code>soln</code> will print out pretty.  If you put all this in a script, <code>soln</code> will not show up at all...  You can put <code>print(soln)</code> in a script, but it will not be pretty.  To make it pretty requires a little work since the solution set is a dictionary with the variables as keys.  To help, here is a Python function you can add to your code:
+
 
<syntaxhighlight lang=python>
+
If you want to see multiple substitutions, you can put the substitution pairs in tuples or lists that are contained in a tuple or list:
def printout(solution, variables, fp=False):
 
    if type(variables)!=tuple: % fixes issue with single symbols
 
        variables = variables,
 
    for var in variables:
 
        sym.pretty_print(var)
 
        if fp:
 
            sym.pretty_print(solution[var].evalf(fp))
 
        else:
 
            sym.pretty_print(solution[var].simplify())
 
    print()
 
</syntaxhighlight>
 
This will go through the solutions and print the variable followed by the solution.  If you have substituted in numbers, set fp to True to do floating point evaluation on the answers.  If you define this function in the console and then type
 
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
printout(soln, (x, y))
+
soln[x].subs([[a, 3], [d, 10]])
 
</syntaxhighlight>
 
</syntaxhighlight>
you will see the variables and their values. 
 
  
When the solutions are numbers, this does not seem that useful, but imagine that you want to solve:
+
=== Complete Example ===
<center>$$
+
The code below has an additional piece, which is importing IPython.display as disp. This will allow you to display symbols in a formatted fashion within a script.
\begin{align*}
 
ax+by&=c\\
 
dx+ey&=f
 
\end{align*}$$</center>
 
symbolically? You will need to add symbols for a through f first, then redefine the equations to include those symbols; here is a sample code:
 
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
 +
# Import sympy
 
import sympy as sym
 
import sympy as sym
  
 +
# Print pretty
 
sym.init_printing()
 
sym.init_printing()
  
def printout(solution, variables, fp=False):
+
# Use disp.display to use formatted printing
    for var in variables:
+
import IPython.display as disp
        sym.pretty_print(var)
+
show = disp.display
        if fp:
+
 
            sym.pretty_print(solution[var].evalf(fp))
+
# Declare symbols
        else:
+
sym.var('a x d')
            sym.pretty_print(solution[var].simplify())
+
 
    print()
+
# Equations
 +
eqn1 = sym.Eq(a * x, d)
 +
 
 +
# Solve
 +
soln1 = sym.solve(eqn1, x)
 +
show(soln1)
 +
 
 +
soln2 = sym.solve([eqn1], x)
 +
show(soln2)
 +
 
 +
soln = sym.solve([eqn1], [x])
 +
show(soln)
 +
 
 +
show(soln[x].subs(d, 10))
 +
 
 +
show(soln[x].subs([[a, 3], [d, 10]]))
 +
</syntaxhighlight>
  
x, y = sym.var('x, y')
 
a, b, c, d, e, f = sym.var('a, b, c, d, e, f')
 
  
eqn1 = a*x + b*y - c # shows moving right to left side
+
<syntaxhighlight lang=python>
eqn2 = sym.Eq(d*x+e*y, f) # Shows using sym.Eq to give left and right
 
  
soln = sym.solve((eqn1, eqn2), (x, y))
 
print(soln)
 
printout(soln, (x, y))
 
 
</syntaxhighlight>
 
</syntaxhighlight>
The printed version gives:
+
 
<syntaxhighlight lang=text>
+
 
{x: (-b*f + c*e)/(a*e - b*d), y: (a*f - c*d)/(a*e - b*d)}
+
<syntaxhighlight lang=python>
 +
 
 
</syntaxhighlight>
 
</syntaxhighlight>
which is a bit hard to interpret; the printout version shows the two fractions as mathematical expressions.
 
  
== Substituting Values ==
+
== Helper Functions ==
SymPy has a subs method that works on a variableFor instance, if you have:
+
As you can see in the example above, there are some processes that look like they might get a little complicated as the number of equations increases.  Given that, here is a set of helper functions that you may want to import into your script or notebookNote: if you are using Google Colab, accessing secondary files takes a bit of work - this will be explained later.  These functions are all in a file called <code>sym_helper.py</code>.
 +
 
 +
=== Imports ===
 +
The <code>sym_helper.py</code> will need to import the sympy module.  It will also attempt to import the IPython.display module.  in order to make <code>sym_helper.py</code> compatible with applications like Trinket (which does not use IPython.display), <code>sym_helper.py</code> will see if it can import the module and then, based on that, decide how it will show things:
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
 
import sympy as sym
 
import sympy as sym
  
sym.init_printing()
+
try:
 +
  import IPython.display as disp
 +
  show = disp.display
 +
except:
 +
  show = sym.pretty_print
 +
</syntaxhighlight>
 +
 
  
sym.var('a, b, c, d, e, f')
+
=== Printing Out Solution Dictionary ===
a = b + c * d + e ** f
+
Next, we may want help printing out the solutions to a set of equations. As long as you give <code>solve</code> a list of equations, you will get back a dictionary.
</syntaxhighlight>
+
If you are running your code in a notebook or in the console, typing <code>soln</code> by itself and hitting return will let you see a pretty version of the solution.  If you put all this in a script, however, <code>soln</code> will not show up at all...  You can put <code>print(soln)</code> in a script, but it will not be pretty.  To make it pretty requires a little work since the solution set is a dictionary with the variables as keys.  To help, here is a Python function called <code>printout</code> you can use:
You have created $$a=b+cd+e^f$$.  If you want to know what this would be if $$b=2$$, you could write:
 
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
a.subs(b, 2)
+
def printout(solution, variables=None, fp=False):
 +
  # Default case: print all variables
 +
  if variables==None:
 +
    variables = tuple(solution.keys())
 +
  # Fixes issue if solving for a single item
 +
  if not isinstance(variables, (list, tuple)):
 +
    variables = [variables]
 +
  for var in variables:
 +
    show(var)
 +
    if fp:
 +
      show(solution[var].evalf(fp))
 +
    else:
 +
      show(solution[var])
 +
    print()
 
</syntaxhighlight>
 
</syntaxhighlight>
to see that - note that this does not change $$a$$If there are multiple substitutions, you can put them in an interable (i.e. list or tuple) of variable-value pairs; the following two lines will produce the same results:
+
This will go through the dictionary and print the variable followed by the solution for that variable.  If you have substituted in numbers, set <code>fp</code> to an integer to do floating point evaluation on the answers.  While a function like this may not seem necessary at the moment (with only one unknown variable, this feels like a lot of overhead), as you start solving problems with more and more unknowns it will be nice to have!
 +
 
 +
=== Making Substitutions ===
 +
As you start working with more equations, you may end up having more and more symbols that you will want to be able to replace with numerical values laterHaving to create a list of lists with the substitutions every time can certainly get old!  Here is a function that will take a solution dictionary, a list of variables for which to substitute, and a list of the values to use for those variables.  It returns a dictionary with the substitutions in place. Note that if it gets a list of equations rather than a dictionary, it will convert the list to a dictionary first.  This is not something that is needed for linear algebra but will be something that is needed when setting up and solving simultaneous differential equations.
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
a.subs( ( (b,2),(c,3) ) )
+
def makesubs(solution, vartosub, valtosub):
a.subs( [ [b,2],[c,3] ] )
+
  subsol = solution.copy()
 +
  sublist = list(zip(vartosub, valtosub))
 +
  if type(subsol)==list:
 +
    subsol = makedict(subsol)
 +
     
 +
  for var in subsol:
 +
    subsol[var] = subsol[var].subs(sublist)
 +
  return subsol
 +
 
 +
def makedict(sollist):
 +
  d = {}
 +
  for eqn in sollist:
 +
    d[eqn.lhs] = eqn.rhs
 +
  return d
 
</syntaxhighlight>
 
</syntaxhighlight>
If you have an iterable of variables to substitute for and an iterable of values, you can use the zip command to create those pairs for you:
+
 
 +
=== Complete Example Extended, with Helpers ===
 +
By carefully setting up your symbolic variables and by using the helper functions above, you can organize your code in a way that will be much more flexible for future assignments.  First, instead of creating all of your symbolic variables at once, you can divide them into a collection of unknowns and a collection of knowns -- that will make it easier when you want Python to solve your symbolic equations.  Second, you can create a list of the substitution values that you will be using later. 
 +
 
 +
'''Note:''' the code below assumes that <code>sym_helper.py</code> is accessible.  If you are using Google Colab, please see the section below on how to get that to work.
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
varstosub = [b, c]
+
# Imports
valstosub = [2, 3]
+
import sympy as sym
zipsub = zip(varstosub, valstosub)
+
from sym_helper import *
a.subs(zipsub)
+
 
 +
# Print pretty
 +
sym.init_printing()
 +
 
 +
# Declare symbols (unknowns in first group, knowns in second)
 +
# Create a list of future numerical values for knowns
 +
unks = sym.var('x')
 +
knowns = sym.var('a d')
 +
subval = [10, 3]
 +
 
 +
# Equations
 +
eqn1 = sym.Eq(a * x, d)
 +
 
 +
# Collect equations
 +
eqns = [eqn1]
 +
 
 +
# Solve and display
 +
sol = sym.solve(eqns, unks)
 +
printout(sol)
 +
 
 +
# Perform substitutions
 +
subsol = makesubs(sol, knowns, subval)
 +
printout(subsol)
 
</syntaxhighlight>
 
</syntaxhighlight>
There will be times when you want to make the same substitions to several symbolic representations at once.
+
 
Given that, here is another handy function for making substitutions that takes a list of variables and a list of values:
+
== Google Colab and Personal Modules ==
 +
Google Colab runs your files in the cloud; if you have extra modules that you need to access, you will need to make sure they are in the space that Google Colab is looking at. The following are two different ways to go about this:
 +
 
 +
=== Grab on the fly from GitHub ===
 +
If you have a few modules that you need, you can ask Google Colab to see if it already knows what they are and, if not, to grab the text from a GitHub file and write it to a new file in your GitHub space.  For instance, if you need access to the methods in the<code>sym_helper.py</code>, which lives at
 +
https://tinyurl.com/mrgdemos/SymPy_Files/sym_helper.py</code>
 +
you can get it with the following lines of code:
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
def makesubs(solution, vartosub, valtosub):
+
# Import the helper functions
    subsol = solution.copy()
+
try:
    sublist = list(zip(vartosub, valtosub))
+
  from sym_helper import *
    for var in solution:
+
except: # Get sym_helper.py from GitHub
        subsol[var] = subsol[var].subs(sublist)
+
  import requests
    return subsol
+
  url = 'https://tinyurl.com/mrgdemos/SymPy_Files/sym_helper.py'
 +
  open('sym_helper.py', 'w').write(requests.get(url).text)
 +
  from sym_helper import *
 
</syntaxhighlight>
 
</syntaxhighlight>
  
== Notes ==
+
=== Grab from a folder on Google Drive ===
For the printout and makesubs commands, if there is only one variable involved, the "list" of variables will be a single item and not an iterable, you may need to put [ ] around the variable "list" in the function call to get it to work.
+
If you have the module you need stored in your Google Drive, you can ask Google Colab to grab it from there.  There are several steps to this:
 +
# Decide where all your files are going to go.  Typically, Google Colab will create a folder called "Colab Notebooks" on your Google Drive.  Best bet is to put everything there in some organized way.
 +
# Decide if you want to have a common folder for help files.  For EGR 224 in Spring of 2023, I have a folder called "Helpers" inside my "Colab Notebooks" folder, and I am planning to store all helper files there.
 +
# Copy the helper files you need into that folder.  The sym_help.py file will be available on Sakai in the Resources section.  You can download it to your computer and then upload it to your Google Colab/Helpers folder using the web interface or you can install the Google Drive application for you computer so that you have direct access to your Google Drive files from Explorer / Finder.
 +
# Decide where your notebook is going to be.  The examples on this page are all in a folder I called "BasicLinalg" that is inside the "Colab Notebooks" folder.  Note that whenever Colab creates a new notebook, it puts it in "Colab Notebooks" - you can move it wherever you want it to be later.
 +
# In your notebook, you will need to do three things to get access to your Helper folder, to import functions from the helper file, and to have the notebook save things in the folder for the notebook:
 +
## Connect the drive:<syntaxhighlight lang=python>
 +
from google.colab import drive
 +
drive.mount('/content/drive')</syntaxhighlight>Note that you will generally need to give Google permission to access your drive.
 +
## Change directories and get helper functions:<syntaxhighlight lang=python>
 +
%cd /content/drive/MyDrive/Colab\ Notebooks/Helpers
 +
from sym_helper import *</syntaxhighlight>Note that the % in front of a command issues the command to your operating system; cd means "change directory." Your Google Drive is mounted at /context/drive/MyDrive, so this changes the directory to the Helpers folder inside of the Colab Notebooks folder.
 +
## Change directories to where your notebook will live:<syntaxhighlight lang=python>
 +
%cd /content/drive/MyDrive/Colab\ Notebooks/BasicLinalg
 +
</syntaxhighlight>Among other things, this will ensure that any files your notebook creates (graphs, for instance) will get saved to the right place in your Google Drive and not to the cloud.
 +
 
  
 
<!--
 
<!--

Latest revision as of 02:19, 23 January 2023

Introduction

This page focuses on using SymPy to find both the symbolic and the numeric solutions to equations obtained from electric circuits. The examples are available via a Google Drive at Basic Linear Algebra. If you have the Google Colaboratory app installed in your browser, you should be able to run the notebooks in your browser. If not, you can either install it or install a local program that can read notebook files such as Jupyter Notebooks, available with Anaconda.

Very Basic Example

The example code below assumes you are either running code in a notebook of some kind or typing it into a console. There is a finished example at the end of this section which also includes the commands to display different variables if you are using a script. Imagine you have the equation $$ax=d$$ and you want to solve for $$x$$. You can do this in SymPy as follows:

Initialization

You will need to import sympy to use symbolic calculations. Pratt Pundit will generally give that module the nickname sym:

import sympy as sym

Declare Variables

You will need to let Python know what your variables are. There are several ways to do this; the easiest is to use the sym.var() command with a string containing the variables you want separated by spaces:

sym.var('a x d')

Define Equations

When it comes to solving things later, there are two different ways to define an equation:

  • If you have an expression that evaluates to other than zero, you can use sym.Eq(left, right) for that. Given that we are trying to solve $$ax=d$$, you can write that in code as:
eqn1 = sym.Eq(a * x, d)
  • If the equation is equal to zero, you do not explicitly have to include the "=0" part; you can simply define a variable to hold on to the expression. For instance, in this case, we can re-write the equation we are trying to solve as $$ax-d=0$$ and just define a variable to hold on to the left side:
eqn1 = a * x - d

Solve Equations

There are two fundamentally different ways to solve one equation. If you give the solver the equation, it will return a list with the solution in it:

soln1 = sym.solve(eqn1, x)
soln1

will produce a list that contains $$d/a$$. On the other hand, if you give the solver a list with an equation in it, it will return a dictionary with the solution defined in it:

soln2 = sym.solve([eqn1], x)
soln2

will produce the dictionary $$\left\{x: \frac{d}{a}\right\}$$. Whenever you have more than one equation, you will need to collect the equations in a list or a tuple and the solver will return a dictionary. Given that, it is generally a good idea to always give the solver a list for the equations and a list for the unknowns, even if there is only one of each.

soln = sym.solve([eqn1], [x])
soln

Make Substitutions

Now that you have symbolic answers, you can make numerical substitutions for those symbols using the subs command. You will need to pull the appropriate definition out of the dictionary and then apply the substitutions to it. For example, to see what $$x$$ is when $$d$$ is 10, you can write:

soln[x].subs(d, 10)

If you want to see multiple substitutions, you can put the substitution pairs in tuples or lists that are contained in a tuple or list:

soln[x].subs([[a, 3], [d, 10]])

Complete Example

The code below has an additional piece, which is importing IPython.display as disp. This will allow you to display symbols in a formatted fashion within a script.

# Import sympy
import sympy as sym

# Print pretty
sym.init_printing()

# Use disp.display to use formatted printing
import IPython.display as disp
show = disp.display

# Declare symbols 
sym.var('a x d')

# Equations
eqn1 = sym.Eq(a * x, d)

# Solve
soln1 = sym.solve(eqn1, x)
show(soln1)

soln2 = sym.solve([eqn1], x)
show(soln2)

soln = sym.solve([eqn1], [x])
show(soln)

show(soln[x].subs(d, 10))

show(soln[x].subs([[a, 3], [d, 10]]))



Helper Functions

As you can see in the example above, there are some processes that look like they might get a little complicated as the number of equations increases. Given that, here is a set of helper functions that you may want to import into your script or notebook. Note: if you are using Google Colab, accessing secondary files takes a bit of work - this will be explained later. These functions are all in a file called sym_helper.py.

Imports

The sym_helper.py will need to import the sympy module. It will also attempt to import the IPython.display module. in order to make sym_helper.py compatible with applications like Trinket (which does not use IPython.display), sym_helper.py will see if it can import the module and then, based on that, decide how it will show things:

import sympy as sym

try:
  import IPython.display as disp
  show = disp.display
except:
  show = sym.pretty_print


Printing Out Solution Dictionary

Next, we may want help printing out the solutions to a set of equations. As long as you give solve a list of equations, you will get back a dictionary. If you are running your code in a notebook or in the console, typing soln by itself and hitting return will let you see a pretty version of the solution. If you put all this in a script, however, soln will not show up at all... You can put print(soln) in a script, but it will not be pretty. To make it pretty requires a little work since the solution set is a dictionary with the variables as keys. To help, here is a Python function called printout you can use:

def printout(solution, variables=None, fp=False):
  # Default case: print all variables
  if variables==None:
    variables = tuple(solution.keys())
  # Fixes issue if solving for a single item
  if not isinstance(variables, (list, tuple)):
    variables = [variables]
  for var in variables:
    show(var)
    if fp:
      show(solution[var].evalf(fp))
    else:
      show(solution[var])
    print()

This will go through the dictionary and print the variable followed by the solution for that variable. If you have substituted in numbers, set fp to an integer to do floating point evaluation on the answers. While a function like this may not seem necessary at the moment (with only one unknown variable, this feels like a lot of overhead), as you start solving problems with more and more unknowns it will be nice to have!

Making Substitutions

As you start working with more equations, you may end up having more and more symbols that you will want to be able to replace with numerical values later. Having to create a list of lists with the substitutions every time can certainly get old! Here is a function that will take a solution dictionary, a list of variables for which to substitute, and a list of the values to use for those variables. It returns a dictionary with the substitutions in place. Note that if it gets a list of equations rather than a dictionary, it will convert the list to a dictionary first. This is not something that is needed for linear algebra but will be something that is needed when setting up and solving simultaneous differential equations.

def makesubs(solution, vartosub, valtosub):
  subsol = solution.copy()
  sublist = list(zip(vartosub, valtosub))
  if type(subsol)==list:
    subsol = makedict(subsol)
      
  for var in subsol:
    subsol[var] = subsol[var].subs(sublist)
  return subsol

def makedict(sollist):
  d = {}
  for eqn in sollist:
    d[eqn.lhs] = eqn.rhs
  return d

Complete Example Extended, with Helpers

By carefully setting up your symbolic variables and by using the helper functions above, you can organize your code in a way that will be much more flexible for future assignments. First, instead of creating all of your symbolic variables at once, you can divide them into a collection of unknowns and a collection of knowns -- that will make it easier when you want Python to solve your symbolic equations. Second, you can create a list of the substitution values that you will be using later.

Note: the code below assumes that sym_helper.py is accessible. If you are using Google Colab, please see the section below on how to get that to work.

# Imports
import sympy as sym
from sym_helper import *

# Print pretty
sym.init_printing()

# Declare symbols (unknowns in first group, knowns in second)
# Create a list of future numerical values for knowns
unks = sym.var('x')
knowns = sym.var('a d')
subval = [10, 3]

# Equations
eqn1 = sym.Eq(a * x, d)

# Collect equations
eqns = [eqn1]

# Solve and display
sol = sym.solve(eqns, unks)
printout(sol)

# Perform substitutions
subsol = makesubs(sol, knowns, subval)
printout(subsol)

Google Colab and Personal Modules

Google Colab runs your files in the cloud; if you have extra modules that you need to access, you will need to make sure they are in the space that Google Colab is looking at. The following are two different ways to go about this:

Grab on the fly from GitHub

If you have a few modules that you need, you can ask Google Colab to see if it already knows what they are and, if not, to grab the text from a GitHub file and write it to a new file in your GitHub space. For instance, if you need access to the methods in thesym_helper.py, which lives at

https://tinyurl.com/mrgdemos/SymPy_Files/sym_helper.py

you can get it with the following lines of code:

# Import the helper functions
try:
  from sym_helper import *
except: # Get sym_helper.py from GitHub
  import requests
  url = 'https://tinyurl.com/mrgdemos/SymPy_Files/sym_helper.py'
  open('sym_helper.py', 'w').write(requests.get(url).text)
  from sym_helper import *

Grab from a folder on Google Drive

If you have the module you need stored in your Google Drive, you can ask Google Colab to grab it from there. There are several steps to this:

  1. Decide where all your files are going to go. Typically, Google Colab will create a folder called "Colab Notebooks" on your Google Drive. Best bet is to put everything there in some organized way.
  2. Decide if you want to have a common folder for help files. For EGR 224 in Spring of 2023, I have a folder called "Helpers" inside my "Colab Notebooks" folder, and I am planning to store all helper files there.
  3. Copy the helper files you need into that folder. The sym_help.py file will be available on Sakai in the Resources section. You can download it to your computer and then upload it to your Google Colab/Helpers folder using the web interface or you can install the Google Drive application for you computer so that you have direct access to your Google Drive files from Explorer / Finder.
  4. Decide where your notebook is going to be. The examples on this page are all in a folder I called "BasicLinalg" that is inside the "Colab Notebooks" folder. Note that whenever Colab creates a new notebook, it puts it in "Colab Notebooks" - you can move it wherever you want it to be later.
  5. In your notebook, you will need to do three things to get access to your Helper folder, to import functions from the helper file, and to have the notebook save things in the folder for the notebook:
    1. Connect the drive:
      from google.colab import drive
      drive.mount('/content/drive')
      
      Note that you will generally need to give Google permission to access your drive.
    2. Change directories and get helper functions:
      %cd /content/drive/MyDrive/Colab\ Notebooks/Helpers
      from sym_helper import *
      
      Note that the % in front of a command issues the command to your operating system; cd means "change directory." Your Google Drive is mounted at /context/drive/MyDrive, so this changes the directory to the Helpers folder inside of the Colab Notebooks folder.
    3. Change directories to where your notebook will live:
      %cd /content/drive/MyDrive/Colab\ Notebooks/BasicLinalg
      
      Among other things, this will ensure that any files your notebook creates (graphs, for instance) will get saved to the right place in your Google Drive and not to the cloud.