Difference between revisions of "Software tutorial/Scripts and functions"

From Process Model Formulation and Solution: 3E4
Jump to navigation Jump to search
m
 
(9 intermediate revisions by the same user not shown)
Line 1: Line 1:
{{Navigation|Book=Software tutorial|previous=Loops|current=Tutorial index|next=Vectors and arrays}}
== Scripts ==
== Scripts ==


Line 106: Line 107:
== Combining functions and scripts: building up your code ==
== Combining functions and scripts: building up your code ==


Functions, like scripts, can also be called from the command line.
MATLAB and Python have quite a different approach to functions, so they won't be described side-by-side here.  


Remember that functions should be self-contained logical pieces of code.  The general idea is that '''''a function should do one thing''''', and do it well.  Then you coordinate your functions from a script.
MATLAB's approach is that you have '''one''' script that coordinates your function(s).  Your script must be in a <tt>.m</tt> file, and here's the important point: ''each function must be in its own <tt>.m</tt> file'' also.
In Python, ''your script and all your functions can be in a single file''.
=== MATLAB details ===
Let's use the function we created earlier, <tt>energy.m</tt>, and call it from a script.  We reproduce all the code from above here:
'''<tt>energy_rate.m</tt>'''
<syntaxhighlight lang="matlab">
<syntaxhighlight lang="matlab">
D = distance(2.0,3.5)
function energy = energy_rate(f, T)
% Returns the energy rate into/out of the system.
% Units assumed: f = [m^3/s], T = [K].
rho = 1200;                  % [kg/m^3]
Cp = 4180;                  % [J/(kg.K)]
energy = rho * Cp * f * T;  % [J]
</syntaxhighlight>
</syntaxhighlight>
*The function will calculate the distance between (2.0,3.5) and the origin and put the result in the variable D
 
*Note that the function allows us to perform the distance calculation without previously assigning values to the variables x and y in the workspace
Now you could write this script, and call it '''<tt>example_script.m</tt>'''
*A function can assign multiple output variables (consult MATLAB help to find out how)
<syntaxhighlight lang="matlab">
*Functions can call other functions
% Calculates the energy flow into a system at 3 different conditions.
% September 2010, 3E4 course.
 
% Condition 1
f = 0.1;      % [m^3/s]
T = 341;      % [K]
disp(['The energy at condition 1 is = ', num2str(energy_rate(f, T)/1E6), ' MJ/s'])
 
% Condition 2
disp(['The energy at condition 2 is = ', num2str(energy_rate(0.2, 350)/1E6), ' MJ/s'])
 
% Condition 3
e3 = energy_rate(0.3, 360)/1E6;
disp(['The energy at condition 3 is = ', num2str(e3), ' MJ/s'])
</syntaxhighlight>
 
The above code shows different ways you can use function.  You should get the following output in MATLAB:
<syntaxhighlight lang="text">
>> example_script
The energy at condition 1 is = 171.0456 MJ/s
The energy at condition 2 is = 351.12 MJ/s
The energy at condition 3 is = 541.728 MJ/s
</syntaxhighlight>
 
=== Python details ===
 
Python lets you write your script and function all in one file.  Write the following script in your Python editor and save it as '''<tt>example_script.py</tt>'''
 
<syntaxhighlight lang="python">
"""
Calculates the energy flow into a system at different conditions.
September 2010, 3E4 course.
"""
 
def energy_rate(f, T):
    """
    Returns the energy rate into/out of the system.
    Units assumed: f = [m^3/s], T = [K].
    """
    rho = 1200              # [kg/m^3]
    Cp = 4180                # [J/(kg.K)]   
    return rho * Cp * f * T  # [J]
 
 
# Condition 1
f = 0.1      # [m^3/s]
T = 341      # [K]
print('The energy rate at condition 1 is = %f MJ/s' % (energy_rate(f, T)/1E6))
 
# Condition 2
print('The energy rate at condition 2 is = %f MJ/s' % (energy_rate(0.2, 350)/1E6))
 
# Condition 3
e3 = energy_rate(0.3, 360)/1E6
print('The energy rate at condition 3 is = %f MJ/s' % e3)
 
# Demonstrates a very powerful aspect of Python: named function inputs; returns the same value in every instance
e3_version1 = energy_rate(0.3, T=360)
e3_version2 = energy_rate(f=0.3, T=360)
e3_version3 = energy_rate(T=360, f=0.3)
</syntaxhighlight>
 
The above code shows different ways you can use function.  You should get the following output in Python:
<syntaxhighlight lang="python">
>>> execfile('example_script.py')
The energy rate at condition 1 is = 171.045600 MJ/s
The energy rate at condition 2 is = 351.120000 MJ/s
The energy rate at condition 3 is = 541.728000 MJ/s
</syntaxhighlight>
 
'''Note''': You can have multiple functions inside your Python script; just make sure they start with the word '''<tt>def</tt>''' and begin next to the left edge in the editor.

Latest revision as of 16:27, 26 September 2010

← Loops (previous step) Tutorial index Next step: Vectors and arrays →

Scripts

  • Scripts are a series of commands, saved in a .m or .py file.
  • When you run a script, it is as if you typed each line, in sequence, into MATLAB or Python.
  • It is good programming practice, and is required for this course, that all all your programs should run from a script.
    • It prevents you retyping in the commands if you need to change a variable's value
    • You must use scripts if you need to debug your program
    • Is helpful when you come back weeks or months later to figure out what you did (like revising for exams)
    • Can be shared with your colleagues for collaborative development.
  • All variables resulting from calculations performed in the script are available to you in the command window after the script is finished


A simple example of a script:

MATLAB: example.m Python: example.py
rho = 1200;   % [kg/m^3]
Cp = 4180;    % [J/(kg.K)]
f = 0.1;      % [m^3/s]
T = 341;      % [K]
energy = rho * Cp * f * T; % [J]
disp(['The energy is = ', num2str(energy/1E6), ' MJ/s'])

Now at the MATLAB command prompt you can type:

>> example
The energy is = 171.0456 MJ/s

Note: you do not type the >> characters - they are used in these tutorials to indicate that you should type the rest of the line in the MATLAB command window.

A simpler way to run your script is to click the "Play" button, or use the shortcut key displayed under the "Debug" menu: usually F7 on Windows computers.

rho = 1200    # [kg/m^3]
Cp = 4180     # [J/(kg.K)]
f = 0.1       # [m^3/s]
T = 341       # [K]
energy = rho * Cp * f * T # [J]
print('The energy is = %f MJ/s' % (energy/1E6))

From the Python command prompt:

>>> execfile('example.py')
The energy is = 171.045600 MJ/s

Note: you do not type the >>> characters - they are used in these tutorials to indicate that you should type the rest of the line in the Python command window.

A simpler way to run your script is to click the "Play" button in Python(x,y), or use the F9 shortcut key.

Functions

What if we needed to calculate the energy in at a different inlet temperature, T and at a different flow rate, f? We could edit our script and change the values of T and f and rerun it.

A better alternative is to write a function, which will accept these values and return the energy. A simple rule to remember: whenever you write code that is similar to code you have previously written - you should stop - and rather write a function.

MATLAB: energy_rate.m Python <no file required>
function energy = energy_rate(f, T)
% Returns the energy rate into/out of the system.
% Units assumed: f = [m^3/s], T = [K].

rho = 1200;                  % [kg/m^3]
Cp = 4180;                   % [J/(kg.K)]
energy = rho * Cp * f * T;   % [J]
  • MATLAB functions must create a variable with the same name as the variable that will be returned, in this case: energy.
def energy_rate(f, T):
    """
    Returns the energy rate into/out of the system.
    Units assumed: f = [m^3/s], T = [K].
    """
    rho = 1200               # [kg/m^3]
    Cp = 4180                # [J/(kg.K)]    
    return rho * Cp * f * T  # [J]
  • The code inside a Python function must be indented to indicate that it is part of the function. The variable that will be returned to the user need not be created - just use the return statement.

Note: It is good programming practice to start every function with a comment. The comment should be at least one line that describe what the function will do. Additional comments on the inputs are usually helpful.

In the above examples the name of the function is energy_rate and the input variables are f and T

  • In MATLAB only: the function must be in a .m file with the same name as the function.
  • In MATLAB only: file names must not have any spaces and cannot use - (minus) or other mathematical symbols in their name.
  • In MATLAB only: the output variable is energy

Combining functions and scripts: building up your code

MATLAB and Python have quite a different approach to functions, so they won't be described side-by-side here.

Remember that functions should be self-contained logical pieces of code. The general idea is that a function should do one thing, and do it well. Then you coordinate your functions from a script.

MATLAB's approach is that you have one script that coordinates your function(s). Your script must be in a .m file, and here's the important point: each function must be in its own .m file also.

In Python, your script and all your functions can be in a single file.

MATLAB details

Let's use the function we created earlier, energy.m, and call it from a script. We reproduce all the code from above here:

energy_rate.m

function energy = energy_rate(f, T)
% Returns the energy rate into/out of the system.
% Units assumed: f = [m^3/s], T = [K].
 
rho = 1200;                  % [kg/m^3]
Cp = 4180;                   % [J/(kg.K)]
energy = rho * Cp * f * T;   % [J]

Now you could write this script, and call it example_script.m

% Calculates the energy flow into a system at 3 different conditions.
% September 2010, 3E4 course.

% Condition 1
f = 0.1;      % [m^3/s]
T = 341;      % [K]
disp(['The energy at condition 1 is = ', num2str(energy_rate(f, T)/1E6), ' MJ/s'])

% Condition 2
disp(['The energy at condition 2 is = ', num2str(energy_rate(0.2, 350)/1E6), ' MJ/s'])

% Condition 3
e3 = energy_rate(0.3, 360)/1E6;
disp(['The energy at condition 3 is = ', num2str(e3), ' MJ/s'])

The above code shows different ways you can use function. You should get the following output in MATLAB:

>> example_script
The energy at condition 1 is = 171.0456 MJ/s
The energy at condition 2 is = 351.12 MJ/s
The energy at condition 3 is = 541.728 MJ/s

Python details

Python lets you write your script and function all in one file. Write the following script in your Python editor and save it as example_script.py

"""
Calculates the energy flow into a system at different conditions.
September 2010, 3E4 course.
"""

def energy_rate(f, T):
    """
    Returns the energy rate into/out of the system.
    Units assumed: f = [m^3/s], T = [K].
    """
    rho = 1200               # [kg/m^3]
    Cp = 4180                # [J/(kg.K)]    
    return rho * Cp * f * T  # [J]


# Condition 1
f = 0.1      # [m^3/s]
T = 341      # [K]
print('The energy rate at condition 1 is = %f MJ/s' % (energy_rate(f, T)/1E6))

# Condition 2
print('The energy rate at condition 2 is = %f MJ/s' % (energy_rate(0.2, 350)/1E6))

# Condition 3
e3 = energy_rate(0.3, 360)/1E6
print('The energy rate at condition 3 is = %f MJ/s' % e3)

# Demonstrates a very powerful aspect of Python: named function inputs; returns the same value in every instance
e3_version1 = energy_rate(0.3, T=360)
e3_version2 = energy_rate(f=0.3, T=360)
e3_version3 = energy_rate(T=360, f=0.3)

The above code shows different ways you can use function. You should get the following output in Python:

>>> execfile('example_script.py')
The energy rate at condition 1 is = 171.045600 MJ/s
The energy rate at condition 2 is = 351.120000 MJ/s
The energy rate at condition 3 is = 541.728000 MJ/s

Note: You can have multiple functions inside your Python script; just make sure they start with the word def and begin next to the left edge in the editor.